%Hanna, 2005

function [shape, value] = AlignShape(varargin)
error(nargchk(0,inf,nargin));
ad.value = 0;
ad.mean_shape = [];
ad.angle = 0;
% if (mod(length(varargin),2) ~= 0) & (length(varargin)<6)
%     % input args have not com in pairs, woe is me
%     error('Arguments to LISTDLG must come param/value in pairs.')
% end
% for i=1:2:length(varargin)
%     switch lower(varargin{i})
%         case 'shape'
%             ad.mean_shape = varargin{i+1};      
%         otherwise
%             error(['Unknown parameter name passed to AlignShape.  Name was ' varargin{i}])
%     end
% end
% if isempty(ad.mean_shape)
%     error('Algorithm directory parameter is required.')
% end
% Open, move, and get the handles from the figure file.
fig = openfig(mfilename, 'reuse');
% Move the gui and then show it, rather than have it jump all over the
% place.
movegui(fig, 'center');
set(fig, 'visible', 'on');
handles = guihandles(fig);
% Set all the callback functions
set(fig, 'WindowButtonDown', {@doMouseClicked});
set(fig, 'WindowButtonUp', {@doMouseReleased});
set(handles.ok_btn, 'callback', {@doOk});


% Initialize the application data structure
% Initialize the application data structure
ad.figMain = fig;
ad.StagedDirString = 'Staged';
ad.OriginalsDirString = 'Originals';
ad.ProcessedDirString = 'Processed';
ad.DataDirString = [ad.StagedDirString, filesep, 'Data'];
if ~exist(ad.DataDirString, 'dir'); mkdir(ad.DataDirString); end;
ad.projectpath = pwd;
ad.sector_files = FindFilenames('_sectors_warped.tif', ad.StagedDirString);
if length(ad.sector_files)==0
    delete(fig);
    return;
end
if ~exist([ad.DataDirString, filesep, 'mean_shape.mat'], 'file')
    file = ad.sector_files{1};
    [path, file, ext, vers] = fileparts(file);
    ad.mean_shape = load([path, filesep, 'edge_xy.mat']);
    ad.mean_shape = ad.mean_shape.E;
    mean_shape = ad.mean_shape;
    save([ad.DataDirString, filesep, 'mean_shape.mat'], 'mean_shape');
    clear mean_shape;
else
    ad.mean_shape = load([ad.DataDirString, filesep, 'mean_shape.mat']);
    ad.mean_shape = ad.mean_shape.mean_shape;
end

ad.value = 0;
ad.handles = handles;

ad.mean_shape_handle = [];
setappdata(0,'AlignShapeData',ad);
doPlotShape;

try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end
if isappdata(0,'AlignShapeData')
    ad = getappdata(0,'AlignShapeData');
    value = ad.value;
    rmappdata(0,'AlignShapeData')
else
    % figure was deleted
    value = 0;
end
return;

function init_gui()
ad =getappdata(0, 'AlignShapeData');

ad.mean_shape_handle = plot(ad.handles.image_axis, ad.mean_shape(:,2), ad.mean_shape(:,1), 'o-', 'MarkerEdgeColor', 'y', 'MarkerFaceColor', 'r');
grid(ad.handles.image_axis, 'on');
axis(ad.handles.image_axis, 'image', 'ij');
set(ad.handles.image_axis, 'XTick', [], 'YTick', [], 'XTickLabel', [], 'YTickLabel', [], 'Color', [0 0 0]);
return;

function doMouseMove(fig, evd)
ad =getappdata(0, 'AlignShapeData');
cp = get(ad.figMain, 'CurrentPoint');
cp = cp(1,1:2);

dy = (ad.PointToMove(2) - cp(2));
if(dy > 0)
    theta = 0.1;
elseif(dy < 0)
    theta = -0.1;
else
    theta = 0;
end
ad.angle = ad.angle + theta;
ax = cos(theta);
ay = sin(theta);
m = ones(size(ad.mean_shape,1),1)*mean(ad.mean_shape, 1);
ad.mean_shape = ad.mean_shape - m;
R = [ax -ay; ay ax];
ad.mean_shape = (R*ad.mean_shape')' + m;
ad.PointToMove = cp;
setappdata(0, 'AlignShapeData', ad);
doPlotShape;
%set(ad.mean_shape_handle, 'XData', ad.mean_shape(:,1), 'YData', ad.mean_shape(:,2));

function doPlotShape()
ad =getappdata(0, 'AlignShapeData');
if isempty(ad.mean_shape)
    return;
end
if ishandle(ad.mean_shape_handle); delete(ad.mean_shape_handle); end;
ad.mean_shape_handle = plot(ad.handles.image_axis, ad.mean_shape(:,2), ad.mean_shape(:,1), 'o-', 'MarkerEdgeColor', 'y', 'MarkerFaceColor', 'r');
axis(ad.handles.image_axis, 'image', 'ij');
set(ad.handles.image_axis, 'XTick', [], 'YTick', [], 'XTickLabel', [], 'YTickLabel', [], 'Color', [0 0 0]);

function doMouseClicked(fig, evd)
ad =getappdata(0, 'AlignShapeData');
cp = get(ad.figMain, 'CurrentPoint');
cp = cp(1,1:2);
ad.PointToMove = [cp(1) cp(2)];
setappdata(0, 'AlignShapeData', ad);
set(ad.figMain, 'WindowButtonMotionFcn', {@doMouseMove});


disp('clicked');

function doMouseReleased(fig, evd)
ad =getappdata(0, 'AlignShapeData');
set(ad.figMain, 'WindowButtonMotionFcn', '');
disp('released');

function doOk(ok_btn, evd)
ad =getappdata(0, 'AlignShapeData');
ad.value = 1;
rotateAlignedEdges;

setappdata(0, 'AlignShapeData', ad);
delete(gcbf);

function rotateAlignedEdges()
ad =getappdata(0, 'AlignShapeData');
theta = ad.angle;
R = rotmat(theta);
for i=1:length(ad.sector_files)
    file = ad.sector_files{i};
    [path, file, ext, vers] = fileparts(file);
    if exist([path, filesep, 'warped_sectors_xy.mat'], 'file')
        sectors = load([path, filesep, 'warped_sectors_xy.mat']);
        sectors = double(sectors.warped_sectors);
        sectors = sectors - ones(size(sectors,1),1)* mean(ad.mean_shape);
        
       warped_sectors = round((R*sectors')' + ones(size(sectors,1),1)* mean(ad.mean_shape));
       
        warped_sectors_im = zeros(max(warped_sectors(:,1))+20, max(warped_sectors(:,2))+20);
        for j=1:size(warped_sectors,1);
            warped_sectors_im(round(warped_sectors(j, 1)), round(warped_sectors(j, 2))) = 1;
        end;

        warped_sectors_im = bwfill(warped_sectors_im, 'holes');
        warped_sectors_im = imclose(warped_sectors_im, strel('disk', 1));
        imwrite(warped_sectors_im, [path, filesep, file, '_warped.tif'], 'TIFF');
        warped_sectors = round(warped_sectors);
        save([path, filesep, 'warped_sectors_xy.mat'], 'warped_sectors');
        %L = bwlabel(warped_sectors_im);
        %warped_sector_info = regionprops(L, 'Centroid', 'MajorAxisLength', 'MinorAxisLength', 'Area', 'Orientation');
        warped_sector_info = calc_region_props(warped_sectors_im);
        save([path, filesep, 'warped_sector_info.mat'], 'warped_sector_info');
       
       
        
        
        figure(1); cla;
        plot(sectors(:,1), sectors(:,2), '.'); hold on
        plot(ad.mean_shape(:,1), ad.mean_shape(:,2), 'go')
    end
end
return;
