% EVALSEGM Evaluating segmentation
%
% EVALSEGM(VALSTACKS,ADDMAN,ADDAUT,PRINTRESULTS) Evaluating the segmentation with
% name [IM VALSTACKS 'SUFFIX' 'OPTION'] in the current folder. 
% VALSTACKS is a row vector containing the numbering of the stacks to use.
% PRINTRESULTS = 1 : Printing results to file
% PRINTRESULTS = 0 : Not printing results to file
%
% Ex: evalsegm(60,'segmman','segmwat',1);
%
function [totman,totaut,totunion,segmman,segmaut,ncellsman,ncellsaut] = evalsegm(stackman,stackaut,plstart)

disp('Evaluating segmentation')

global conn       

% connectivitiy
conn = 6;

nstacks = numel(stackman);

teller = 0;
for i = 1 : nstacks
    
    
    teller = teller + 1;
  
    
    %
    % Manual solution
    %
    
    disp(sprintf('  Loading first solution %s',stackman{i}))
    D = load(stackman{i});         
    cellbw = D.cellbw;
    wat = D.wat;
    cellbw = cellbw(:,:,plstart(1):end);
    wat = wat(:,:,plstart(1):end);
    
%     dim = size(cellbw);
    
               
    % asssign value    
    watman = wat .* gt(cellbw,0);
    
    
    %
    % Automated solution
    %
    disp(sprintf('  Loading second solution %s',stackaut{i}))
    D = load(stackaut{i});         
    wat = D.wat;
    cellbw = D.cellbw;
    cellbw = cellbw(:,:,plstart(2):end);
    wat = wat(:,:,plstart(2):end);    
    
    % asssign value
    wataut = wat .* gt(cellbw,0);
%     showall(watman,wataut)
%     whos
    
    
%     showall(watman,wataut)
    
    % evaluate segmentation
    [totman,totaut,totunion,nman,naut] = dice(watman,wataut);
   
    % results for all images    
    ncellsaut(i,1) = naut;
    ncellsman(i,1) = nman;         
    totalman(i,1) = totman;
    totalaut(i,1) = totaut;
    totalunion(i,1) = totunion;    

    segmman{i} = watman;
    segmaut{i} = wataut;
    
end;

%
% Total success rated by the cells
%
ratio = ncellsman / sum(ncellsman);

% totalman
% totalaut
% totalunion
% ratio
totman = sum(totalman .* ratio);
totaut = sum(totalaut .* ratio);
totunion = sum(totalunion .* ratio);

% 
% if printresults    
%     name = ['stat' addaut '.mat'];
%     disp(sprintf('Saving results in %s',name))
%     save(name,'totman','totaut','totunion','totalman','totalaut','totalunion', ...
%               'valstacks','numcellsall','numcellsaut');
% else
%     disp('No results are saved')    
% end;

% print table with results
% printTable(numcellsAll,totallman,totallaut,totallunion);

%------------------------------------------------------

  
      
function [numval] = sortval(val,valUnique)

for i = 1 : size(valUnique,1)
    % the number of this value
    numval(i) = size(find(val == valUnique(i)),1);

end;

