function SATPlotOptionsTool
% function SATPlotOptionsTool
%
% A small utility that allows the user to select some plot options before
% displaying the ungrowth data.
%
% Usage:
%
% >>SATPlotOptionsTool
%
% Dr. A. I. Hanna, CMP & JIC, Norwich, UK, 2008.

%% initialize the utility
%if checkSATDir(pwd) == 0
%    fprintf('You are not in a valid SectorAnalysisToolbox Project directory\n');
%    return;
%end
% Open, move, and get the handles from the figure file.
fig = openfig(mfilename, 'reuse');
movegui(fig, 'northwest');
set(fig, 'Visible', 'on');

ad.figMain = fig;
ad.handles = guihandles(fig);

% Initialize the application data structure
ad = initadstruct(ad);
% Set all the callback functions
ad = setupCallbacks(ad);

setappdata(0,'SATPlotOptionsTool',ad);
updateGui;
try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end
return;
%%
%
function ad = initadstruct(ad)
set(ad.figMain, 'Color', get(ad.handles.colpanel, 'BackgroundColor'));
ad.StagedDirString = 'Staged';
ad.OriginalsDirString = 'Originals';
ad.ProcessedDirString = 'Processed';
ad.DataDir = [ad.StagedDirString, filesep, 'Data'];
ad.UngrowthDir = [ad.DataDir, filesep, 'UngrowthData'];
ad.MeanShapeName = [ad.DataDir, filesep, 'mean_shape.mat'];
ad.projectpath = pwd;
ad.value = 0;
ad = initData(ad);

%%
function wp = initWarpParams
wp.xspace = 20;
wp.yspace = 20;
wp.smoothterm = 0.01;
wp.showmaterialvectors = 0;
wp.direction = 'Forward';
wp.rotval = 0;
wp.padval = 1;
wp.showclones = 0;
wp.clonescale = 1;
return;
%%
%
function ad = initData(ad)
ad.data.ungrowthfilename = '';
ad.data.edgecolor = [0 0 0];
ad.data.uniformfacecolor = [0 1 0];
ad.data.outlinecolor = [0 0 0];
ad.data.tensorcol = [0 0 0];
ad.data.colormap = 'lab';
ad.data.allfigures = [];
ad.data.flipcolmap = 0;
ad.data.warpparams = initWarpParams;
return;
%%
%
function updateGui
ad = getappdata(0,'SATPlotOptionsTool');
set(ad.handles.facecol_btn, 'BackgroundColor', (ad.data.uniformfacecolor));
set(ad.handles.edgecol_btn, 'BackgroundColor', (ad.data.edgecolor));
set(ad.handles.outlinecol_btn, 'BackgroundColor', (ad.data.outlinecolor));
set(ad.handles.tensorcol_btn, 'BackgroundColor', (ad.data.tensorcol));
setappdata(0,'SATPlotOptionsTool',ad);
return
%%
%
function selectFaceColour(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
col = uisetcolor(ad.data.uniformfacecolor);
if col==0
    return;
end
ad.data.uniformfacecolor = col;
setappdata(0,'SATPlotOptionsTool',ad);
updateGui;
return;
%%
%
function selectEdgeColour(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
col = uisetcolor(ad.data.edgecolor);
if col==0
    return;
end
ad.data.edgecolor = col;
setappdata(0,'SATPlotOptionsTool',ad);
updateGui;
return;
%%
%
function selectOutlineColour(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
col = uisetcolor(ad.data.edgecolor);
if col==0
    return;
end
ad.data.outlinecolor = col;
setappdata(0,'SATPlotOptionsTool',ad);
updateGui;
return;
%%
%
function selectTensorColour(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
col = uisetcolor(ad.data.tensorcol);
if col==0
    return;
end
ad.data.tensorcol = col;
setappdata(0,'SATPlotOptionsTool',ad);
updateGui;
return;
%%
%
function selectColormap(popup, evd)
ad = getappdata(0,'SATPlotOptionsTool');
val = get(popup, 'Value');
str = get(popup, 'String');
ad.data.colormap = str{val};
setappdata(0,'SATPlotOptionsTool',ad);
updateGui;
return;
%%
%
% Set all the callback functions
function ad = setupCallbacks(ad)
set(ad.handles.cancel_btn, 'callback', {@cancelWindow});
set(ad.handles.plot_btn, 'callback', {@plotData});
set(ad.handles.load_btn, 'callback', {@getGrowthFile});
set(ad.handles.facecol_btn, 'callback', {@selectFaceColour});
set(ad.handles.edgecol_btn, 'callback', {@selectEdgeColour});
set(ad.handles.outlinecol_btn, 'callback', {@selectOutlineColour});
set(ad.handles.tensorcol_btn, 'callback', {@selectTensorColour});
set(ad.handles.mappicker, 'callback', {@selectColormap});
set(ad.handles.warpgrid_btn, 'callback', {@warpRegularGrid});
set(ad.handles.closeall_btn, 'callback', {@closeAll});
set(ad.handles.setalldst_btn, 'callback', {@setAllDeltaSt});
set(ad.handles.changedst_btn, 'callback', {@changeDeltaSt});
set(ad.handles.save_btn, 'callback', {@saveGrowthFile});

return
%%
%
function closeAll(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
for i=1:length(ad.data.allfigures)
    if ishandle(ad.data.allfigures(i))
        close(ad.data.allfigures(i));
    end
end
ad.data.allfigures = [];
setappdata(0,'SATPlotOptionsTool',ad);
%%
% just delete the figure and return
function cancelWindow(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
delete(ad.figMain);
setappdata(0,'SATPlotOptionsTool',ad);
%%
% just delete the figure and return
function warpRegularGrid(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
if isempty(ad.data.ungrowthfilename)
    uiwait(msgbox('You must load some growth data first','Error','modal'));
    return;
end
linwidth = str2double(get(ad.handles.linewidth_txt, 'String'));


ad.data.warpparams = SATWarpParamsDlg('warpparams', ad.data.warpparams);
xspace = ad.data.warpparams.xspace;
yspace = ad.data.warpparams.yspace;
smoothterm = ad.data.warpparams.smoothterm;
showvectors = ad.data.warpparams.showmaterialvectors;
showclones = ad.data.warpparams.showclones;
direction = ad.data.warpparams.direction;
rotval = ad.data.warpparams.rotval;
padval = ad.data.warpparams.padval;
clonescale = ad.data.warpparams.clonescale;
smooththr = 0.00001;
if abs(smoothterm) <smooththr
    str = sprintf('%s %f\n%s', 'Your chosen smoothing parameter is <', smooththr, 'This may result in a distorted grid');
    uiwait(msgbox(str,'WARNING','modal'));
end

edgecol = ad.data.edgecolor;
if get(ad.handles.showmesh_chk, 'Value') == 0
    edgecol = 'none';
end
facecol = ad.data.uniformfacecolor;
if get(ad.handles.showfaces_chk, 'Value') == 0
    facecol = 'none';
end
outlinecol = ad.data.outlinecolor;
if get(ad.handles.showoutline_chk, 'Value') == 0
    outlinecol = 'none';
end
figvec = satlib_warpRegularMesh('filename', ad.data.ungrowthfilename, ...
    'dx', xspace,'dy', yspace,...
    'facecolor', facecol, ...
    'scale', get(ad.handles.scale_chk, 'Value'), ...
    'edgecolor', edgecol, 'direction', direction, ...
    'smoothingterm', smoothterm, 'showvectors', showvectors, ...
    'showclones', showclones, 'clonescale', clonescale , ...
    'linewidth', linwidth, 'rotval', rotval, 'outlinecol', outlinecol, 'padval', padval);
ad.data.allfigures = cat(1, ad.data.allfigures, figvec);
setappdata(0,'SATPlotOptionsTool',ad);


%%
function changeDeltaSt(chgbtn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
if isempty(ad.data.ungrown_grids)
    uiwait(msgbox('You must load some growth data first','Error','modal'));
    return;
end
val = get(ad.handles.stageinfo_txt, 'Value');
prompt={'Enter the number of hours:'};
name='Hour between stage';
numlines=1;
defaultanswer={'20'};

answer=inputdlg(prompt,name,numlines,defaultanswer);
if isempty(answer)
    return;
end
ad.data.ungrown_grids{val+1}.deltaSt = str2double(answer{1});
setappdata(0,'SATPlotOptionsTool', ad);
updateGrowthInfo();
%%
function setAllDeltaSt(setallbtn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
if isempty(ad.data.ungrown_grids)
    uiwait(msgbox('You must load some growth data first','Error','modal'));
    return;
end
val = get(ad.handles.stageinfo_txt, 'Value');

prompt={'Enter the number of hours:'};
name='Hour between stage';
numlines=1;
defaultanswer={'20'};

answer=inputdlg(prompt,name,numlines,defaultanswer);
if isempty(answer)
    return;
end

for i=1:length(ad.data.ungrown_grids)
    ad.data.ungrown_grids{i}.deltaSt = str2double(answer{1});
end
setappdata(0,'SATPlotOptionsTool', ad);
updateGrowthInfo();
%%
function updateGrowthInfo()
ad = getappdata(0,'SATPlotOptionsTool');
if isempty(ad.data.ungrown_grids)
    uiwait(msgbox('You must load some growth data first','Error','modal'));
    return;
end
str = {};


ug = ad.data.ungrown_grids;
stages = ug{1}.stage_info.stages;
for i=2:length(ug)
    if ~isfield(ug{i}, 'deltaSt')
        ug{i}.deltaSt = 20;
    end
    sstr = [stages{i-1}, ' - ', stages{i}, '  ', num2str(ug{i}.deltaSt), ' hrs'];
    str = cat(1, str, sstr);
end
set(ad.handles.stageinfo_txt, 'String', str);
ad.data.ungrown_grids = ug;
setappdata(0,'SATPlotOptionsTool', ad);

%%
% just delete the figure and return
function plotData(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
if isempty(ad.data.ungrowthfilename)
    uiwait(msgbox('You must load some growth data first','Error','modal'));
    return;
end
edgecol = ad.data.edgecolor;
if get(ad.handles.showmesh_chk, 'Value') == 0
    edgecol = 'none';
end

facecol = ad.data.uniformfacecolor;

if get(ad.handles.showfaces_chk, 'Value') == 0
    facecol = 'none';
end

tensoruniscale = 1;
tensorscalefactor = str2double(get(ad.handles.scalefactortxt, 'String'));
if get(ad.handles.scaletensorchk, 'Value')==0
    tensoruniscale = 0;
end

tensorthreshold = str2double(get(ad.handles.tensorthrtxt, 'String'));
if get(ad.handles.tensorthrchk, 'Value')==0
    tensorthreshold = 0;
end

tensortype = getTensorType(ad);
ad.data.colormap = getColormap(ad);

outlinecol = ad.data.outlinecolor;
if get(ad.handles.showoutline_chk, 'Value') == 0
    outlinecol = 'none';
end



linwidth = str2double(get(ad.handles.linewidth_txt, 'String'));

gptype = getGPType(ad);
method = getMethod(ad);
userlims = getUserLimits(ad);

figvec = satlib_plot_ungrowth_data('ungrown_grids', ad.data.ungrown_grids, ...
    'edgecolor', edgecol, 'facecolor', facecol, ...
    'showtensors', get(ad.handles.showtensors_chk, 'Value'), ...
    'outlinecolour', outlinecol, ...
    'scale', get(ad.handles.scale_chk, 'Value'), ...
    'tensorcol', ad.data.tensorcol, ...
    'method', method,...
    'colormap', ad.data.colormap, ...
    'flipcolormap', get(ad.handles.flipcolmap_chk, 'Value'), ...
    'userlimits', userlims, ...
    'linewidth', linwidth, ...
    'tensorscalefactor', tensorscalefactor, ...
    'tensorthreshold', tensorthreshold, ...
    'tensoruniscale', tensoruniscale, ...
    'tensortype', tensortype, 'gptype', gptype);
ad.data.allfigures = cat(1, ad.data.allfigures, figvec);
setappdata(0,'SATPlotOptionsTool',ad);
%%
%
function userlims = getUserLimits(ad)
userlims = [];
if ~get(ad.handles.userlims_chk, 'Value')
    return;
end
userlims = [str2double(get(ad.handles.mintxt, 'String')), str2double(get(ad.handles.maxtxt, 'String'))];
return
%%
%
function tensortype = getTensorType(ad)
majval = get(ad.handles.major_chk, 'Value');
minval = get(ad.handles.minor_chk, 'Value');
tensortype = [majval, minval];
return
%%
function cmap = getColormap(ad)
cmap = 'lab2';
val = get(ad.handles.mappicker, 'Value');
str = get(ad.handles.mappicker, 'String');
cmap = str{val};
return
%%
%
function gptype = getGPType(ad)
gptype = 'mesh';
if get(ad.handles.sectorgp_radio, 'Value')
    gptype = 'sector';
end
return
%%
%
function method = getMethod(ad)
str = get(ad.handles.schema_popup, 'String');
val = get(ad.handles.schema_popup, 'Value');
method = str{val};
return
%%
%
function getGrowthFile(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
[filename, pathname] = uigetfile('*.mat', 'Pick an Ungrowth File', [ad.UngrowthDir, filesep]);
if isequal(filename,0) || isequal(pathname,0)
    disp('User pressed cancel')
    return;
end
ad.data.ungrowthfilename = [pathname, filesep, filename];
d = load(ad.data.ungrowthfilename);
if ~isfield(d, 'ungrown_grids')
    fprintf('Invalid ungrowth file\n');
    ad.data.ungrown_grids = {};
else
    ad.data.ungrown_grids = d.ungrown_grids;
    ad.data.origgrid = d;
end
setappdata(0,'SATPlotOptionsTool',ad);
updateGrowthInfo();
return;
%%
%
function saveGrowthFile(btn, evd)
ad = getappdata(0,'SATPlotOptionsTool');
[filename, pathname] = uiputfile('*.mat', 'Save as..., ', ad.data.ungrowthfilename);
if isequal(filename,0) || isequal(pathname,0)
    disp('User pressed cancel')
else
    disp(['User selected ', fullfile(pathname, filename)])
end

grid_name = ad.data.origgrid.grid_name;
ungrown_grids = ad.data.ungrown_grids;
save([pathname, filesep, filename], 'grid_name', 'ungrown_grids');
setappdata(0,'SATPlotOptionsTool',ad);
uiwait(msgbox('Finished saving your ungrowth data','Save','modal'));

return;