function satlib_sectorStats2Excel(varargin)
% function satlib_sectorStats2Excel(varargin)
%
% Dr. A. I. Hanna, CMP, 2008.

% get the user selected sector filenames
[prjpath, stagedDirString, sector_files] = satlib_getSectorNames;
if isempty(sector_files)
    return;
end

% get the user selected excel file to save to
[xlsfilename, xlspathname] = uiputfile('*.xls', 'Pick an Excel-file', [pwd, filesep]);
if isequal(xlsfilename,0) || isequal(xlspathname,0)
    disp('User pressed cancel');
    return;
end

meansize = getMeanOrganSize;

origSheet{1, 1} = 'Mean Shape Size (Pixels)';
origSheet{1, 2} = meansize;

s = 2;
% setup the headings for the excel file.
origSheet{s, 1} = 'Directory';
origSheet{s, 2} = 'Image Name';
origSheet{s, 3} = 'Original Organ Area';
origSheet{s, 4} = 'Number Original Sectors';
origSheet{s, 5} = 'Average Original Sector Area (Pixels)';
origSheet{s, 6} = 'Variance Original Sectors';
origSheet{s, 7} = 'Proportion Covered by All Original Sectors';


warpedSheet{s, 1} = 'Directory';
warpedSheet{s, 2} = 'Image Name';
warpedSheet{s, 3} = 'Warped Organ Area';
warpedSheet{s, 4} = 'Number Warped Sectors';
warpedSheet{s, 5} = 'Average Warped Sector Area (Pixels)';
warpedSheet{s, 6} = 'Variance Warped Sectors';
warpedSheet{s, 7} = 'Proportion Covered by All Warped Sectors';
warpedSheet{s, 8} = 'Length of Average Warped Major Axis';
warpedSheet{s, 9} = 'Length of Average Warped Minor Axis';

filtSheet{s, 1} = 'Directory';
filtSheet{s, 2} = 'Image Name';
filtSheet{s, 3} = 'Warped Organ Area';
filtSheet{s, 4} = 'Number Filtered Sectors';
filtSheet{s, 5} = 'Average Filtered Sector Area (Pixels)';
filtSheet{s, 6} = 'Variance Filtered Sectors';
filtSheet{s, 7} = 'Proportion Covered by All Filtered Sectors';
filtSheet{s, 8} = 'Length of Average Filtered Major Axis';
filtSheet{s, 9} = 'Length of Average Filtered Minor Axis';
    

stats_waitbar_handle = waitbar(0,'Calculating statistics, please wait...');
N = length(sector_files);
for i=1:N
    waitbar(i/N,stats_waitbar_handle)
    filename = sector_files{i};
    fprintf('Processing file: %s\n', filename);
    
    stats = satlib_sectorFileToStats(prjpath, filename);
    [pathname, imname] = fileparts(filename);
    origSheet{i+s, 1} = pathname;
    origSheet{i+s, 2} = imname;
    origSheet{i+s, 3} = stats.origOrganSzPx;
    origSheet{i+s, 4} = stats.numSectors;
    origSheet{i+s, 5} = stats.avOrigSectorArea;
    origSheet{i+s, 6} = stats.varOrigSectorArea;
    origSheet{i+s, 7} = stats.propAreaOrig;
    
    warpedSheet{i+s, 1} = pathname;
    warpedSheet{i+s, 2} = imname;
    warpedSheet{i+s, 3} = stats.warpedOrganSzPx;
    warpedSheet{i+s, 4} = stats.numWarpedSectors;
    warpedSheet{i+s, 5} = stats.avWarpedSectorArea;
    warpedSheet{i+s, 6} = stats.varWarpedSectorArea;
    warpedSheet{i+s, 7} = stats.propAreaWarped;
    warpedSheet{i+s, 8} = stats.GmaxWarped;
    warpedSheet{i+s, 9} = stats.GminWarped;
    
    filtSheet{i+s, 1} = pathname;
    filtSheet{i+s, 2} = imname;
    filtSheet{i+s, 3} = stats.filteredOrganSzPx;
    filtSheet{i+s, 4} = stats.numFiltSectors;
    filtSheet{i+s, 5} = stats.avWarpedFiltSectorArea;
    filtSheet{i+s, 6} = stats.varWarpedFiltSectorArea;
    filtSheet{i+s, 7} = stats.propAreaWarpedFilt;
    filtSheet{i+s, 8} = stats.GmaxWarpedFilt;
    filtSheet{i+s, 9} = stats.GminWarpedFilt;

end
close(stats_waitbar_handle);
success = xlswrite([xlspathname, filesep, xlsfilename], origSheet, 'Original Sectors');
success = xlswrite([xlspathname, filesep, xlsfilename], warpedSheet, 'Warped Sectors');
success = xlswrite([xlspathname, filesep, xlsfilename], filtSheet, 'Filtered Sectors');
return;
%%
%
function meansize = getMeanOrganSize
meanshape = satio_load_mean_shape;
if ~isempty(meanshape)
    meansize = polyarea(meanshape(:,1), meanshape(:,2));
end
%%
%
function stats = initStatStructure
stats.origOrganSzPx = -1;
stats.warpedOrganSzPx = getMeanOrganSize;
stats.filteredOrganSzPx = getMeanOrganSize;


stats.numSectors = 0;
stats.avOrigSectorArea = 0;
stats.avWarpedSectorArea = 0;
stats.avWarpedFiltSectorArea = 0;

stats.varOrigSectorArea = 0;
stats.varWarpedSectorArea = 0;
stats.varWarpedFiltSectorArea = 0;
stats.GmaxWarped = 0;
stats.GminWarped = 0;
stats.numWarpedSectors = 0;


stats.propAreaOrig = 0;
stats.propAreaWarped = 0;
stats.propAreaWarpedFilt = 0;
stats.GmaxWarpedFilt = 0;
stats.GminWarpedFilt = 0;
stats.numFiltSectors = 0;

return
%%
%
function stats = satlib_sectorFileToStats(prjpath, filename)
stats = initStatStructure;
stats.origOrganSzPx = satlib_getOrganSz([prjpath, filesep, filename]);
stats = satlib_getSectorStats([prjpath, filesep, filename], stats);
return
%%
%
function stats = satlib_getSectorStats(fname, stats)
 stats = satlib_getOriginalSectorStats(fname, stats);
 stats = satlib_getWarpedSectorStats(fname, stats);
return
%%
%
function stats = satlib_getWarpedSectorStats(fname, stats)
[pathname] = fileparts(fname);

warped_orig_fname = [pathname, filesep, 'warped_sector_info_orig.mat'];
warped_fname = [pathname, filesep, 'warped_sector_info.mat'];
if ~exist(warped_orig_fname, 'file')
    warped_orig_fname = warped_fname;
end
if ~exist(warped_fname, 'file')
    return;
end
worig = load(warped_orig_fname);
if isfield(worig, 'warped_sector_info')
    worig = worig.warped_sector_info;
else
    worig = [];
end
[Gmax, Gmin, theta] = gtlib_growthTensor2Params(avGrowthTensor(worig));
stats.numWarpedSectors = length([worig.Area]);
stats.avWarpedSectorArea = mean([worig.Area]);
stats.varWarpedSectorArea = var([worig.Area]);
stats.GmaxWarped = Gmax;
stats.GminWarped = Gmin;

if (stats.warpedOrganSzPx>0)
    stats.propAreaWarped = sum([worig.Area])./stats.warpedOrganSzPx;
end

wfilt = load(warped_fname);
if isfield(wfilt, 'warped_sector_info')
    wfilt = wfilt.warped_sector_info;
else
    wfilt = [];
end
[Gmax, Gmin, theta] = gtlib_growthTensor2Params(avGrowthTensor(wfilt));
stats.numFiltSectors = length([wfilt.Area]);
stats.avWarpedFiltSectorArea = mean([wfilt.Area]);
stats.varWarpedFiltSectorArea = var([wfilt.Area]);
stats.GmaxWarpedFilt = Gmax;
stats.GminWarpedFilt = Gmin;
if (stats.filteredOrganSzPx>0)
    stats.propAreaWarpedFilt = sum([wfilt.Area])./stats.filteredOrganSzPx;
end
return
%%
%
function G = avGrowthTensor(winfo)
G = zeros(3,3);
for i=1:length(winfo)
    if isfield(winfo(i), 'growthTensor')
        G = G + winfo(i).growthTensor;
    end
end
G = G./length(winfo);
return

%%
%
function stats = satlib_getOriginalSectorStats(fname, stats)
if ~exist(fname, 'file')
    return;
end
sectorim = imread(fname);
if ~islogical(sectorim)
    fprintf(' - image %f should be logical \n', fname);
    return;
end
L = bwlabel(sectorim);
props = regionprops(L, 'Area');
sectorarea = [props.Area];
stats.numSectors = length(sectorarea);
stats.avOrigSectorArea = mean(sectorarea);
stats.varOrigSectorArea = var(sectorarea);
if (stats.origOrganSzPx>0)
    stats.propAreaOrig = sum(sectorarea)./stats.origOrganSzPx;
end
return
%%
%
function organSzPx = satlib_getOrganSz(fname)
organSzPx = -1;
fname = [fname(1:end-12), '_organ.tif'];
if ~exist(fname, 'file')
    return;
end
organbim = imread(fname);
if islogical(organbim)
    organSzPx = sum(organbim(:));
end
return
%%
%
function [prjpath, stagedDirString, sector_files] = satlib_getSectorNames
stagedDirString = 'Staged';
prjpath = pwd;
sector_files = FindFilenames('_sectors.tif', stagedDirString);

fprintf('Generating excel statistics file\n');
[s,v] = listdlg('PromptString','Select files to generate statistics:', ...
    'SelectionMode','multiple', 'ListSize', [600 300],...
    'ListString',sector_files);
if v == 0
    sector_files = [];
    return;
end
sector_files = sector_files(s);
return