% PSYCH 221
% Helmy Eltoukhy and Ali Ercan

% function im  = LSBS(picture);
% This function gets a multicapture image (picture) and applies last sample 
% before saturation algorithm to get high DR image (im)

function im  = LSBS(picture);

% Cut the "white corner" caused by the imager
picture = picture(2:end,40:end,1:end); 

[m n T] = size(picture);
ind = zeros(m,n); % The index of last valid capture value for pixel i,j
for i=1:m
    for j=1:n
        pix_charge = picture(i,j,:);
        % For pixel i,j, find the values that are less than 230 (not 255, 
        % order to avoid pixels that wrongly go back to 0, after saturation 
        % due to a bug in the imager. (They cause sparkle like blck dots in
        % the saturated ares.)) and take the last valid one, scale for exposure 
        % time differerence, and record its index to ind(i,j)
        temp = min(find(pix_charge > 230)); 
        if isempty(temp)
            im(i,j) = pix_charge(T)-pix_charge(1); % substract first one for CDS
            ind(i,j) = T;
        else
            ind(i,j) = temp;
            im(i,j) = (T-1)/(ind(i,j)-2)*(pix_charge(ind(i,j)-1)-pix_charge(1));
        end
    end
end
im(find(im<0)) = 0;     % Correct for false negative values. These need to come
                        % from very dark pixels, as you subtract pix_charge(1)
                        % from its last valid value, if it ends up negative 
                        % due to pixel noise, it should have been zero, we should
                        % correct for them
min(min(ind)) % Display min "last sample before sat. index" for that image for 
            % control purposes

% there is a bad pixel in upper right corner of the image which 
% gives unnaturally high value. Replace it with the mean of its two neighbors.
imx = im(1:80,250:end);
badind = find(imx>1000)
if length(badind)>1
    error('bad index more than 1')
end

imx(badind) = .5*(imx(badind-1)+imx(badind+1));
im(1:80,250:end) = imx;

return;

        