function ShowWarpedSectors
% function ShowWarpedSectors
%
% A utility to be used with the SectorAnalysisToolbox. This tool allows the
% user to select a stage of development. It then loads and displays the
% warped sectors for each sample in the stage onto the mean shape.
%
%
% Dr. A. I. Hanna, CMP & JIC, 2008.

% 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});
chooseimages = questdlg('Would you like to choose the images for each stage?','Choose images','Yes', 'No', 'No');

%um scale axes
prompt={'Pixel per um?', 'length of scale bar in um'};
dlg_title = 'Scale Bar Params';
numlines=1;
defaultanswer={'1','1'};
answer = inputdlg(prompt,dlg_title,numlines,defaultanswer);
scale = str2double(answer{1});
barLength = str2double(answer{2});

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
    figure(figh); hold on

    % 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
    secScale = 1;
    displayStageWarpedData(stagedir, samples, axish, salpha, secScale, mrow, mcol);
    axis(axish, 'image', 'ij');
      
    title(axish, ['All Sectors for Stage ' , stage]);
    set(gca, 'YDir', 'normal');
    
    drawScaleBar(scale,barLength);
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';
wh = waitbar(0,'Please wait...');
for i=1:length(samples)
    waitbar(i/length(samples),wh)
    fname = [stagedir, filesep, samples{i}, filesep, warpedfilename];
    if exist(fname, 'file')
        data = load(fname);
        data = data.warped_sectors;
        fprintf(' - art corner (%s)\n', samples{i});
        displayWarpedData(data, alpha, axish, scale, mrow, mcol);
    end
end
close(wh);
return
%%
%
function displayWarpedData(data, alpha, axish, scale, mrow, mcol)
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);
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

function drawScaleBar(scale,barLength)
[x,y] = ginput(1);
len = barLength/scale;
x(2) = x + len;
y(2) = y;
line(x,y,'color',[0 0 0],'linewidth',5)
return