%Hanna, 2005
function [value] = OptimiseGridTool(varargin)
if checkSATDir(pwd) == 0
    fprintf('You are not in a valid SectorAnalysisToolbox Project directory\n');
    return;
end
error(nargchk(0,inf,nargin));
% Open, move, and get the handles from the figure file.
fig = openfig(mfilename, 'reuse');
movegui(fig, 'center');
set(fig, 'Visible', 'on');
handles = guihandles(fig);
% Set all the callback functions
set(handles.load_ungrown_shape_btn, 'callback', {@doLoadUngrownShape});
set(handles.zoom_btn, 'callback', {@doZoom});
set(handles.pan_btn, 'callback', {@doPan});
set(handles.auto_grid_btn, 'callback', {@doAutoGrid});
set(handles.warp_grid_btn, 'callback', {@doWarpGridToMeanShape});
set(handles.edit_edge_btn, 'callback', {@doEditEdgePoints});
set(handles.concavity_check_btn, 'callback', {@doConcavityCheck});
% Toggle Callbacks
set(handles.toggle_mean_shape, 'callback', {@doToggleMeanShape});
set(handles.toggle_internal_spring, 'callback', {@doToggleInternalSpring});
set(handles.toggle_external_spring, 'callback', {@doToggleExternalSpring});
set(handles.toggle_centroids, 'callback', {@doToggleCentroids});
set(handles.toggle_grid, 'callback', {@doToggleGrid});
set(handles.load_grid_btn, 'callback', {@doLoadGrid});

set(handles.save_grid_btn, 'callback', {@doSaveGrid});



% Initialize the application data structure
ad.figMain = fig;
ad.StagedDirString = 'Staged';
ad.OriginalsDirString = 'Originals';
ad.ProcessedDirString = 'Processed';
ad.RegionDirName = 'RegionData';
ad.DataDir = [ad.StagedDirString, filesep, 'Data'];
ad.GridDir = [ad.DataDir, filesep, 'Grids'];
ad.UngrowthDataDir = [ad.DataDir, filesep, 'UngrowthData'];
if ~exist(ad.GridDir, 'dir') mkdir(ad.GridDir); end;
ad.MeanShapeName = [ad.DataDir, filesep, 'mean_shape.mat'];
ad.shape = [];
ad.regions.R = [];
ad.regions.vertex = [];
ad.regions.edge = [];
ad.regions.edge_petal = [];
ad.regions.grid_xy = [];
ad.regions.centroids = [];
ad.regions.xy_regions = [];
ad.region_size_threshold = 0.33;
ad.grid_plot_handle = [];
ad.vertex_plot_handle =[];
ad.mean_shape_plot_handle =[];
ad.edge_plot_handle = [];
ad.spring_marker_handle = [];
ad.spring_line_handle = [];
ad.spring_text_handle = [];
ad.edge_marker_handle = [];
ad.edge_line_handle = [];
ad.edge_text_handle = [];
ad.centroid_plot_handle = [];
ad.projectpath = pwd;
ad.value = 0;
ad.handles = handles;

if ~exist(ad.MeanShapeName, 'file')
    fprintf('There is no mean shape to align a grid to, aborting!\n');
    delete(fig)
    return;
else
    ad.mean_shape = load(ad.MeanShapeName);
    ad.mean_shape = ad.mean_shape.mean_shape;
end
setappdata(0,'OptimiseGridToolData',ad);
init_gui();

%doUpdateGridList();
%doChangeGrid(ad.handles.grid_popup);

try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end
value = 0;
return;

function [] = init_gui()
ad =getappdata(0, 'OptimiseGridToolData');
%I = zeros(ceil(max(ad.mean_shape(:,1)))+ceil(min(ad.mean_shape(:,1))),ceil( max(ad.mean_shape(:,2)))+ceil( min(ad.mean_shape(:,2))));
%I = roipoly(I, ad.mean_shape(:,2), ad.mean_shape(:,1));
%imagesc(I, 'Parent', ad.handles.imageAxis); hold(ad.handles.imageAxis, 'on');
%axis(ad.handles.imageAxis, 'image');
%set(ad.figMain, 'Colormap', copper);
setappdata(0, 'OptimiseGridToolData', ad);
return;

function doToggleMeanShape(toggle_mean_shape, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if ishandle(ad.mean_shape_plot_handle)
    if get(toggle_mean_shape, 'value')
        set(ad.mean_shape_plot_handle, 'Visible', 'on');
    else
        set(ad.mean_shape_plot_handle, 'Visible', 'off');
    end
end
setappdata(0, 'OptimiseGridToolData', ad);

function doToggleGrid(toggle_grid, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if ishandle(ad.grid_plot_handle)
    if get(toggle_grid, 'value')
        set(ad.grid_plot_handle, 'Visible', 'on');
    else
        set(ad.grid_plot_handle, 'Visible', 'off');
    end
end
setappdata(0, 'OptimiseGridToolData', ad);

function doToggleInternalSpring(toggle_internal, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if ishandle(ad.spring_marker_handle)
    if get(toggle_internal, 'value')
        set(ad.spring_marker_handle, 'Visible', 'on');
    else
        set(ad.spring_marker_handle, 'Visible', 'off');
    end
end
if ishandle(ad.spring_line_handle)
    if get(toggle_internal, 'value')
        set(ad.spring_line_handle, 'Visible', 'on');
    else
        set(ad.spring_line_handle, 'Visible', 'off');
    end
end
if ishandle(ad.spring_text_handle)
    if get(toggle_internal, 'value')
        set(ad.spring_text_handle, 'Visible', 'on');
    else
        set(ad.spring_text_handle, 'Visible', 'off');
    end
end
setappdata(0, 'OptimiseGridToolData', ad);

function doToggleExternalSpring(toggle_internal, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if ishandle(ad.edge_marker_handle)
    if get(toggle_internal, 'value')
        set(ad.edge_marker_handle, 'Visible', 'on');
    else
        set(ad.edge_marker_handle, 'Visible', 'off');
    end
end
if ishandle(ad.edge_line_handle)
    if get(toggle_internal, 'value')
        set(ad.edge_line_handle, 'Visible', 'on');
    else
        set(ad.edge_line_handle, 'Visible', 'off');
    end
end
if ishandle(ad.edge_text_handle)
    if get(toggle_internal, 'value')
        set(ad.edge_text_handle, 'Visible', 'on');
    else
        set(ad.edge_text_handle, 'Visible', 'off');
    end
end
setappdata(0, 'OptimiseGridToolData', ad);

function doToggleSpringPoints(toggle_spring_points, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if ishandle(ad.edge_plot_handle)
    if get(toggle_spring_points, 'value')
        set(ad.edge_plot_handle, 'Visible', 'on');
    else
        set(ad.edge_plot_handle, 'Visible', 'off');
    end
end
setappdata(0, 'OptimiseGridToolData', ad);
function doToggleCentroids(toggle_centroids, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if ishandle(ad.centroid_plot_handle)
    if get(toggle_centroids, 'value')
        set(ad.centroid_plot_handle, 'Visible', 'on');
    else
        set(ad.centroid_plot_handle, 'Visible', 'off');
    end
end
setappdata(0, 'OptimiseGridToolData', ad);




% function doUpdateGridList()
% ad =getappdata(0, 'OptimiseGridToolData');
% files = dir([ad.GridDir, filesep, 'grid_data*']);
% files = {files.name};
% if length(files)>0
%     set(ad.handles.grid_popup, 'String', files);
% else
%     set(ad.handles.grid_popup, 'String', {'No Grids Found'});
% end
% setappdata(0, 'OptimiseGridToolData', ad);




% function doCalcRegionStats(region_stats_btn, evd)
% ad =getappdata(0, 'OptimiseGridToolData');
% R = ad.regions.R;
% centroids = ad.regions.centroids;
% str = get(ad.handles.grid_popup, 'String');
% val = get(ad.handles.grid_popup, 'value');
% if strcmp(str{val}, 'No Grids Found')
%     return;
% end
% StagedDirString = ad.StagedDirString;
% FILES = dir(StagedDirString);
% if isempty(FILES); 
%     return; 
% end;
% FILES = {FILES.name};
% FILES = cleanup_stage_list(FILES);
% [s,v] = listdlg('Name', 'Select Stages To Calc. Region Stats', 'PromptString','Select the stages you wish to calculate regional statistical for:', 'SelectionMode','multiple', 'ListString',FILES, 'ListSize', [300, 200]);
% pause(.01);
% FILES = FILES(s);
% ind = [];
% for f = 1:length(FILES)
%     file = FILES{f};
%     if (file(1) == '.') | strcmp(file, 'Data')
%         ind = [ind; f];
%     end
% end
% FILES(ind) = [];
% waitbar_h = waitbar(0, 'Calculating region statistics, please wait...');
% number_of_regions = size(R,3)-1;
% for i=1:length(FILES)
%     stage = [StagedDirString, filesep, FILES{i}];
%     str = get(ad.handles.grid_popup, 'String');
%     val = get(ad.handles.grid_popup, 'Value');
%     calc_stage_sector_info(StagedDirString, stage, ad.RegionDirName, number_of_regions, R, centroids, str{val});
%     calc_average_stage_sector_info(stage, str{val}, number_of_regions);
%     waitbar(i/length(FILES), waitbar_h);
% end
% close(waitbar_h);

% function doChangeGrid(grid_popup, evd)
% ad =getappdata(0, 'OptimiseGridToolData');
% str = get(grid_popup, 'String');
% val = get(grid_popup, 'value');
% if strcmp(str{val}, 'No Grids Found')
%     return;
% end
% file = [ad.GridDir, filesep, str{val}];
% if exist(file, 'file')
%     region_info = load(file);
%     ad.regions = region_info.region_info;
% else
%     ad.regions.R = [];
%     ad.regions.grid_xy = [];
%     ad.regions.vertex = [];
%     ad.regions.edge = [];
%     ad.regions.edge_petal = [];
%     ad.regions.neighbours = [];
% end
% setappdata(0, 'OptimiseGridToolData', ad);
% doPlotAll;
% doToggleAll;

function doZoom(zoom_btn, evd)
ad =getappdata(0, 'OptimiseGridToolData');
zoom off;
pan off;
if get(ad.handles.zoom_btn, 'value')
    zoom on;
end

function doPan(pan_btn, evd)
ad =getappdata(0, 'OptimiseGridToolData');
zoom off;
pan off;
if get(ad.handles.pan_btn, 'value')
    pan on;
end

function doWarpGridToMeanShape(warp_grid_btn, evd)
ad =getappdata(0, 'OptimiseGridToolData');
edge = ad.regions.edge_petal;
N = max(edge(:,3));
figure(1); clf; hold on;
warped_grid = [];
h = [];
reg = ad.regions.xy_regions;
for k=1:length(reg); h = [h; [reg{k} ones(size(reg{k},1),1)*k]]; end;
[hu, I,J] = unique(h(:,1:2), 'rows');
h = h(I,:);
for i=2:length(ad.mature_grid.order)+1
    r = i-1;
    [xmat, ymat] = get_region_vertices(ad.mature_grid.Edgs, ad.mature_grid.S, r, ad.mature_grid.order{r});
    [xmat, ymat] = interp_vertex_points(xmat, ymat);
    [xyng, yyng] = get_region_vertices(ad.ungrown_grid.Edgs, ad.ungrown_grid.S, r, ad.ungrown_grid.order{r});
    [xyng, yyng] = interp_vertex_points(xyng, yyng);
    T = cp2tform([xmat, ymat], [xyng, yyng],'polynomial', 2);
    ind = find(h(:,3)==r);
    u = double(h(ind,1));
    v = double(h(ind,2));
    newgrid = [ones(length(u),1)  u  v  u.*v  u.^2  v.^2]*T.tdata;
    warped_grid = [warped_grid; [newgrid, ones(size(newgrid,1),1)*double(i)]];
end
grid_pts = SelectGridPointsUtil('shape', [fliplr(ad.mean_shape(:,1:2)) ad.mean_shape(:,3)], 'warped_pts', warped_grid);
R = pts2gridIm(grid_pts);
edge_petal = [fliplr(ad.mean_shape(:,1:2)), ad.mean_shape(:,3)];
vertex{1} = {};
clear edge;
edge{1} = {};
for i=1:max(grid_pts(:,3))
    ind = find(grid_pts(:,3) == i);
    vertex{i+1} = grid_pts(ind,1:2);
    edge{i+1} = grid_pts(ind,1:2);
    ind = find(edge_petal(:,3)==i+1);
    edge{i+1} = [edge{i+1}; edge_petal(ind,1:2)];
end
%function [R, vertex, edge, edge_petal, N, grid_xy, centroids] = autoMakeGrid(reduce, reg_x, reg_y, max_regions, shape, thr)
%[R, vertex, edge, edge_petal] = auto_regions(reduce,reg_x,reg_y,max_regions, double(shape));
region_inds = edge_petal(:,3);
[edge_petal, toind] = image_sort(edge_petal(:,1), edge_petal(:,2));
edge_petal = [edge_petal, region_inds(toind)];
[R, vertex, edge, edge_petal] = autoRemoveSmallRegions(R, vertex, edge, edge_petal, 0.33);
fprintf('Now finding the neighbours for each region...\n');
N = find_neighbours(R);
fprintf('done.\n');
grid_xy = calc_grid_outline(R);
centroids = get_centroids(R);
centroids = centroids(2:end, :);
ad.regions.layers = show_layers(R);
ad.regions.R = R;
ad.regions.vertex = vertex;
ad.regions.edge = edge;
ad.regions.edge_petal = edge_petal;
ad.regions.neighbours = N;
ad.regions.grid_xy = grid_xy;
ad.regions.centroids = centroids;
ad.regions.xy_regions = edge(2:end);
ad.regions.order = [];
setappdata(0, 'OptimiseGridToolData', ad);
[ad.regions.Springs.S, ad.regions.Springs.E, ad.regions.Springs.Edgs] = doMakeSprings(R, vertex, edge, edge_petal, N, centroids);
indtoremove = calc_remove_ind(vertex, ad.regions.Springs.Edgs);
ad.regions.Springs.Edgs_All = ad.regions.Springs.Edgs;
ad.regions.Springs.Edgs = ad.regions.Springs.Edgs(indtoremove, :);
ad.regions.Springs.Edgs = orderEdgs(ad.regions.Springs.Edgs);
ad.regions.order = makeorder(ad.regions.Springs.S, ad.regions.Springs.Edgs);
ad.regions.Springs.edges_removed_ind = setdiff(1:size(ad.regions.Springs.Edgs_All,1), indtoremove);
setappdata(0, 'OptimiseGridToolData', ad);

function doLoadGrid(save_grid_btn, evd)
ad = getappdata(0, 'OptimiseGridToolData');
[filename, pathname] = uigetfile('*.mat', 'Pick an Grid-file', [ad.GridDir, filesep]);
if isequal(filename,0) | isequal(pathname,0)
    disp('User pressed cancel')
else
    disp(['User selected ', fullfile(pathname, filename)])
    f = load([pathname, filesep, filename]);
    f = f.region_info;
    ad.shape = f.edge_petal;
    ad.regions = f;
end
setappdata(0, 'OptimiseGridToolData', ad)
doPlotAll;

function doSaveGrid(save_grid_btn, evd)
ad = getappdata(0, 'OptimiseGridToolData');
region_info = ad.regions;
fprintf('Saving grid data...\n');
reg_x = str2num(get(ad.handles.num_x_edit, 'String'));
reg_y = str2num(get(ad.handles.num_y_edit, 'String'));
grid_name = ['grid_data_', num2str(reg_x), '_by_', num2str(reg_y), '_optimised.mat'];
[filename, pathname] = uiputfile(grid_name, 'Pick an Grid Filename', [ad.GridDir, filesep]);
if isequal(filename,0) | isequal(pathname,0)
    disp('User pressed cancel')
else
    disp(['User selected ', fullfile(pathname, filename)])
end
save([pathname,filesep, filename], 'region_info');
fprintf('done.\n');
setappdata(0, 'OptimiseGridToolData', ad);



function doConcavityCheck(concavity_check_btn, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if isempty(ad.regions)
    return;
end
if ~isfield(ad.regions, 'Springs')
    return;
end
[xyreg, order, value] = ConcavityCheck('Springs', ad.regions.Springs.S, 'Edgs', ad.regions.Springs.Edgs, 'E',ad.regions.Springs.E, 'Order', ad.regions.Springs.order);%, 'Layers', ad.regions.layers); %
ad.regions.xy_regions = xyreg;
ad.regions.Springs.order = order;

reg_x = str2num(get(ad.handles.num_x_edit, 'String'));
reg_y = str2num(get(ad.handles.num_y_edit, 'String'));
grid_name = ['grid_data_', num2str(reg_x), '_by_', num2str(reg_y), '.mat'];
fprintf('Saving grid data (post-concavity check)\n');
region_info = ad.regions;
%save([ad.GridDir,filesep, str{val}], 'region_info');
fprintf('done.\n');
setappdata(0, 'OptimiseGridToolData', ad);
%display_organ(ad.regions.xy_regions, gca);
doPlotAll;




function doPlotCentroids()
ad = getappdata(0, 'OptimiseGridToolData');
cen = ad.regions.centroids;
if isempty(cen)
    return;
end
if ishandle(ad.centroid_plot_handle)
    delete(ad.centroid_plot_handle);
    ad.centroid_plot_handle = [];
end
ad.centroid_plot_handle = plot(ad.handles.imageAxis, cen(:,2), cen(:,1), 'o', 'MarkerEdgeColor', 'y', 'MarkerFaceColor', 'y');

setappdata(0, 'OptimiseGridToolData', ad);
return;

function doPlotSprings()
ad = getappdata(0, 'OptimiseGridToolData');
if ~isfield(ad.regions, 'Springs')
    return;
end
Springs = ad.regions.Springs.S;
if ishandle(ad.spring_marker_handle)
    delete(ad.spring_marker_handle);
    ad.spring_marker_handle = [];
end
if ishandle(ad.spring_line_handle)
    delete(ad.spring_line_handle);
    ad.spring_line_handle = [];
end
if ishandle(ad.spring_text_handle)
    delete(ad.spring_text_handle);
    ad.spring_text_handle = [];
end
[ad.spring_marker_handle, ad.spring_line_handle, ad.spring_text_handle] = display_springs(Springs, ad.handles.imageAxis);
setappdata(0, 'OptimiseGridToolData', ad);
return;

function doPlotEdgeSprings()
ad = getappdata(0, 'OptimiseGridToolData');
if ~isfield(ad.regions, 'Springs')
    return;
end
Springs = ad.regions.Springs.S;
Edgs = ad.regions.Springs.E;
if ishandle(ad.edge_marker_handle)
    delete(ad.edge_marker_handle);
    ad.edge_marker_handle = [];
end
if ishandle(ad.edge_line_handle)
    delete(ad.edge_line_handle);
    ad.edge_line_handle = [];
end
if ishandle(ad.edge_text_handle)
    delete(ad.edge_text_handle);
    ad.edge_text_handle = [];
end
[ad.edge_marker_handle, ad.edge_line_handle, ad.edge_text_handle] = display_edges(Springs, Edgs, ad.handles.imageAxis);
setappdata(0, 'OptimiseGridToolData', ad);
return;

function doPlotVertices()
ad = getappdata(0, 'OptimiseGridToolData');
vertex = ad.regions.vertex;
if ishandle(ad.vertex_plot_handle)
    delete(ad.vertex_plot_handle);
    ad.vertex_plot_handle = [];
end
for e=2:length(vertex)
  ad.vertex_plot_handle(end+1) = plot(ad.handles.imageAxis, vertex{e}(:,1), vertex{e}(:,2), 'o', 'Color', 'w', 'MarkerFaceColor', 'r');
end
setappdata(0, 'OptimiseGridToolData', ad);
return;

function doPlotEdgePoints()
ad = getappdata(0, 'OptimiseGridToolData');
edge = ad.regions.edge;
if ishandle(ad.edge_plot_handle)
    delete(ad.edge_plot_handle);
    ad.edge_plot_handle = [];
end
for e=2:length(edge)
    ad.edge_plot_handle(end+1) = plot(ad.handles.imageAxis, edge{e}(:,1), edge{e}(:,2), 'o', 'MarkerFaceColor', 'g');
end
setappdata(0, 'OptimiseGridToolData', ad);
return;

function doPlotMeanShape()
ad = getappdata(0, 'OptimiseGridToolData');
if ishandle(ad.mean_shape_plot_handle)
    delete(ad.mean_shape_plot_handle);
    ad.mean_shape_plot_handle = [];
end
ad.mean_shape_plot_handle = plot(ad.handles.imageAxis, ad.shape(:,1), ad.shape(:,2), '-o', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'y', 'Color', 'b');
setappdata(0, 'OptimiseGridToolData', ad);
return;


function doPlotGrid()
ad = getappdata(0, 'OptimiseGridToolData');    
    
    
if ishandle(ad.grid_plot_handle)
    delete(ad.grid_plot_handle);
    ad.grid_plot_handle = [];
end

S = ad.regions.Springs.S;
Edgs = ad.regions.Springs.Edgs;
order = ad.regions.Springs.order;
ad.grid_plot_handle = display_grid(S, Edgs, order, ad.handles.imageAxis, [1 0 0], 2);

% if ishandle(ad.grid_plot_handle)
%     delete(ad.grid_plot_handle);
%     ad.grid_plot_handle = [];
% end
% grid_xy = ad.regions.grid_xy;
% ad.grid_plot_handle = display_organ(ad.regions.xy_regions, ad.handles.imageAxis, [1 1 1]);
% hold(ad.handles.imageAxis, 'on');
% %ad.grid_plot_handle = plot(ad.handles.imageAxis, grid_xy(:,2), grid_xy(:,1), '.w');
setappdata(0, 'OptimiseGridToolData', ad);
return;

function doLoadUngrownShape(load_ungrown_shape_btn, evd)
ad =getappdata(0, 'OptimiseGridToolData');
[filename, pathname] = uigetfile('*.mat', 'Pick an Ungrowth File', [ad.UngrowthDataDir, filesep]);
if isequal(filename,0) | isequal(pathname,0)
    disp('User pressed cancel')
else
    f = load([pathname, filesep, filename]);
    f = f.ungrown_grid;
    N = length(f);
    ad.regions.Springs.S = f(N).S;
    ad.regions.Springs.Edgs = f(N).Edgs;
    ad.regions.Springs.order = f(N).order;
    ad.shape = f(N).edge_petal;
    ad.shape = double([ad.shape(:,1), ad.shape(:,2), ad.shape(:,3)]);
    ad.mean_shape = f(1).edge_petal;
    ad.mean_shape = double([ad.mean_shape(:,2), ad.mean_shape(:,1), ad.mean_shape(:,3)]);
    ad.mature_grid = f(1);
    ad.ungrown_grid = f(length(f));
    setappdata(0, 'GridEditorToolData', ad);
    set(ad.handles.imageAxis, 'Visible', 'on');
end
setappdata(0, 'OptimiseGridToolData', ad);
doPlotAll;
return;

function doEditEdgePoints(edit_edge_btn, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if ~isfield(ad.regions, 'Springs')
    return;
end
Edgs = ad.regions.Springs.Edgs_All;
Spr = ad.regions.Springs.S;
xyreg = ad.regions.xy_regions;
removed_ind = ad.regions.Springs.edges_removed_ind;
[Edgs, removed_ind, order, value] = EditEdgePoints('Springs', Spr, 'Edges', Edgs, 'xyregs', xyreg, 'removed_indices', removed_ind, 'order', ad.regions.order);%, 'Layers', ad.regions.layers);
ad.regions.order = makeorder(ad.regions.Springs.S, ad.regions.Springs.Edgs);
ad.regions.Springs.Edgs = Edgs;
ad.regions.Springs.edges_removed_ind = removed_ind;
ad.regions.Springs.order = order;
%cla(ad.handles.imageAxis);
%display_edges(Spr, Edgs, ad.handles.imageAxis);
setappdata(0, 'OptimiseGridToolData', ad);
region_info = ad.regions;
%save([ad.GridDir,filesep, str{val}], 'region_info');
doPlotAll;

return;




function doAutoGrid(auto_grid_btn, evd)
ad =getappdata(0, 'OptimiseGridToolData');
if isempty(ad.shape)
    return;
end
reduce = 1;
reg_x = str2num(get(ad.handles.num_x_edit, 'String'));
reg_y = str2num(get(ad.handles.num_y_edit, 'String'));
max_regions = 45;
fprintf('Making a grid with %d in x and %d in y\n', reg_x, reg_y);
fprintf('Maximum number of grids is %d\n', max_regions);
fprintf('Reduction factor is set to %d\n', reduce);
[R, vertex, edge, edge_petal, N, grid_xy, centroids] = autoMakeGrid(reduce, reg_x, reg_y, max_regions, fliplr(ad.shape(:,1:2)), ad.region_size_threshold);
ad.regions.layers = show_layers(R);
ad.regions.R = R;
ad.regions.vertex = vertex;
ad.regions.edge = edge;
ad.regions.edge_petal = edge_petal;
ad.regions.neighbours = N;
ad.regions.grid_xy = grid_xy;
ad.regions.centroids = centroids;
ad.regions.xy_regions = edge(2:end);
ad.regions.order = [];
setappdata(0, 'OptimiseGridToolData', ad);
[ad.regions.Springs.S, ad.regions.Springs.E, ad.regions.Springs.Edgs] = doMakeSprings(R, vertex, edge, edge_petal, N, centroids);
indtoremove = calc_remove_ind(vertex, ad.regions.Springs.Edgs);
ad.regions.Springs.Edgs_All = ad.regions.Springs.Edgs;
ad.regions.Springs.Edgs = ad.regions.Springs.Edgs(indtoremove, :);
ad.regions.order = makeorder(ad.regions.Springs.S, ad.regions.Springs.Edgs);
ad.regions.Springs.edges_removed_ind = setdiff(1:size(ad.regions.Springs.Edgs_All,1), indtoremove);
region_info = ad.regions;
%fprintf('Saving grid data...\n');
%grid_name = ['grid_data_', num2str(reg_x), '_by_', num2str(reg_y), '.mat'];
%save([ad.GridDir,filesep, grid_name], 'region_info');
%fprintf('done.\n');
setappdata(0, 'OptimiseGridToolData', ad);
%doUpdateGridList;
doPlotAll;
%str = get(ad.handles.grid_popup, 'String');
%val = strmatch(grid_name, str, 'exactly');
%set(ad.handles.grid_popup, 'Value', val);



function doToggleAll
ad =getappdata(0, 'OptimiseGridToolData');
doToggleMeanShape(ad.handles.toggle_mean_shape);
doToggleInternalSpring(ad.handles.toggle_internal_spring);
doToggleExternalSpring(ad.handles.toggle_external_spring);
doToggleCentroids(ad.handles.toggle_centroids);
doToggleGrid(ad.handles.toggle_grid);


function doPlotAll
doPlotGrid;
doPlotMeanShape;
%doPlotCentroids;
%doPlotEdgeSprings;
%doPlotSprings;
doToggleAll;






