function [pixsum_center,pixsum_spread,pixsum_n] = confocal_pixsum(tstack,iscrs,varargin)
%% [pixsum,pixsum_sem] = confocal_pixsum(tstack,iscrs,...)
% This function calculates the sum of the pixel intensities over each of
% the confocal microscope data frames.
% 'iscrs' is the optional array.

%% Parse the input
narginchk(1,Inf); nargoutchk(1,3);

% Parse options
spec = {'verbosity', true;
        'plot',false;
        'center',@(x) mean(x);
        'spread',@(x) std(x)./sqrt(length(x)/2);
        };
opt = Confocal_varargin2opt(varargin,spec);

if nargin < 2 || isempty(iscrs)
    iscrs = true(size(tstack(:,:,1)));
end
assert(isequal(size(tstack(:,:,1)),size(iscrs)),'Input has an invalid size');

%% Sum over all the pixels
n = size(tstack,3); % Assumimg that tstack hasn't been permuted

pixsum_center = zeros(1,n); % Pixel sum
pixsum_spread = zeros(1,n); % Standard error of the mean
pixsum_n = repmat(sum(iscrs),1,n); % # of pixels summed <- WIP. Kindof redundant at the moment

center_fun = opt.center;
spread_fun = opt.spread;

nans_found = false;
if opt.verbosity, Confocal_tpbar('Adding tstack pixels'), end
for j = 1:n
    if opt.verbosity, Confocal_tpbar(j/n), end
    frame = tstack(:,:,j);
    frame = double(frame); % Make sure is double-precision float
    frame(~iscrs) = []; % Remove non-crystal
    frame = frame(:); % Reshape into 1d vector
    nans = isnan(frame);
    if any(nans)
        frame = frame(~nans);
        nans_found = true;
    end
    pixsum_center(j) = center_fun(frame);
    pixsum_spread(j) = spread_fun(frame);
end
if opt.verbosity, Confocal_tpbar(), end

if opt.verbosity && nans_found
    warning('Found some nans in the frames');
end

if opt.plot
    % Open figure
    fh = findobj(0,'Name',mfilename);
    if ~isempty(fh)
        figure(fh);
    else
        figure('Name',mfilename);
    end
    clf;
    
    axes;
    plot(pixsum_center);
    grid on;
    ylabel('Average intensity');
    xlabel('frame number');
    
    commandwindow; % Return control to command window
end
end