function ModelGenerator(arg)
global AAMShapemodel_figure_handle
global AAMModelGenerator_handle
global AAMModelBuilder_handle
global AAMSetPicker_handle
global UpdateModel_handle
global PMTemplateBuilder_handle
global PDMWalk_handle
if strcmpi(class(arg), 'AAM')
    %close all;
    % Open the GUI for display
    fig = openfig(mfilename, 'reuse');
    movegui(fig, 'center');
    % Generate a structure of handles to pass to callbacks, and store
    Data.handles = guihandles(fig);
    set(fig, 'Color', get(Data.handles.uipanel8, 'BackgroundColor'));
    set(fig, 'Visible', 'on');
    Data.handles.figMain = fig;
    AAMModelGenerator_handle=fig;
    Data.handles.AAM = arg;
    %Data.handles.AAM = UpdateAAMFromDisk(Data.handles.AAM);
    Data.handles.dat.options = [];
    set(Data.handles.filenamesList, 'value', []);
    Data.handles.workingDir = pwd;
    Data.handles.dat.currentLoopNumber = 0;
    set(Data.handles.txtCurrentStatus, 'ForegroundColor', 'blue','String', 'Please Choose an Operation');
    indices=get(Data.handles.AAM,'pointindices');
    if iscell(indices)
        indices=indices{1};
    end

    Data.handles.dat.indices = indices;
    Data.handles.dat.edit_indices = [];
    Data.handles.dat.pointsToMove = [];
    Data.handles.dat.imagelists = {};
    Data.handles.dat.currentSet = ['Set_', num2str(get(Data.handles.AAM, 'pointset'))];
    %Data.handles.dat.currentSet
    %set(Data.handles.imageList, 'value', get(Data.handles.AAM, 'imageset') )
    Data.handles = SetupModel(Data.handles);
    Data.handles.dat.plotH = PlotModel(Data.handles.mainAxes, get(Data.handles.AAM, 'PointModelTemplate'), Data.handles, Data.handles.dat.plotH);

    guidata(fig, Data);
    if exist('AAMShapemodel_figure_handle')
        if ishandle(AAMShapemodel_figure_handle)
            set(AAMShapemodel_figure_handle,'visible','off');
        end
    end
else
    Data = guidata(gcbo);
    set(Data.handles.figMain, 'Pointer', 'watch');
    switch arg
        case 'ToggleLabeling'
            Data.handles.dat.plotH = PlotModel(Data.handles.mainAxes, get(Data.handles.AAM, 'PointModelTemplate'), Data.handles, Data.handles.dat.plotH);
        case 'ToggleLandmarks'
            Data.handles.dat.plotH = PlotModel(Data.handles.mainAxes, get(Data.handles.AAM, 'PointModelTemplate'), Data.handles, Data.handles.dat.plotH);
        case 'ToggleLines'
            Data.handles.dat.plotH = PlotModel(Data.handles.mainAxes, get(Data.handles.AAM, 'PointModelTemplate'), Data.handles, Data.handles.dat.plotH);
        case 'ToggleZoom'
            [Data.handles] = ToggleZoom(Data.handles);
        case 'TogglePan'
            [Data.handles] = TogglePan(Data.handles);
        case 'LoadModel'
            [Data.handles] = LoadModel(Data.handles);
        case 'GenerateModel'
            [Data.handles] = GenerateModel(Data.handles);
        case 'SaveModel'
            [Data.handles] = SaveModel(Data.handles);
        case 'SelectAAMElements'
            [Data.handles] = SelectAAMElements(Data.handles);
        case 'ChangedImageList'
            [Data.handles] = ChangedImageList(Data.handles);
        case 'Done'
            Data.handles = SaveModel(Data.handles);
            if exist('AAMShapemodel_figure_handle')
                if ishandle(AAMShapemodel_figure_handle)
                    set(AAMShapemodel_figure_handle,'visible','on');
                end
            end
            delete(AAMModelGenerator_handle);
            return;
        otherwise
            error('Unknown Option in AAMToolbox');
    end
    if isfield(Data.handles, 'figMain')
        guidata(Data.handles.figMain, Data);
    end
    set(Data.handles.figMain, 'Pointer', 'arrow');
end
function [named, imagelists] = BuildNamedImageList(handles);
[set_direc, image_direc, ext, vers] = fileparts(get(handles.AAM, 'modelDirec'));
imagelists = FindImageLists(handles);
for i = 1:length(imagelists)
    logical = dir([set_direc, filesep, imagelists{i}, filesep, 'LN_*']);
    if length(logical)>0
        logical = logical(1).name;
        [path, logical, ext, vers] = fileparts(logical);
        logical = logical(4:end);
        named{i} = [imagelists{i}, '  ', logical];
    else
        named{i} = imagelists{i};
    end
end
%%%%%%%%%%%%%%%%%%%%%%
%
%  Changed Image List
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = ChangedImageList(handles);
[named_imageList, imagelists] = BuildNamedImageList(handles);
handles.dat.imagelists = imagelists;
set(handles.imageList, 'String', named_imageList);
% current_imagelist=get(handles.AAM,'modelDirec');
% current_imagelist=current_imagelist(findstr(current_imagelist,'ImageList'):end);
% %which index in the list
% n=regexp(handles.dat.imagelists,current_imagelist);
% for i=1:size(n,2)
%     if strcmp(handles.dat.imagelists{i},current_imagelist)%~isempty(n{i})
%         value=i;
%     end
% end
% set(handles.imageList, 'value', value);
pmt = get(handles.AAM, 'PointModelTemplate');
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);

%modelname=['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(get(handles.AAM, 'pointset')), filesep, 'ImageList_', num2str(get(handles.imageList, 'value')), filesep, 'model.aam_dat'];
imlist = handles.dat.imagelists{get(handles.imageList, 'value')};
modelname=[pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(get(handles.AAM, 'pointset')), filesep, imlist, filesep, 'model.aam_dat'];
modelname
if exist([modelname])
     aam = load(modelname, '-mat');

   % aam = load(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(get(handles.AAM, 'pointset')), filesep, 'ImageList_', num2str(get(handles.imageList, 'value')), filesep, 'model.aam_dat'], '-mat');
    handles.AAM = aam.aam;
    %handles.dat.imagelists{get(handles.imageList, 'value')};
    % ensure that only those images with point models are listed
   % handles.AAM=get_names_with_pm(handles.AAM,handles.workingDir);
    amn=get(handles.AAM, 'am_imagenames'); %unique(get(handles.AAM, 'am_imagenames'));
    set(handles.AAM, 'am_imagenames',amn);
    set(handles.filenamesList, 'String', amn);
    set(handles.modelDirTxt, 'String', get(handles.AAM, 'modelDirec'));
end

%%%%%%%%%%%%%%%%%%%%%%
%
%  Update Image List
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = UpdateImageList(handles)
%activeElements = get(handles.AAM, 'activeElements');
%imagefilenames = get(handles.AAM, 'imageFilenames');
%imagefilenames = dir([pwd, filesep, 'Cropped', filesep, '*.jpg']);
%imagefilenames = {imagefilenames.name};

pmt = get(handles.AAM, 'PointModelTemplate');
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);
currentSet = handles.dat.currentSet;
dirs = dir(['StatisticalModels', filesep, templatename, filesep, currentSet, filesep, 'ImageList*']);
ndirs = {dirs.name};
% found = 0;
% for d = 1:length(dirs)
%     imageindex = load(['StatisticalModels', filesep, templatename, filesep, currentSet, filesep, dirs(d).name, filesep, 'imageindex']);
%     if size(imageindex.imageindex) == size(activeElements)
%         if all(imageindex.imageindex == activeElements)
%             found = d;
%         end
%     end
% end
maxdir = 0;
for i=1:length(ndirs)
    num = str2num(ndirs{i}(11:end));
    if num>maxdir
        maxdir = num;
    end
end
%maxdir = ndirs{end};
%maxdir = str2num(maxdir(11:end));
%if found==0
modelDirec = ['StatisticalModels', filesep, templatename, filesep, currentSet, filesep, 'ImageList_', num2str(maxdir+1)];
mkdir(modelDirec);
% This asks the user for a logical name to associate with the image
% list
prompt={'Enter the logical name of the new image list:'};
name='Name';
numlines=1;
defaultanswer={'FRED'};
answer=inputdlg(prompt,name,numlines,defaultanswer);
if ~isempty(answer)
    d =0;
    save([modelDirec ,filesep, 'LN_', answer{1}], 'd');
else
    save([modelDirec ,filesep, 'LN_FRED'], 'd');
end
imageindex = get(handles.AAM, 'activeElements');
save([modelDirec,filesep, 'imageindex'], 'imageindex');
%for a = activeElements
%    thumbnail = imresize(imread(['Cropped', filesep, imagefilenames{a}]), [100 100]);
%    imwrite(thumbnail, [modelDirec, filesep, imagefilenames{a}], 'JPEG');
%end
imageList = get(handles.imageList, 'String');
imageList{end+1} = ['ImageList_', num2str(maxdir+1)];
set(handles.imageList, 'String',imageList);
set(handles.imageList, 'value',length(imageList));
%handles.AAM  = set(handles.AAM, 'am_imagenames', {imagefilenames{activeElements}});
handles.AAM  = set(handles.AAM, 'imageset', maxdir+1);
handles.AAM  = set(handles.AAM, 'modelDirec', ['StatisticalModels', filesep, templatename, filesep, currentSet, filesep, 'ImageList_', num2str(maxdir+1)]);
handles.AAM  = set(handles.AAM, 'pdmDirec', ['StatisticalModels', filesep, templatename, filesep, currentSet, filesep, 'ImageList_', num2str(maxdir+1)]);
handles.AAM  = set(handles.AAM, 'sfamDirec', ['StatisticalModels', filesep, templatename, filesep, currentSet, filesep, 'ImageList_', num2str(maxdir+1)]);
aam = handles.AAM;
save([modelDirec, filesep, 'model.aam_dat'], 'aam');
%else
%    imageList = dir( ['StatisticalModels', filesep, templatename, filesep, currentSet, filesep, 'ImageList_',found, filesep, '*.jpg']);
%    imageList = {imageList.name};
%    set(handles.imageList, 'String',imageList);
%    set(handles.imageList, 'value',found);
%end
handles = ChangedImageList(handles);
return;
%%%%%%%%%%%%%%%%%%%%%%
%
%  Get Procrustes Params
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = GetProcrustesParams(handles)
procrustesParams.translation =  get(handles.translationChk, 'value');
procrustesParams.rotation =  get(handles.rotationChk, 'value');
procrustesParams.scaling =  get(handles.scalingChk, 'value');
handles.AAM = set(handles.AAM, 'procrustesParams', procrustesParams);
%%%%%%%%%%%%%%%%%%%%%%
%
%  Align Data
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = AlignData(handles)
elements = get(handles.AAM, 'elements');
if length(elements) == 0
    fprintf('There are no elements to align\n');
    return;
end
template = get(handles.AAM, 'PointModelTemplate');
templatename = get(template, 'name');
templatename = templatename(1:length(templatename)-9);
% Prepare ALL the point models for procrustes
for e =1:length(elements)
    pts = get(elements{e}, 'pts');
    if size(pts, 2) >0
        % data(e).marks = pts(:, handles.dat.indices);
        %pts = pts(:, handles.dat.indices);
        pointmodels(:, e) = pts(:);
    end
end
modelDirec=get(handles.AAM,'modelDirec');
details.scaling=get(handles.scalingChk, 'value');
details.rotation=get(handles.rotationChk, 'value');
details.translation=get(handles.translationChk, 'value');
details.pixelnumber=str2num(get(handles.numPixTxt, 'String'));
details.FractionPCs=str2num(get(handles.FractionPCs, 'String'));
save(fullfile(modelDirec,'details.mat'),'details','-mat');

[pointmodels,ProcrustesAlignment] = pmalign(pointmodels,[get(handles.scalingChk, 'value') get(handles.rotationChk, 'value') get(handles.translationChk, 'value')]);
Xm = mean(pointmodels,2);
handles.dat.ProcrustesAlignment = ProcrustesAlignment;
for p=1:length(ProcrustesAlignment)
    pts = pointmodels(:, p);
    pts = project2tangentspace(pts, Xm);
    pts = reshape(pts, 2, length(pts)/2);
    elements{p} = set(elements{p}, 'alignedPts', pts);
    name = get(elements{p}, 'imagefilename');
    proc_data = ProcrustesAlignment(p);
    %save(['PointModels', filesep, templatename, filesep, name(1:length(name)-4), '_procrustes.mat'], 'proc_data');
    save(fullfile(modelDirec,[name(1:length(name)-4),'_procrustes.mat']),'proc_data');
    pts = pts(:);
    %save(['PointModels', filesep, templatename, filesep, name(1:length(name)-4), '_aligned.mat'], 'pts');
    save(fullfile(modelDirec,[name(1:length(name)-4),'_aligned.mat']),'pts');
end
handles.AAM = set(handles.AAM, 'elements', elements);
%%%%%%%%%%%%%%%%%%%%%%
%
%  Perform PCA
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = PerformPCA(handles)
if isfield(handles,'FractionPCs')
    pdm.FractionPCs=str2num(get(handles.FractionPCs,'String'));
else
    pdm.FractionPCs=0.95;
end
[pointsetdirec, a, b, c] = fileparts(get(handles.AAM, 'modelDirec'));
show_in_context = get(handles.context_chk, 'value');
if show_in_context
    e = get(handles.AAM, 'elements');
    [m,n] = size(get(e{1}, 'pts'));
    [Xm, P, b, pcad] = aam_pca(handles.AAM, 1:n, get(handles.filenamesList, 'String'), pdm.FractionPCs, [], 0, 0);
    Xm = reshape(Xm, 2, length(Xm)/2);
    [pdm.Xm, pdm.P, pdm.b, pdm.pca] = aam_pca(handles.AAM, handles.dat.indices, get(handles.filenamesList, 'String'), pdm.FractionPCs, Xm, 1, 0);
    context = 1:size(Xm,2);
    save([pointsetdirec, filesep, 'context.mat'], 'context');
else
    if exist([pointsetdirec, filesep, 'context.mat'])
       delete([pointsetdirec, filesep, 'context.mat']);
    end
    [pdm.Xm, pdm.P, pdm.b, pdm.pca] = aam_pca(handles.AAM, handles.dat.indices, get(handles.filenamesList, 'String'), pdm.FractionPCs, [], 0, 0);
end
pdm.rotate_flag=0;
pdm.subject='';
handles.AAM = set(handles.AAM, 'pdm', pdm);
%%%%%%%%%%%%%%%%%%%%%%
%
%  Generate Model
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = GenerateModel(handles)
if isempty(get(handles.filenamesList, 'String'))
   uiwait(msgbox(sprintf('There are no ''Active Images''. Cannot build model.\nTry Re-Choosing the Template.'),'Ooops','modal'));
    return;
end
%set(handles.generateModelBtn,'BackgroundColor','r');
handles = GetProcrustesParams(handles);
template = get(handles.AAM, 'PointModelTemplate');
templateName = get(template, 'name');
templateName = templateName(1:length(get(get(handles.AAM, 'PointModelTemplate'), 'name'))-9);
D = get(handles.imageList, 'String');

%handles.AAM = set(handles.AAM, 'modelDirec',  ['StatisticalModels', filesep, templateName, filesep, handles.dat.currentSet, filesep, 'ImageList_', num2str(get(handles.imageList, 'value'))]);
[M, N] = size(get(template, 'image'));
completeElements = get(handles.AAM, 'completeElements');
fprintf('Model has %d landmarks\n', length(handles.dat.indices));
disp('Image Used In Model Generation');
%disp(get(handles.filenamesList, 'String'));
%JAB here we need to load the elements i.e. the point model data FROM DISC
handles.AAM=read_in_pointmodels(handles.AAM,handles.workingDir);
w = waitbar(0, 'Calculating statistical models of shape, please wait...');
waitbar(1/5, w);
% Here we align the point models and save the procrustes data in the directory PointModels/<tempaltename>/
handles = AlignData(handles);
waitbar(2/5, w);
handles = PerformPCA(handles);
waitbar(3/5, w);
pdm = get(handles.AAM, 'pdm');
if isempty(pdm.Xm)
    close(w);
    return;
end
aam = handles.AAM;
save( [get(handles.AAM, 'modelDirec'), filesep, get(handles.AAM, 'modelName')], 'aam');
waitbar(4/5);
if exist([get(handles.AAM, 'modelDirec')], 'dir') == 0
    error('Model directory not found, current working directory must be incorrect');
else
    modelName = get(handles.AAM, 'modelName');
    modelName = modelName(1:length(modelName)-10);
    pdm = get(handles.AAM, 'pdm');
    save( [get(handles.AAM, 'modelDirec'), filesep, modelName, '_pdm.mat'], 'pdm');
end
waitbar(5/5, w);
close(w);
options = BuildOptions(handles);
%options.pdm =  [get(handles.AAM, 'modelDirec'), filesep, modelName, '_pdm.mat'];
if get(handles.shape_app_radio_btn, 'value') == 1
    w = waitbar(0, 'Calculating statistical models of appearance, please wait...');
    waitbar(1/5, w);
    set(handles.figMain, 'Pointer', 'watch');
    numPix = str2num(get(handles.numPixTxt, 'String'));
    handles.critical_triangle_expansion=str2num(get(handles.IgnoreTrianglesValue,'String'));
    [sfam, options] = buildsfam(options, numPix, options.FractionPCs, handles.critical_triangle_expansion, templateName, get(handles.verbose_chk, 'value'));
    sfam.critical_triangle_expansion=handles.critical_triangle_expansion;
    waitbar(2/5, w);
    disp('Saving AAM');
    save( [get(handles.AAM, 'modelDirec'), filesep, modelName,  '_sfam.mat'], 'sfam');
    disp('Saved');
    set(handles.figMain, 'Pointer', 'arrow');
    options.sfam = [get(handles.AAM, 'modelDirec'), filesep, modelName,  '_sfam.mat'];
    handles.dat.options = options;
    aam = handles.AAM;
    waitbar(4/5, w);
    save( [get(handles.AAM, 'modelDirec'), filesep, get(handles.AAM, 'modelName')], 'aam');
    waitbar(5/5, w);
    close(w);
    set(handles.generateModelBtn,'Selected','off');
end
options.pdm =  [get(handles.AAM, 'modelDirec'), filesep, modelName, '_pdm.mat'];
handles.AAM = set(handles.AAM, 'pdmDirec', get(handles.AAM, 'modelDirec'));
handles.AAM = set(handles.AAM, 'pdmName', ['pdm.mat']);
handles.AAM = set(handles.AAM, 'sfamDirec', get(handles.AAM, 'modelDirec'));
handles.AAM = set(handles.AAM, 'sfamName', ['sfam.mat']);
handles.AAM = set(handles.AAM, 'options', options);
uiwait(msgbox('Your statistical models have been saved.','Saved','modal'));

%%%%%%%%%%%%%%%%%%%%
%
% Find Existing ImageLists
%
%%%%%%%%%%%%%%%%%%%%
function [imagelists] = FindImageLists(handles)
pmt = get(handles.AAM, 'PointModelTemplate');
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);
imagelists = {};
if exist(['StatisticalModels', filesep, templatename, filesep, handles.dat.currentSet], 'dir')
    files = dir(['StatisticalModels', filesep, templatename, filesep, handles.dat.currentSet, filesep, 'ImageList*']);
    imagelists = {files.name};
else
    warndlg('There is not a directory in statistical models for this template!!\n');
end
%%%%%%%%%%%%%%%%%%%%
%
% Build Options
%
%%%%%%%%%%%%%%%%%%%%
function options = BuildOptions(handles)
% We need to create the default list of options
p = pwd;
PMTDirec = get(get(handles.AAM, 'PointModelTemplate'),'direc');
PMTName = get(get(handles.AAM, 'PointModelTemplate'),'name');
ModelName = get(handles.AAM, 'modelName');
if isfield(handles,'FractionPCs')
    options.FractionPCs=str2num(get(handles.FractionPCs,'String'));
else
    options.FractionPCs=0.95;
end
options.Type = 'soptions';
options.CWD = pwd;
options.InputDirectory = [get(handles.AAM, 'imageDirectory'), filesep];
options.InputFilenames = get(handles.AAM, 'am_imagenames');
options.InputType = 0;
options.InputStartFrame = 1;
options.InputStartMovie = 1;
options.PointModelFile = PMTDirec(length(p)+2:end);
options.MeshFile = '';
options.MeshMappingFile = '';
options.PDMFile = [get(handles.AAM, 'modelDirec'), filesep, ModelName(1:length(ModelName)-10), '_pdm.mat'];
options.GLDMFile = '';
options.SFAMFile = '';
options.SAMFile = '';
options.LabelMode = 0;
options.FitterType = 0;
options.OutputDirectory = '';
options.Output3DVertices = '';
options.Output3DVerticesD = '';
options.OutputShapePCA = '';
options.OutputTexturePCA = '';
options.OutputCombinedPCA = '';
options.OutputType = 0;
options.ShowLandmarkSets = 0;
options.ShowPicture = 1;
options.TryFit = 1;
options.IncludeRotate = 0;
options.GLDMType = 1;
options.FITPOINTTYPE = 1;
options.subject = '';
options.Tryfit = 0;
options.ProcrustesAlignment = handles.dat.ProcrustesAlignment;
options.img = get(get(handles.AAM, 'PointModelTemplate'),'imageName');
options.pdm = '';
options.sfam = '';
options.PMdirectory = ['PointModels', filesep, PMTName(1:length(PMTName)-9), filesep];
options.dat = '';
options.indices = handles.dat.indices;
[pointsetdirec, a, b, c] = fileparts(get(handles.AAM, 'modelDirec'));
if exist([pointsetdirec, filesep, 'context.mat'])
    context = load([pointsetdirec, filesep, 'context.mat']);
    options.indices = context.context;
end
PMTName = PMTName(1:length(PMTName)-9);
options.imagesDir = ['StatisticalModels', filesep, PMTName, filesep, handles.dat.currentSet, filesep, handles.dat.imagelists{get(handles.imageList, 'value')}];
return
%%%%%%%%%%%%%%%%%%%%%%
%
%  SelectAAMElements    //Pretty Obvious
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = SelectAAMElements(handles)
str = dir([pwd, filesep, 'Cropped', filesep, '*.jpg']);
str = {str.name};
if isempty(str)
    warndlg(sprintf('There are no elements in this model.\nUse ModelBuilder to create point models!!!'))
    return;
end
elements = get(handles.AAM, 'elements');
template_size = size(get(get(handles.AAM, 'PointModelTemplate'), 'pts'),2);
activeElements = get(handles.AAM, 'activeElements');
completeElements = get(handles.AAM, 'completeElements');
filenamesList = {};
[s, v] = CustomListDlg(str);
if length(v)>0
    str = get(handles.AAM, 'imageFilenames');
    handles.AAM = set(handles.AAM, 'activeElements', v);
    handles.AAM = set(handles.AAM, 'am_imagenames', {str{v}});
    handles.AAM = set(handles.AAM, 'imageFilenames', {});
    handles.AAM = set(handles.AAM, 'elements', {});
    set(handles.filenamesList, 'String', {str{v}});
else
    return;
end
handles = UpdateImageList(handles);
handles = ChangedImageList(handles);

%%%%%%%%%%%%%%%%%%%%%%
%
%  Save Model    //Pretty Obvious
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = SaveModel(handles)
aam = handles.AAM;
save([get(aam, 'modelDirec'), filesep, get(aam, 'modelName')], 'aam');
disp('Saving');
return;

%%%%%%%%%%%%%%%%%%%%%%
%
%  Load Model    //Pretty Obvious
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = LoadModel(handles)
[filename, pathname] = uigetfile('*.model_dat', 'Pick a File', [handles.workingDir]);
if isequal(filename,0) | isequal(pathname,0)
    disp('User pressed cancel')
else
    model = load([pathname, filesep, filename], '-mat');
    handles.AAM = model.aam;
    handles.workingDir = pathname;
    handles = SetupModel(handles);
end
return;
%%%%%%%%%%%%%%%%%%%%%%
%
%  Setup Model    //Pretty Obvious
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles]  = SetupModel(handles)
handles.dat.plotH = [];
plotTemplate(handles);
set(handles.modelDirTxt, 'String', cut_string(get(handles.AAM, 'modelDirec')));
set(handles.modelNameTxt, 'String', get(handles.AAM, 'modelName'));
%activeElements = get(handles.AAM, 'activeElements');
%filenames = get(handles.AAM, 'imageFilenames');
procrustesParams = get(handles.AAM, 'procrustesParams');
set(handles.translationChk, 'value', procrustesParams.translation);
set(handles.rotationChk, 'value', procrustesParams.rotation);
set(handles.scalingChk, 'value', procrustesParams.scaling);
handles = ChangedImageList(handles);
set(handles.filenamesList, 'String', get(handles.AAM, 'am_imagenames'));
%%%%%%
%
%
%%%%%%
function plotTemplate(handles);
cla(handles.mainAxes);
aam=handles.AAM;
pmt=get(aam,'PointModelTemplate');
im = get(pmt, 'image');
pts = get(pmt, 'pts');
xp = pts(1,:);
yp = pts(2,:);
handles.dat.plotimageH=imagesc(im, 'Parent', handles.mainAxes, 'HitTest', 'off'); axis image ij; set(gca, 'XTickLabel', [], 'YTickLabel', []);
set([handles.mainAxes], 'Visible', 'on');
%%%%%%%%%%%%%%%%%%%%%%
%
%  cut_string   //splits directory names so you can see the beginning and the end
%
%%%%%%%%%%%%%%%%%%%%%%
function [s] = cut_string(s)
if (length(s)>83)
    s = [s(1:40), '...', s(end-40:end)];
end
%%%%%%%%%%%%%%%%%%%%%%
%
%  Toggle Zoom
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = ToggleZoom(handles)
switch(get(handles.zoomBtn, 'Value'))
    case 0
        zoom off;
        set(handles.txtCurrentStatus, 'ForegroundColor', 'black', 'String', 'Zoom is off');
    case 1
        zoom on;
        set(handles.txtCurrentStatus, 'ForegroundColor', 'black', 'String', 'Zoom is on');
    otherwise
        set(handles.txtCurrentStatus, 'ForegroundColor', 'red', 'String', 'Unknown value for zoom mode');
end
%%%%%%%%%%%%%%%%%%%%%%
%
%
%  Toggle Pan
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = TogglePan(handles)
switch(get(handles.panBtn, 'Value'))
    case 0
        pan off;
        set(handles.txtCurrentStatus, 'ForegroundColor', 'black', 'String', 'Pan is off');
    case 1
        pan on;
        set(handles.txtCurrentStatus, 'ForegroundColor', 'black', 'String', 'Pan is on');
    otherwise
        set(handles.txtCurrentStatus, 'ForegroundColor', 'red', 'String', 'Unknown value for pan mode');
end
