function ExportSectorNumbersToExcel(varagin)

[prjpath, grid_file, gridpath] = satlib_getGridsName;
[prjpath, stagedDirString, stagesString,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



origSheet{1, 1} = 'Mean Shape Size (Pixels)';
 
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} = 'Number Warped Sectors';
origSheet{s, 6} = 'Number Filtered Sectors';

%warped area display at top;

% StageHistSheet{s, 1} = 'Directory';
% StageHistSheet{s, 2} = 'Stage';
% StageHistSheet{s, 3} = 'Warped Sector Number';
% StageHistSheet{s, 4} = 'Filtered Sector Number';


RegionHistSheet{1, 1} = 'Directory';
RegionHistSheet{s, 1} = 'Region';
RegionHistSheet{1, 5} = 'Stage Sector Number';
for i=1:size(stagesString,2)
RegionHistSheet{s, 1+i} =  char(stagesString{:,i});
end 


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{1, 2} = stats.warpedOrganSzPx;
    
    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.numWarpedSectors;
    origSheet{i+s, 6} = stats.numFiltSectors;
end
close(stats_waitbar_handle);
       
    stats = satlib_gridFileToStats(gridpath, grid_file);
    RegionHistSheet{1,2} = strcat(gridpath, '\', grid_file);
    regionl = length(stats.stage_density{1}.density.prev);
    for j=1:length(stats.stage_density) 
        for i=1:regionl
           RegionHistSheet{s+i,1+j} = stats.stage_density{j}.density.prev(i);
           RegionHistSheet{s+i,1} = i; 
        end
        RegionHistSheet{s+i+1,1+j} = sum(stats.stage_density{j}.density.prev);
    end
   RegionHistSheet{s+i+1,1} = 'Total';
     
     
success = xlswrite([xlspathname, filesep, xlsfilename], origSheet, 'Sectors Overview');
%success = xlswrite([xlspathname, filesep, xlsfilename], StageHistSheet, 'Sector Number per Stage');
success = xlswrite([xlspathname, filesep, xlsfilename], RegionHistSheet, 'Sector Number per Region');
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_gridFileToStats(gridpath,grid_file);

    fprintf('Processing file: %s\n', grid_file);
hist_sectors = load(strcat(gridpath, '\', grid_file)); 
stats.stage_density = hist_sectors.stage_grids;
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

stats.numWarpedSectors = length([worig.Area]);

wfilt = load(warped_fname);
if isfield(wfilt, 'warped_sector_info')
    wfilt = wfilt.warped_sector_info;
else
    wfilt = [];
end
stats.numFiltSectors = length([wfilt.Area]);
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);
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, stagesString, sector_files]= satlib_getSectorNames
stagedDirString = 'Staged';
prjpath = pwd;
sector_files = FindFilenames('_sectors.tif', stagedDirString);
stage_names = [];
stagesString = struct2cell(dir(strcat(pwd,'\Staged')));
stagesString = stagesString(1,4:size(stagesString,2));
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);
for i=1:size(sector_files,2)
    matches(i,:) = regexp(sector_files{i},stagesString,'match');
end
stages = find(cellfun('prodofsize', matches));
    
l = 1;
stagesString =cellstr('test1');
for k=1:length(stages)
    matching = 0; 
    for m=1:length(stagesString)
    hmatch = regexp(stagesString{m}, matches{stages(k)}, 'match');
    matching =  matching + sum(cellfun('prodofsize',hmatch));
    end
    if  matching == 0
    stagesString{l}= matches{stages(k)};
    l = l+1;
    end
end

% gaps = find(cellfun('prodofsize', stagesStrang));
% for k=1:length(gaps)    
% stagesString(k) = stagesStrang{gaps(k)}; 
% end
return
%%
%
function [prjpath, grid_file, gridpath] = satlib_getGridsName
gridDirString = 'Staged\Data\Grids';
prjpath = pwd;
gridpath = strcat(prjpath, '\',gridDirString);
cd(gridpath);
grid_file = uigetfile('*.mat');
cd(prjpath);
fprintf('Generating excel statistics file\n');
return

return