function ShowWarpedEllipses

% function ShowWarpedEllipses
%
% A utility to be used with the SectorAnalysisToolbox. This tool allows the
% user to select a stage (or several) of development. It then loads and displays the
% warped ellipses for each sector for each sample in the stage onto the mean shape.
%
%
% Dr. A. I. Hanna, CMP & JIC, 2008. Modified by Erika, 2009.

% initialize some paths
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});

% 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});


chooseimages = questdlg('Would you like to choose the images for each stage?','Choose images','Yes', 'No', 'No');


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 up the figure and the axis
    axish = subplot(M, N, indx); indx = indx + 1;
    hold(axish, 'on');

    % load and display the mean shape as a patch object
    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');
    %axis off;

    
    % load and display the warped sectors ontop of the mean shape
    displayStageWarpedData(stagedir, samples, axish, salpha, scale, mrow, mcol);
    axis(axish, 'image', 'ij');
    %axis off;
    
    title(axish, ['All Ellipses for Stage ' , stage]);
    set(gca, 'YDir', 'normal');
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 displayStageWarpedData(stagedir, samples, axish, alpha, scale, mrow, mcol)
warpedfilename = 'warped_sectors_xy.mat';
warpedname = 'warped_sector_info.mat';
for i=1:length(samples)
    fname = [stagedir, filesep, samples{i}, filesep, warpedfilename];
    wname = [stagedir, filesep, samples{i}, filesep, warpedname];
    if exist(fname, 'file')
        data = load(fname);
        data = data.warped_sectors;
        worig = load(wname);
        worig = worig.warped_sector_info;
        fprintf(' - art corner (%s)\n', samples{i});
        displayWarpedData(data, alpha, axish, scale, mrow, mcol, worig); 
    end
end
return
%%

function displayWarpedData(data, alpha, axish, scale, mrow, mcol, worig)
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);
        [major, minor, theta] = gtlib_growthTensor2Params(worig(i).growthTensor);
        r.Orientation = theta;
        r.MajorAxisLength = major;
        r.MinorAxisLength = minor; 
        r.Centroid = worig(i).Centroid;
        r.growthTensor = worig(i).growthTensor;
        r.Area = worig(i).Area;
        [eh, epts] = plot_ellipse(axish,r);
        
        z = zeros(size(epts,2),1);
         sh = patch(epts(1,:), epts(2,:), z, 'FaceColor', col, ...
        'EdgeColor', edgecol, 'Parent', axish, 'FaceAlpha', alpha);
end
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