% function to output the distances from each sector from the tip or the
% base to excel together with the size of the sector. 
function SaveSectorAreaToExcel
 
stageddir = [pwd, filesep, 'Staged'];
datadir = [stageddir, filesep, 'Data'];

% get the stages for this project.
stages = getstages(stageddir);

% ask the user to select a stage to display
stageid = getStageId(stages);
if isempty(stageid)
    return;
end

% get the desired number of rows and cols per figure
prompt={'Number of rows:','Number of cols:'};
name='Number of Axes';
numlines=1;
defaultanswer={'1','1'};
answer=inputdlg(prompt,name,numlines,defaultanswer);
M = str2double(answer{1});
N = str2double(answer{2});

figh = figure;
indx = 1;
% get the samples for a particular stage
stages = stages(stageid);
facecol = uisetcolor('Organ Colour');
if facecol==0
    facecol = [0 0.5 0.25];
end
prompt={'Organ Transparancy (0-1):', 'Sector Transparancy (0-1):'};
name='Alpha';
numlines=1;
defaultanswer={'0.3', '0.7'};
answer = inputdlg(prompt,name,numlines,defaultanswer);

alpha=str2double(answer{1});
salpha=str2double(answer{2});
chooseimages = questdlg('Would you like to choose the images for each stage?','Choose images','Yes', 'No', 'No');

% um scale axes
prompt={'Scale in um? (Enter 1 for pixel scale)'};
name='Scale';
numlines=1;
defaultanswer={'1'};
answer = inputdlg(prompt,name,numlines,defaultanswer);
scale = str2double(answer{1});

for i=1:length(stages)
    stage = stages{i};
    fprintf(' - user selected stage %s\n', stage);
    stagedir = [stageddir, filesep, stage];
    samples = getStageSamples(stagedir);

    if strcmpi(chooseimages, 'yes')
        [s,v] = listdlg('PromptString','Select images:',...
            'SelectionMode','multiple',...
            'ListString',samples);
        if ~isempty(s)
            samples = samples(s);
        end
    end
    %% the art corner
    if indx>(M*N)
        indx = 1;
        figh = figure;
    end

    set(0, 'CurrentFigure', figh);
    % set up the figure and the axis
    axish = subplot(M, N, indx); indx = indx + 1;
    hold(axish, 'on');

% load the mean shape and find the positions of the base and the tip.  
    meanshape = satio_load_mean_shape;
    meanshape = meanshape*scale;
    mrow = min(meanshape(:,1));
    mcol = min(meanshape(:,2));
    meanshape(:,1) = meanshape(:,1) - mrow;
    meanshape(:,2) = meanshape(:,2) - mcol;
    displayMeanShape(meanshape, axish, facecol, alpha);
    axis(axish, 'image', 'ij');


% ms = satio_load_mean_shape;
% ms = ms*scale;
% figure, plot(ms(:,1),ms(:,2),'k+');
% hold on;
% m1 = find(ms(:,1)==max(ms(:,1)));
% m2 = find(ms(:,1)==min(ms(:,1)));
% plot(ms(m1,1), ms(m1,2), 'g+');hold on;
% plot(ms(m2,1), ms(m2,2), 'r+'); hold on;


% load and display the warped sectors ontop of the mean shape
  d = displayStageWarpedData(stagedir, samples, axish, salpha, scale, mrow, mcol);
  axis(axish, 'image', 'ij');
   
    
  title(axish, ['All Sectors for Stage ' , stage]);
  set(gca, 'YDir', 'normal');
  
% output to excel: File name, area, distance from tip,
% distance from base
exportExcelData(d)

end
return;

function displayMeanShape(meanshape, axish, facecol, alpha)
if isempty(meanshape)
    return;
end
meanshape(end+1,:) = meanshape(1,:);
%facecol = [0 0.5 0.25];
edgecol = [0 0 0];
z = zeros(size(meanshape,1),1);
sh = patch(meanshape(:,2), meanshape(:,1), z, 'FaceColor', facecol, ...
    'EdgeColor', edgecol, 'Parent', axish, 'FaceAlpha', alpha);
return

function d = displayStageWarpedData(stagedir, samples, axish, alpha, scale, mrow, mcol)
warpedfilename = 'warped_sectors_xy.mat';
warpedinfo = 'warped_sector_info.mat';
l = 1;
d = [];

wh = waitbar(0,'Please wait...');
for i=1:length(samples)
    waitbar(i/length(samples),wh)
    fname = [stagedir, filesep, samples{i}, filesep, warpedfilename];
    finfo = [stagedir, filesep, samples{i}, filesep, warpedinfo];
    
    if exist(fname, 'file')
        data = load(fname);
        data = data.warped_sectors;
        dinfo = load(finfo);
        dinfo = dinfo.warped_sector_info;  
        name = samples{i}; 
        fprintf(' - art corner (%s)\n', samples{i});
        [d, l] = displayWarpedData(data, dinfo, alpha, axish,scale, mrow, mcol, l, d, name);
    end
end
close(wh);
return

function [d, l] = displayWarpedData(data, dinfo, alpha, axish,scale, mrow, mcol, l, d, name)
col = rand(1,3);
edgecol = [0 0 0];
edgecol = 'none';
for i=1:length(data)
     pts = data{i}*scale;
     pts(:,1) = pts(:,1) - mrow;
     pts(:,2) = pts(:,2) - mcol;
    z = zeros(size(pts,1),1);
    sh = patch(pts(:,2), pts(:,1), z, 'FaceColor', col, ...
        'EdgeColor', edgecol, 'Parent', axish, 'FaceAlpha', alpha);
    
    % find distance betweent the points
    d(l).name = name;
    p = [dinfo(i).Centroid(1)*scale-mcol, dinfo(i).Centroid(2)*scale-mrow];
    d(l).CentroidX = p(1);
    d(l).CentroidY = p(2);
    d(l).Area = dinfo(i).Area*(scale^2);
    
    % plot area information where the centroid normally is. 
    text(p(1)-10,p(2),num2str(d(l).Area), 'Parent', axish);
    l=l+1;
end
return


function exportExcelData(d)
current = {pwd};
cd(['Staged', filesep, 'Data']);
path = uiputfile('SectorAreaData','Save to excel spreadsheet');

s = 1;
t = 1;
sheet{1, t} = 'Name';
sheet{1, t+1} = 'Area (um2)';
sheet{1, t+2} = 'Centroid X';
sheet{1, t+3} = 'Centroid Y';

for j=1:size(d,2)
sheet{s+j, t} = d(j).name;
sheet{s+j, t+1} = d(j).Area;
sheet{s+j, t+2} = d(j).CentroidX;
sheet{s+j, t+3} = d(j).CentroidY;
end

xlswrite(path,sheet);
cd(current{1});
return   
     
function stageid = getStageId(stages)
[stageid,v] = listdlg('PromptString','Select a stage:',...
    'SelectionMode','multiple',...
    'ListString',stages);
return
%%
%
function stages = getstages(stageddir)
stages = dir(stageddir);
stages = {stages.name};
ind = [];
for i=1:length(stages)
    stage = stages{i};
    if strcmpi(stage(1), '.') || strcmpi(stage, 'Data')
        ind = cat(1, ind, i);
    end
end
stages(ind) = [];
return
%%
%
function files = getStageSamples(stagedir)
files = dir(stagedir);
files = {files.name};
ind = [];
for i=1:length(files)
    file = files{i};
    if strcmpi(file(1), '.')
        ind = cat(1, ind, i);
    end
end
files(ind) = [];
return