function [ low_high ] = image_stretchlim( img, tol )
%IMAGE_STRETCHLIM Summary of this function goes here
%   Detailed explanation goes here

    if(nargin == 1)
        low_count = 0.01;
        high_count = 0.01;
    else
        if(isscalar(tol))
            if(tol < 0 || tol >=0.5)
                error('tol out of bounds');
            end
            low_count = tol;
            high_count = tol;
        elseif(isvector(tol))
            if(length(tol) ~= 2)
                error('tol must be of length 2');
            end
            low_count = tol(1);
            high_count = tol(2);
        else
            error('tol contains an invalid value');
        end 
    end
    
    simage = size(img);
    
    psimage = prod(simage(1:2));
    low_count = low_count*psimage;
    high_count = high_count*psimage;
    
    if(low_count == 0 && high_count == 0)
        low_high = [min(img(:));max(img(:))];
        return;
    else
    
        sorted = sort(img(:));

        low = sorted(round(low_count+1));
        pos = find(sorted>low);
        if(~isempty(pos))
            low2 = sorted(pos(1));
            d1 = low_count - sum(sorted < low);
            d2 = sum(sorted < low2)-low_count;
            if(d2<d1)
                low=low2;
            end
        end
        
        high = sorted(end-round(high_count));
        pos = find(sorted < high);
        if(~isempty(pos))
            high2 = sorted(pos(end));
            d1 = high_count - sum(sorted > high);
            d2 = sum(sorted > high2)-high_count;
            if(d2<d1)
                high=high2;
            end
        end
        
        low_high = [low;high];
    end
    
    



end

