function output=AAMToolbox(arg, argoption)
%function output=AAMToolbox(arg, argoption)
%Create or select a Shape Model Project
%     namely a directory structure called: PRJ_*
%
%arg, usually a string identifying what to do
%     by default it initialise the GUI
%argoption, additional information to be passed between calls
%     by default it is empty and ignored
%
%output, usually a copy of non-gui data
%     e.g. AAM, dat
%
%usage:
%To launch the toolbox for replaying only
%AAMToolbox
%To launch the toolbox for model building include your initials
%AAMToolbox('Initialise','JAB')
%Within the AAMToolbox the string provides a command
%AAMToolbox('refresh')
%The second argument provides a extra option
%Finally,
%AAMToolbox(Data) where Data is either
%       an AAMToolbox structure (prevents AAMToolbox initialising from
%       disc)
%       a  Class structure in which case it updates the appropriate part of
%       the AAMToolbox structure (prevents AAMToolbox initialising from
%       disc)
%
%also see
%guide('AAMToolbox.fig'); % to edit the GUI layout
%
%AAMToolbox;        % to manage the creation and display of shape and
%       appearance models
%ModelGenerator; % to create/edit statistical models
%PMTemplateBuilder; % to create/edit and then select a template from which
%       create a new set of pointmodels (that will require dotting in)
%AAMSetPicker;      % to create/edit and then select a subset of points
%       from a template (i.e. set of pointmodels) from which statistical
%       models will be built
%ModelBuilder; % to create/edit and then select a list of pointmodels
%       and associated images from which a statistical model is built
%UpdateModel;       % to ripple changes in template through all derivative
%       pointmodels
%
%Andrew I Hanna, 2005
%(J. Andrew Bangham, 2005)

% The following globals allow all of the GUIs in the
% Shape Model Toolkit to be closed down using the single command
% CloseAAMToolbox
global SETWEIGHTS % this controls the behaviour of weights sliders in pdmwalk
SETWEIGHTS=1; % 0 do not use modify_weights(), 1 to use it



matlab_files_dir = which('AAMToolbox');
%[matlab_files_dir, f, e] = fileparts(matlab_files_dir);
[matlab_files_dir, f, e] = fileparts(matlab_files_dir);
vers = dir([matlab_files_dir, filesep, '*.version']);
vers = {vers.name};
if isempty(vers)
    VersionNumber=1.0;
else
    [p, VersionNumber, e, v] = fileparts(vers{1});
    VersionNumber = str2double(VersionNumber);
end
if nargin>0
    if strcmpi(arg, '-version')
        fprintf('AAMToolbox version: %2.2f\n', VersionNumber);
        return;
    end
end

global AAMShapemodel_figure_handle
global AAMModelGenerator_handle
global AAMModelBuilder_handle
global AAMSetPicker_handle
global UpdateModel_handle
global PMTemplateBuilder_handle
global PDMWalk_handle
global ShapeSpaceTool_handle

% Communication between the GUI's is either through disc files (from which
% AAMToolbox is refreshed every time it is re-entered) or
% through arguments

% Note
% Data.handles.dat  is constructed as required when running the system. It
% holds GUI status information that is neither on disc
% (in AAM structure) or in the GUI itself

if nargin<1
    % Check to make sure that all the library functions are there
    str = AAMToolboxLibraryCheck;
    if ~isempty(str)
        return;
    end
    arg='Initialise';

end
if nargin<2
    argoption='';
end

%  in case the window is invisible
if exist('AAMShapemodel_figure_handle')
    if ishandle(AAMShapemodel_figure_handle)
        set(AAMShapemodel_figure_handle,'visible','on');
    end
end

if ~strcmp(arg,'Quit')
    switch arg
        case 'Initialise'
            Data=Initialise(arg,VersionNumber);
            %Data.handles.VersionNumber=VersionNumber;
            AAMShapemodel_figure_handle=Data.handles.figMain;
            %Data.handles=Update_AAMToolbox_GUI(Data.handles);
        otherwise
            object_handle=findobj('Tag', 'AAMToolbox');
            if isempty(object_handle)
                Data = guidata(AAMShapemodel_figure_handle);
            else
                Data = guidata(findobj('Tag', 'AAMToolbox'));
            end
            Data.handles=Update_AAMToolbox_GUI(Data.handles);

            switch arg
                case 'help'
                    web('http://www2.cmp.uea.ac.uk/~aih/code/ShapeModels/Help/Dummies%20Guide%20To%20Shape%20Models.html', '-browser');
                    %uiwait(msgbox('Something helpfull','Help','help'));
                case 'ShowAbout'
                    D=1:64;D=(D'*D)/64;
                    uiwait(msgbox(sprintf(...
                        'Shape and Appearance Model Toolbox\n\nDr. A. I. Hanna (2005)\naih@cmp.uea.ac.uk\nVersion %f',VersionNumber), ...
                        'About AAMToolbox', 'custom', D, hot(64), 'modal'));
                case {'refresh','get'}
                    Data.handles = InitGUI(Data.handles);
                    disp('Refreshed');
                case 'GenMeanAugShapes'
                    generateMeanAugmentedShapes;
                case 'ShowScalingInfo'
                    showScalingInfo;
                case 'ShowProjectImageNames'
                    Data.handles = ShowProjectImageNames(Data.handles);
                    Data.handles=Update_AAMToolbox_GUI(Data.handles);
                case 'DelSMs'
                    Data.handles = DelSMs(Data.handles);
                    Data.handles=Update_AAMToolbox_GUI(Data.handles);
                case 'SelectModel'
                    [Data.handles] = SelectModel(Data.handles);
                    Data.handles=Update_AAMToolbox_GUI(Data.handles);
               
                    
                case 'ChangeProject'
                    set(Data.handles.figMain, 'Pointer', 'watch');
                    [Data.handles] = ChangeProject(Data.handles);
                    set(Data.handles.figMain, 'Pointer', 'Arrow');
                case 'ScalePointModels'
                    template = get(Data.handles.AAM, 'PointModelTemplate');
                    [templatepath, templatename, ext, vers] = fileparts(get(template, 'name'));
                    pmdir = [pwd, filesep, 'PointModels', filesep, templatename];
                    setScalePointModels(pmdir);
                case 'CustomScaling'
                    scaleAugmentationGroup;
                case 'NewProject'
                    [Data.handles] = NewProject(Data.handles);
                case 'CreateMaskForTemplate'
                    MaskMaker;
                case 'CreateFigures'
                    aam = Data.handles.AAM;
                    modeldir = [pwd, filesep, get(aam,'modelDirec')];
                    FigureCreator('ModelDir', modeldir);
                case 'ImportSimpleShape'
                    [Data.handles] = ImportSimpleShape(Data.handles);
                case 'NewSet'
                    SetPicker('init');
                    % collect the revised data structure next time an AAMToolbox button is pressed
                case 'MakeTemplate'

                    % Begin change by js, 070429
                    % Begin original code

                    % PMTemplateBuilder('init');

                    % End original code
                    % Begin replacement code
                    projectDirectory = pwd;

                    if ~isProject3D(projectDirectory)
                        PMTemplateBuilder('init');
                    else
                        set(AAMShapemodel_figure_handle, 'Visible', 'off');
                        aam = Data.handles.AAM;
                        templateBuilder3DTool(...
                            'projectDirectory', projectDirectory);
                        set(AAMShapemodel_figure_handle, 'Visible', 'on');
                    end

                    % End replacement code
                    % End change by js, 070429


                case 'ShowDetails'
                    ShowDetails('init');
                case 'ModelBuilder'
                    aam = Data.handles.AAM;
                    if isempty(get(aam, 'modelName'))
                        uiwait(msgbox(sprintf('Cannot find a model name, Please Choose a Template'),'Invalid Point and Statistical Model Structure', 'modal'));
                    else
                        if isempty(get(aam, 'imageFilenames'))
                            uiwait(warndlg('There are no images in this model, please check the Cropped directory!!!'));
                        else
                            %handles = TurnOffAll(handles);

                            % Begin change by js, 070312
                            % Begin original code

                            %                             ModelBuilder(aam);

                            % End original code
                            % Begin replacement code
                            projectDirectory = pwd;

                            if ~isProject3D(projectDirectory)
                                ModelBuilder(aam);
                            else
                                set(AAMShapemodel_figure_handle, 'Visible', 'off');
                                modelBuilder3DTool('aam', aam, ...
                                    'projectDirectory', projectDirectory);
                                set(AAMShapemodel_figure_handle, 'Visible', 'on');
                            end

                            % End replacement code
                            % End change by js, 070307
                        end
                    end
                case 'BuildHierarchy'
                    HierarchyBuilder('init');
                case 'CreateNewModel'
                    [Data.handles] = CreateNewModel(Data.handles);
                    Data.handles=Update_AAMToolbox_GUI(Data.handles);
                    Data.handles=InitGUI(Data.handles);
                case 'ImportGroupMeans'
                    [Data.handles] = ImportGroupMeans(Data.handles);
                    Data.handles=Update_AAMToolbox_GUI(Data.handles);
                case 'RefreshGUI'
                    Data.handles=Update_AAMToolbox_GUI(Data.handles);
                    Data.handles=InitGUI(Data.handles);
                case 'PDMWalk'
                    aam = Data.handles.AAM;
                    % indices = get(aam, 'pointindices');
                    pdmfile = [pwd, filesep, get(aam,'modelDirec'), filesep, 'mod_pdm.mat'];
                    sfamfile = [pwd, filesep, get(aam,'modelDirec'), filesep, 'mod_sfam.mat'];
                    template = get(Data.handles.AAM, 'PointModelTemplate');
                    loops = get(template, 'loops');
                    edges = loops{1};
                    [templatepath, templatename, ext, vers] = fileparts(get(template, 'name'));
                    pmdir = [pwd, filesep, 'PointModels', filesep, templatename];
                    if ~exist(sfamfile, 'file')
                        sfamfile = '';
                    end
                    if exist(pdmfile, 'file')
                        details = get(aam, 'procrustesParams');
                        set(AAMShapemodel_figure_handle, 'Visible', 'off');
                        indices = get(aam, 'pointindices');
                        if isfield(Data.handles,'Facets')
                            ModelViewer('PDMfile', pdmfile, 'SFAMfile', sfamfile, 'pmdirectory', pmdir, ...
                                'Edges', edges, 'imdirectory', 'Cropped', 'details', details, ...
                                'indices', indices, 'Facets', Data.handles.Facets);
                        else
                            ModelViewer('PDMfile', pdmfile, 'SFAMfile', sfamfile, 'pmdirectory', pmdir, ...
                                'Edges', edges, 'imdirectory', 'Cropped', 'details', details, 'indices', indices);
                        end
                        set(AAMShapemodel_figure_handle, 'Visible', 'on');
                    else
                        warndlg('You must run the SMG Tool first');
                    end
                case 'ModelGenerator'
                    if isempty(get(Data.handles.AAM,'imageFilenames')) % need to load the aam structure
                        Data.handles = FreshAAM(Data.handles);
                    end
                    aam = Data.handles.AAM;
                    if isempty(get(aam, 'imageFilenames'))
                        uiwait(warndlg('There are no images in this model, please check the Cropped directory!!!'));
                    else
                        %ModelGenerator(aam);
                        template = get(aam, 'PointModelTemplate');
                        templatename = ['Templates', filesep, get(template, 'name')];
                        pointset = get(aam, 'pointset');
                        if exist(templatename)
                            template = load(templatename, '-mat');
                            template = template.PMTemplate;
                            set(AAMShapemodel_figure_handle, 'Visible', 'off');
                            ModelGeneratorTool('Template', template, 'PointSet', ['Set_', num2str(pointset)]);
                            set(AAMShapemodel_figure_handle, 'Visible', 'on');
                            Data.handles = InitGUI(Data.handles);
                        end
                    end

                case 'ShapeSpaceTool'
                    if isempty(get(Data.handles.AAM,'imageFilenames')) % need to load the aam structure
                        Data.handles = FreshAAM(Data.handles);
                    end
                    aam = Data.handles.AAM;
                    if isempty(get(aam, 'imageFilenames'))
                        uiwait(warndlg('There are no images in this model, please check the Cropped directory!!!'));
                    else
                        template = get(Data.handles.AAM, 'PointModelTemplate');
                        moddir = get(aam, 'modelDirec');
                        pdmfile = [pwd, filesep, moddir, filesep, 'mod_pdm.mat'];
                        sfamfile = [pwd, filesep, moddir, filesep, 'mod_sfam.mat'];
                        detailsfile  = [pwd, filesep, moddir, filesep, 'details.mat'];
                        if ~exist(pdmfile, 'file')
                            uiwait(msgbox('There is no statistical shape information for this model.','No PDM','modal'));
                            return;
                        end
                        pdm = load(pdmfile); pdm = pdm.pdm;
                        sfam = [];
                        details.scaling = 1; details.rotation = 1; details.translation = 1;
                        details = get(aam, 'procrustesParams');
                        if exist(sfamfile, 'file') 
                            sfam = load(sfamfile); 
                            sfam = sfam.sfam; 
                        end
                        indices = get(aam, 'pointindices');
                        fprintf('Model from directory: %s\n', moddir);
                        set(AAMShapemodel_figure_handle, 'Visible', 'off');
%                         ShapeSpaceTool('template', template, 'pdm', pdm, 'sfam', sfam, 'details', details, 'indices', indices);
                        if isfield(Data.handles,'Facets')
                            ShapeSpaceTool('template', template, 'pdm', pdm, 'sfam', sfam,...
                                'details', details, 'indices', indices, 'Facets', Data.handles.Facets);
                        else
                            ShapeSpaceTool('template', template, 'pdm', pdm, 'sfam', sfam,...
                                'details', details, 'indices', indices);
                        end
                        set(AAMShapemodel_figure_handle, 'Visible', 'on');
                    end
                case 'AutomaticPlacement' % There is a problem
                    % 1) select interior point
                    % 2) click on primary points IN ORDER
                    % 3) does not complete before doing the wrong thing
                    aam = Data.handles.AAM;
                    AutomaticPlacement(aam);
                case 'PreProcessImages'
                    aam = Data.handles.AAM;
                    PreProcessImages(aam);
                case 'ImportProjects'
                    [Data.handles] = ImportProjects(Data.handles);
                case 'MakeAugmentedTemplate'
                    MakeAugmentedTemplate;
                case 'OrderAugmentedPointModels'
                    OrderAugmentedPointModels;
                case 'BuildAugmentedPointModels'
                    BuildAugmentedPointModels;
                case 'OrganizeAugmentedShapes'
                    pdmfilename = [get(Data.handles.AAM, 'modelDirec'), filesep, 'mod_pdm.mat'];
                    template = get(Data.handles.AAM, 'PointModelTemplate');
                    loops = get(template, 'loops');
                    loops = loops{1};
                    OrganizeAugmentedShapes('pdmfilename', pdmfilename, 'edges', loops);
                case 'ExportModel'
                    aam = Data.handles.AAM;
                    modelfilename = [get(aam, 'modelDirec'), filesep, get(aam, 'modelName')];
                    exportModelData(modelfilename);
                case 'ExportShapeEigenData'
                    fprintf(' - exporting eigenvectors and eigenvalues\n');
                    aam = Data.handles.AAM;
                    if isempty(get(aam, 'imageFilenames'))
                        uiwait(warndlg('There are no images in this model, please check the Cropped directory!!!'));
                    else
                        template = get(Data.handles.AAM, 'PointModelTemplate');
                        moddir = get(aam, 'modelDirec');
                        pdmfile = [pwd, filesep, moddir, filesep, 'mod_pdm.mat'];
                        sfamfile = [pwd, filesep, moddir, filesep, 'mod_sfam.mat'];
                        detailsfile  = [pwd, filesep, moddir, filesep, 'details.mat'];
                        if ~exist(pdmfile, 'file')
                            uiwait(msgbox('There is no statistical shape information for this model.','No PDM','modal'));
                            return;
                        end
                        pdm = load(pdmfile); pdm = pdm.pdm;
                        export_eigen_data(pdm);
                    end
                case 'ShowGrpModelEstimates'
                    aam = Data.handles.AAM;
                    show_group_model_estimates(get(aam, 'modelDirec'));
                case 'MakeShapePCMatrix'
                    aam = Data.handles.AAM;
                    extract_shape_PC_data(get(aam, 'modelDirec'));
                case 'ShapePCMat2Excel'
                    shapematrix2excell;
                case 'PMErrorCalc'
                    mse = aamlib_calcPMError;
                case 'DevProjErr'
                    [ratio, origDist, projDist] = aamlib_calcProjError;
                case 'ViewGrowth'
                    if isfield(Data.handles,'Facets')
                        ViewGrowthTool('fromaamtoolbox',Data.handles.Facets);
                    else
                        ViewGrowthTool('fromaamtoolbox');
                    end
                otherwise
                    error('Unknown Option in AAMToolbox');
            end
    end
    guidata(Data.handles.figMain, Data);
else
    clear global;
    remaining_globals = whos('global');
    if length(remaining_globals)>0
        fprintf('Warning!!! Some global variables have remained active\n');
    end
    closereq;
    CloseAAMtoolbox;
    return;
end
output=Data.handles.AAM;
%%%%%%%%%%%%%%%%%%%%
%
% DelSMs
%
%%%%%%%%%%%%%%%%%%%%
function handles = DelSMs(handles)
if ~isfield(handles.dat, 'templatename')
    fprintf('Field handles.dat.templatename has not yet been defined\n');
    return;
end
recycle on;
SMDir = [pwd, filesep, 'StatisticalModels', filesep, handles.dat.templatename];
if ~exist(SMDir, dir)
    fprintf('Statistical Models: %s does not exist. Cannot delete.\n', SMDir);
    return;
end
rmdir(SMDir,'s');
%%%%%%%%%%%%%%%%%%%%
%
% ShowProjectImageNames
%
%%%%%%%%%%%%%%%%%%%%
function handles = ShowProjectImageNames(handles)
aam = handles.AAM;
filenames = get(aam, 'am_imagenames');
if ~isempty(filenames)
    [s,v] = listdlg('ListSize', [300 200], 'Name', 'Filename List', 'PromptString','Current Image Filenames','SelectionMode','single','ListString',filenames);
else
    fprintf('There are no filenames to show\n');
end
return;

%%%%%%%%%%%%%%%%%%%%
%
% Initialize
%
%%%%%%%%%%%%%%%%%%%%
function Data=Initialise(arg,argoption)
if nargin<2
    argoption='';
    VersionNumber=0.0;
else
    VersionNumber=argoption;
end
p = which ('AAMToolbox');
p = fileparts(fileparts(fileparts(p)));
% if isempty( strfind(pwd, 'Models'))
%     if ~exist([p, filesep, 'Models'])
%         uiwait(warndlg(sprintf(...
%            'You must have a directory called Models.\n i.e. C:\\...\\Shape_models\\Models\nSee Dummies Guide for more details.'),...
%            'Directory Hierarchy Error!'));
%         directoryname = '';
%                 while ~strcmp(directoryname, 'Models')
%                     directoryname = uigetdir(pwd, sprintf(...
%                     'You must have a directory called Models.\n i.e. C:\\...\\Shape_models\\Models\nSee Dummies Guide for more details.'));
%                     [path, directoryname, ext, vers] = fileparts(directoryname);
%                 end
%     end
%     cd([p, filesep, 'Models']);
% end
if nargin == 2 && ischar(argoption)
    fprintf('Author: %s, model editing allowed\n', argoption);
end
%close all;
% Open the GUI for display
%fig = openfig(mfilename, 'reuse');
fig = openfig(mfilename, 'new');
movegui(fig, 'center');

% Generate a structure of handles to pass to callbacks, and store
Data.handles = guihandles(fig);
set(fig, 'Color', get(Data.handles.uipanel1, 'BackgroundColor'));
set(fig, 'Visible', 'on');
Data.handles.figMain = fig;
Data.handles.AAM = AAM;
Data.handles.VersionNumber=VersionNumber;
Data.handles = InitGUI(Data.handles);
Data.guilevel = getGUILevelInfo;
Data.handles = SetGUILevel(Data.handles, Data.guilevel);
%%%%%%%%%%%%%%%%%%%%
%
% SetGUILevel
%
%%%%%%%%%%%%%%%%%%%%
function handles = SetGUILevel(handles, level)
if level==1
    set(handles.imageProcBtn, 'Visible', 'off');
    set(handles.showDetailsBtn, 'Visible', 'off');
end

%%%%%%%%%%%%%%%%%%%%
%
% Fresh AAM
%
%%%%%%%%%%%%%%%%%%%%
function handles = FreshAAM(handles)
% keep handles but replace AAM from disc
% and the current status of the AAMToolbox, i.e.
% current Project
% string and value of Current Model selected
aam=AAM; %Data.handles.AAM;
am_imagenames = {};
modelstrings=get(handles.currentModelTxt,'string');
value=get(handles.currentModelTxt,'value');
modelstring=modelstrings{value};
%reconstruct correct models name
Modelname2=fullfile('StatisticalModels',modelstring);
Modelname3=Modelname2(1:findstr(Modelname2,'[')-2);
Modelname=fullfile(Modelname3,'model.aam_dat');
templatename1=modelstring(length('StatisticalModels')+2:end);
setname1=templatename1(findstr(templatename1,filesep)+1:end);
templatename=templatename1(1:findstr(templatename1,filesep)-1);
setname=setname1(1:findstr(setname1,filesep)-1);
imagelist1=setname1(findstr(setname1,filesep)+1:end);
imagelist=imagelist1(1:findstr(imagelist1,filesep)-1);
aam=set(aam,'imageDirectory','Cropped');
aam=set(aam,'modelDirec',fullfile('StatisticalModels',templatename,setname,imagelist));
aam=set(aam,'modelDirec',fullfile('StatisticalModels',templatename,setname,imagelist));
aam=set(aam,'sfamDirec',fullfile('StatisticalModels',templatename,setname,imagelist));
d=[dir(['Cropped', filesep, '*.jpg']),dir(['Cropped', filesep, '*.JPG'])];
nc=cell(1,length(d));
for i=1:length(d)
    nc(i)={d(i).name};
end
aam=set(aam,'imageFilenames',nc);
% temporarily set the following
aam=set(aam,'am_imagenames',{d.name});
aam=set(aam,'modelName','model.aam_dat');
aam=set(aam,'pdmName','pdm.mat');
aam=set(aam,'sfamName','sfam.mat');
[pwd, filesep, 'Templates', filesep, templatename,'.temp_dat']
if ~exist([pwd, filesep, 'Templates', filesep, templatename,'.temp_dat'])
    uiwait(warndlg('Template found in AAM is not on disk, aborting','Template not found'));
    return;
end
pmt = load(['Templates', filesep, templatename,'.temp_dat'], '-mat');
aam=set(aam,'PointModelTemplate',pmt.PMTemplate);
d2=dir(['PointModels', filesep, templatename, filesep, '*_pm.mat']);
ncpm=cell(1,length(d2));
for i=1:length(d2)
    ncpm(i)={d2(i).name};
end
completeElements=[];
k=1;
for i=1:length(ncpm)
    am_imagename=d(i).name;
    r=regexp(nc,am_imagename);
    for j=1:length(r)
        if ~isempty(r{j})
            completeElements=[completeElements,j];
            am_imagenames{k}=d(i).name;
            k=k+1;
        end
    end
end
aam=set(aam,'completeElements',completeElements);
aam=set(aam,'pointset',[]);
aam=set(aam,'am_imagenames',am_imagenames);
aam=set(aam,'pointset',str2num(setname(findstr(setname,'Set_')+4:end)));
aam=set(aam,'imageset',1);
pts=get(pmt.PMTemplate,'pts');
indices=1:size(pts,2);
aam=set(aam,'pointindices',indices);

modelfilename=[get(aam, 'modelDirec'), filesep, get(aam, 'modelName')];
save(modelfilename, 'aam');
disp(sprintf('Replaced %s with a fresh model file that has',modelfilename))
disp('no statistical models. Please run AAM Editor');
%%%%%%%%%%%%%%%%%%%%
%
% MakeStatisticalModelsIfNeeded
%
%%%%%%%%%%%%%%%%%%%
function handles = MakeStatisticalModelsIfNeeded(handles)
d=dir('PointModels');
for i=3:length(d)
    template=d(i).name;
    dd=dir(['PointModels',filesep, template]);
    n=regexp({dd.name},'_pm');
    if ~isempty(n) % there are PointModels in this template
        % is there a Statistical Model?
        if ~exist([pwd, filesep, 'StatisticalModels'])
            mkdir([pwd, filesep, 'StatisticalModels']);
        end
        if ~exist([pwd, 'StatisticalModels', filesep, template])
            pmt = load([pwd, filesep, 'Templates', filesep, template,'.temp_dat'], '-mat');
            pmt = pmt.PMTemplate;
            handles=CreateNewModel(handles,pmt);
        end
    end

end
%%%%%%%%%%%%%%%%%%%%
%
% reload_image_model_icons
%
%%%%%%%%%%%%%%%%%%%
function reload_image_model_icons(AAMToolboxAxis_handle,AAMToolbox_plot_data_handle,template)
% requires AAM to be up-to-date
d=[dir('*.jpg'),dir('*.JPG')];
if isempty(d)
    d=[dir(['Cropped', filesep, '*.jpg']),dir(['Cropped', filesep, '*.JPG'])];
    if ~isempty(d)
        imagefilename=d(1).name;
        x=imread(['Cropped', filesep, imagefilename]);
        xsmall=imresize(x,0.25);
        imwrite(xsmall,'example.jpg');
    else
        x = zeros(5,5,3);
    end
else
    imagefilename=d(1).name;
    x=imread(imagefilename);
end
image(x,'parent',AAMToolboxAxis_handle);
axis(AAMToolboxAxis_handle, 'image', 'ij');
set(AAMToolboxAxis_handle,'visible','off');
cla(AAMToolbox_plot_data_handle);
if ~isempty(template)
    pts=get(template,'pts');
    h = [];
    loops = get(template, 'loops');
    hold(AAMToolbox_plot_data_handle, 'on');
    if length(loops)>0
        edges = loops{1};
        for e = 1:size(edges,1)
            h(end+1) = plot(AAMToolbox_plot_data_handle, ...
                [pts(1, edges(e,1)),pts(1, edges(e,2))], ...
                [pts(2, edges(e,1)),pts(2, edges(e,2))], ...
                '-r', 'LineWidth', 1.5, 'MarkerEdgeColor', [112/255 91/255 223/255], 'HitTest', 'off');
        end
    end
    if size(pts,2)>0
        h(end+1)=plot(AAMToolbox_plot_data_handle, ...
            pts(1, :), pts(2,:), 'o','linewidth',0.1,...
            'marker','o', 'MarkerEdgeColor', 'b', ...
            'MarkerFaceColor', 'y', 'MarkerSize', 2, 'HitTest', 'off');
    end
    axis(AAMToolbox_plot_data_handle, 'image', 'ij');
else
    cla(AAMToolbox_plot_data_handle);
end
set(AAMToolbox_plot_data_handle,'visible','off');
%%%%%%%%%%%%%%%%%%%%
%
% reload_updated_disc_data
%
%%%%%%%%%%%%%%%%%%%
function Data=reload_updated_disc_data(Data)
d=[dir('*.jpg'),dir('*.JPG')];
if isempty(d)
    d=[dir(['Cropped', filesep, '*.jpg']),dir(['Cropped', filesep, '*.JPG'])];
    imagefilename=d(1).name;
    x=imread(['Cropped', filesep, imagefilename]);
    xsmall=imresize(x,0.25);
    imwrite(xsmall,'example.jpg');
else
    imagefilename=d(1).name;
    x=imread(imagefilename);
end
Data.handles.AAM_plot_image=image(x,'parent',Data.handles.AAMToolboxAxis);
set(Data.handles.AAMToolboxAxis,'visible','off');
if exist('Data')
    if isfield(Data,'handles')
        if isfield(Data.handles,'AAMToolbox_plot_data')
            if ishandle(Data.handles.AAMToolbox_plot_data)
                delete(Data.handles.AAMToolbox_plot_data);
            end
        end
    end
end
if ~isempty(get(Data.handles.AAM, 'modelDirec'))
    tempname=[pwd, filesep, get(Data.handles.AAM, 'modelDirec'), filesep, get(Data.handles.AAM, 'modelName')];
    if exist(tempname)
        tempname=[get(Data.handles.AAM, 'modelDirec'), filesep, get(Data.handles.AAM, 'modelName')];
        aam = load([get(Data.handles.AAM, 'modelDirec'), filesep, get(Data.handles.AAM, 'modelName')], '-mat');
        %Data = guidata(Data.handles.figMain);
        Data.handles.AAM = aam.aam;
        t=get(Data.handles.AAM,'PointModelTemplate');
        %x=get(t,'image');
        Data.handles.AAMToolbox_plot_data = PlotModel(Data.handles.AAMToolbox_plot, t, Data.handles, [],1);
        set(Data.handles.AAMToolbox_plot,'visible','off');
        set(Data.handles.AAMToolbox_plot_data,'linewidth',0.1);
        set(Data.handles.AAMToolbox_plot_data,'marker','.');
        % update teh Current Point Set popup
        Data.handles = FindSets(Data.handles);
        sets1=Data.handles.dat.sets;
        ind=get(Data.handles.AAM,'imageset');
        set(Data.handles.SetList,'string',sets1(ind));
        Data.handles = UpdateGUI(Data.handles);
    end
else
    msg_h=msgbox('There are no models in this project');
    pause(1);
    if ishandle(msg_h)
        delete(msg_h);
    end
end
%%%%%%%%%%%%%%%%%%%%
%
% Fill all projects
%
%%%%%%%%%%%%%%%%%%%%
function [projs] = FindProjects(root_dir, projs)
files = dir(root_dir);
files = {files.name};
for f = 1:length(files)
    filename = files{f};
    if (filename(1)~='.') & (isdir([root_dir, filesep, filename]))
        if length(filename)>3
            if strcmp(filename(1:3), 'PRJ')
                projs{end+1} = [root_dir, filesep, filename];
            else
                projs = FindProjects([root_dir, filesep, filename], projs);
            end
        end
    end
end
return;

%%%
%
%
%%%
function found = construct_project_directories(handles, project_directory)
found = 0;
if ~exist(project_directory, 'dir');
    mkdir(project_directory);
else
    str = sprintf('A project with this name already exists.\nSwitching to that project');
    uiwait(msgbox(str,'Sorry','modal'));
    found = 1;
    return;
end;
if ~exist([project_directory, filesep, 'Original'], 'dir'); mkdir([project_directory, filesep, 'Original']); end;
if ~exist([project_directory, filesep, 'Cropped'], 'dir'); mkdir([project_directory, filesep, 'Cropped']); end;
if ~exist([project_directory, filesep, 'Templates'], 'dir'); mkdir([project_directory, filesep, 'Templates']); end;
if ~exist([project_directory, filesep, 'PointModels'], 'dir'); mkdir([project_directory, filesep, 'PointModels']); end;
if ~exist([project_directory, filesep, 'StatisticalModels'], 'dir'); mkdir([project_directory, filesep, 'StatisticalModels']); end;
if ~exist([project_directory, filesep, 'Groups'], 'dir'); mkdir([project_directory, filesep, 'Groups']); end;
cd(project_directory);
if ~checkDir(project_directory, handles)
    error('Could not create directory structure properly please contact the administrator for AAMToolbox');
end
return


%%%%%%%%%%%%%%%%%%%%
%
% New Project
%
%%%%%%%%%%%%%%%%%%%%
function [handles] = NewProject(handles)
cwd=pwd;
cwd=fileparts(cwd);
directoryname = uigetdir(cwd,'Place the new project in current directory or change');
if directoryname == 0
    return;
end
prompt={'Please enter the name of the new project:'};
name='Name';
numlines=1;
defaultanswer={''};
options.Resize='on';
options.WindowStyle='modal';
options.Interpreter='tex';
answer=inputdlg(prompt,name,numlines,defaultanswer, options);
if isempty(answer)
    return;
end
if isempty(answer{1})
    return;
end
project_directory = [directoryname, filesep, 'PRJ_', answer{1}];
found = construct_project_directories(handles, project_directory);
if found
    handles = ChangeProject(handles, project_directory);
    return;
end
handles = InitGUI(handles);
ButtonName=newProjectDialog();

switch ButtonName,
    case 'new3D',
        % Create file that identifies this as a 3D project
        file = fullfile(project_directory, 'project3D.type');
        save(file);
    case 'combination',
        [handles] = CombineProjects(handles, project_directory);
    case 'augmented',
        [handles] = AugmentProjects(handles, project_directory);
end

return;
%%%
%
%
%%%
function [handles] = AugmentProjects(handles, project_directory)
% From the root Models directory build a list of all projects and allow the
% user to select from this list.
root_models_dir = uigetdir(pwd, 'Please choose the root projects directory, i.e. ''../Shape_Models/Models''');
if root_models_dir == 0
    fprintf('User pressed cancel\n');
    return;
end
if ~isempty(root_models_dir)
    projs = FindProjects(root_models_dir, {});
else
    fprintf('There must be a root project directory\n');
    return;
end
if isempty(projs)
    return;
end
fprintf('Building list of project from root project directory %s\n', 'Models');
% 2. Display the list and allow the user to select
[s,v] = listdlg('PromptString','Select a file:', 'SelectionMode','multiple', 'ListString',projs, 'ListSize', [800 300]);
% 3. Combine the projects into the new desired project (we must append the project name to the {image/pointmodel/etc..} filenames
if isempty(s)
    return;
end
indx = 1;
augment_info = getAugmentInfo(s, projs);
for i=1:length(augment_info)
    copyProjectImages([augment_info(i).projectdir, filesep, 'Cropped'], [pwd, filesep, 'Cropped'])
end
if isempty(augment_info)
    return;
end
datadir = [pwd, filesep, 'Data'];
if ~exist(datadir, 'dir');
    mkdir(datadir);
end
save([datadir, filesep, 'augment_info'], 'augment_info');
%%%
%
%
%%%
function copyProjectImages(sourceDir, destDir)
filenames = dir([sourceDir, filesep, '*.jpg']);
filenames = {filenames.name};
[pathname, parent_dir, ext, vers] = fileparts(sourceDir);
[pathname, parent_dir, ext, vers] = fileparts(pathname);
w_h = waitbar(0, sprintf('Copying image files for %s\nplease wait...', parent_dir));
set(findall(w_h,'type','text'),'Interpreter','none')
M = length(filenames);
for i=1:M
    waitbar(i/M, w_h);
    file = filenames{i};
    [success, mesg, mesgid] = copyfile([sourceDir, filesep, file], [destDir, filesep, file]);
end
close(w_h);
%%%%%
%
%
%%%%%
function [pathname, filename] = getGroupFile

[filename, pathname] = uigetfile('*.mat', 'Pick a group file', [pwd, filesep, 'Groups', filesep]);
if isequal(filename,0) || isequal(pathname,0)
    disp('User pressed cancel')
else
    disp(['User selected ', fullfile(pathname, filename)])
end
%%%
%
%
%%%
function [handles] = ImportGroupMeans(handles)
set(handles.figMain, 'Pointer', 'arrow');
modelDirec = get(handles.AAM, 'modelDirec');
template = get(handles.AAM, 'PointModelTemplate');
edges = get(template, 'loops');
if length(edges)>0
    edges = edges{1};
else
    edges = [];
end
templatename = get(template, 'name');
[temppath, templatename, ext, vers] = fileparts(templatename);

[pathname, filename] = getGroupFile;
if (filename==0) & (pathname == 0)
    return
end
groupfilename = [pathname, filesep, filename];
%groupfilename = [pwd, filesep, modelDirec, filesep, 'groups.mat'];
if ~exist(groupfilename)
    uiwait(msgbox('There are no groups defined yet for this model.','No Group','modal'));
    return;
end
groups = load(groupfilename);
if ~isfield(groups, 'groups')
    fprintf('Not a valid groups file\n');
    return;
end
groups = groups.groups;
[groupindx,v] = listdlg('Name', 'Group Selection', 'PromptString','Select Group''s:', 'SelectionMode','multiple','ListString',{groups.name}, 'ListSize', [300 160]);
if isempty(groupindx)
    return;
end
groups = groups(groupindx);
point_models_dir = [pwd, filesep, 'PointModels', filesep, templatename, filesep];
procrustes_params = get(handles.AAM, 'procrustesParams');
disp('Current procrustes params');
disp(procrustes_params);

%[option, customscalingflag] = BuildAugmentedPointModelsDialog;
%opts = ProcrustesParamsDlg;
normalize_size = questdlg('Normalize shapes for size?', 'Normalize Size', 'Yes', 'No', 'Yes');
opts.scaling = 1;
opts.rotation = 1;
opts.translation = 1;
if strcmp(normalize_size, 'No')
    opts.scaling = 0;
end
figh = figure;
rows = 2;
cols = 2;
indx = 1;
for i=1:length(groups)
    group = groups(i);
    [X] = load_group_pointmodels(templatename, group.elements);
    [xaligned, template] = pcalib_GPA('data', X, 'opts', opts, 'dimension', 2);
    %[xaligned, proc_alignment] = pmalign(X, opts);
    Xm = mean(xaligned, 2);
    if indx>rows*cols
        figh = figure;
        indx = 1;
    end
    axish = subplot(rows, cols, indx); indx = indx + 1;
    plotGroup(axish, xaligned, Xm, edges, group.name);
    pts = Xm(:);
    filename = [point_models_dir, filesep, 'MEAN_GROUP_', group.name,'_pm.mat'];
    fprintf('Saving mean shape for group %s\n', ['MEAN_GROUP_', group.name]);
    save(filename, 'pts');
    [mean_appearance] = mean_group_image(templatename, group.elements, Xm);
    filename = ['Cropped', filesep, 'MEAN_GROUP_', group.name,'.jpg'];
    imwrite(mean_appearance, filename);
end
return;
%%%
%
%%%
function plotGroup(axish, X, Xm, edges, name)
cla(axish);
hold(axish, 'on');
N = size(X,2);
N = min(N, 20);
for j=1:N
    x = reshape(X(:,j), 2, length(X(:,j))/2);
    plot(axish, x(1,:), x(2,:), 'o', 'MarkerEdgeColor', 'y', 'MarkerFaceColor', 'r');
    for i=1:size(edges,1)
        plot(axish, [x(1, edges(i,1)), x(1, edges(i,2))], [x(2, edges(i,1)), x(2, edges(i,2))], 'y-');
    end
end

Xm = reshape(Xm, 2, length(Xm)/2);
plot(axish, Xm(1,:), Xm(2,:), 'o', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'g');
for i=1:size(edges,1)
    plot(axish, [Xm(1, edges(i,1)), Xm(1, edges(i,2))], [Xm(2, edges(i,1)), Xm(2, edges(i,2))], 'g-');
end
axis(axish, 'image', 'xy');
grid(axish, 'on');
title(axish, name, 'Interpreter', 'none');
drawnow;
return;


%%%
%
%
%%%
function [handles] = ImportCombinedProjectMeans(handles)
set(handles.figMain, 'Pointer', 'arrow');

if exist('combined_prj_details.mat', 'file')==0
    return;
end
if ~isfield(handles, 'AAM')
    return;
end
template = get(handles.AAM, 'PointModelTemplate');
if isempty(template)
    return;
end
templatename = get(template, 'name');
[templatepath, templatename, ext, vers] = fileparts(templatename);
if isempty(templatename)
    return;
end
prj_details = load('combined_prj_details');

if ~isfield(prj_details, 'prj_details')
    return;
end
set(handles.figMain, 'Pointer', 'watch');
prj_details = prj_details.prj_details;
[prj_details] = calculate_group_shape_means(prj_details, templatename);
[image_filenames] = calculate_group_appearance_means(prj_details, templatename);
current_image_filenames = get(handles.AAM, 'imageFilenames');
for i=1:length(image_filenames)
    filename = image_filenames{i};
    found = 0;
    for ii = 1:length(current_image_filenames)
        if strcmp(current_image_filenames{ii}, filename)
            found = 1;
        end
    end
    if found == 0
        current_image_filenames{end+1} = filename;
    end
end
%current_image_filenames = [current_image_filenames, image_filenames];
handles.AAM = set(handles.AAM, 'imageFilenames', current_image_filenames);
aam = handles.AAM;
save([pwd, filesep, get(aam, 'modelDirec'), filesep, get(aam, 'modelName')], 'aam');
set(handles.figMain, 'Pointer', 'arrow');
return;
%%%
%
%
%%%
function [handles] = CombineProjects(handles, project_directory)
% From the root Models directory build a list of all projects and allow the
% user to select from this list.
root_models_dir = uigetdir(pwd, 'Please choose the root projects directory, i.e. ''../Shape_Models/Models''');
if root_models_dir == 0
    fprintf('User pressed cancel\n');
    return;
end
if ~isempty(root_models_dir)
    projs = FindProjects(root_models_dir, {});
else
    fprintf('There must be a root project directory\n');
    return;
end
fprintf('Building list of project from root project directory %s\n', 'Models');
% 2. Display the list and allow the user to select
[s,v] = listdlg('PromptString','Select a file:', 'SelectionMode','multiple', 'ListString',projs, 'ListSize', [800 300]);
% 3. Combine the projects into the new desired project (we must append the project name to the {image/pointmodel/etc..} filenames
if isempty(s)
    return;
end
indx = 1;
for i=s
    projs{s}
    projectname = projs{i};
    [projectpath, projectname, ext, vers] = fileparts(projectname);
    projectname2=projectname(5:end);
    % Now we need to copy the templates, we also append the project
    % name so we know what template comes from where
    % There are 3 cases
    % i) if the template does not exist in the new directory copy
    % it across
    % ii) if the template does exist then check if it is identical,
    % if so then copy the point models across
    % iii) otherwise, flag an error and do not copy that template
    % or its point models.
    templatefiles = findfilesext('temp_dat', [projectpath, filesep, projectname, filesep, 'Templates']);
    wt = waitbar(0, sprintf('Copying %s\nTemplate Files', projectname(5:end)));
    set(findall(wt,'type','text'),'Interpreter','none')
    project_details = [];
    for f = 1:length(templatefiles)
        waitbar(f/length(templatefiles), wt);
        temps = template_exist('Templates', templatefiles{f});
        if isempty(temps)
            [templatepath, templatename, ext, vers] = fileparts(templatefiles{f});
            [success, mesg, mesgid] = copyfile(templatefiles{f}, [project_directory, filesep, 'Templates', filesep, templatename, ext]);
            edit_set_filename=[templatefiles{f}(1:findstr(templatefiles{f},'temp_dat')-1),'edit_sets'];
            if exist(edit_set_filename)==2
                [success, mesg, mesgid] = copyfile(edit_set_filename, [project_directory, filesep, 'Templates', filesep, templatename, '.edit_sets']);
            end
            % Copy across the point models
            %pmfiles = FindFilenames('_pm.mat', [projectpath, filesep, projectname, filesep, 'PointModels'], [{'PRJ_'}, {'PointModels'}, {templatename}]);
            pmfiles = dir([projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, '*_pm.mat']);
            pmfiles = {pmfiles.name};

            project_details(f).prj_name = projectname2;
            project_details(f).temp_name = templatename;
            project_details(f).pmfiles = pmfiles;
            project_details(f).pca = [];
            project_details(f).mean_image = [];

            for i=1:length(pmfiles); pmfiles{i} = [projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, pmfiles{i}]; end;

            wp = waitbar(0, sprintf('Copying %s\nPoint Model Files for Template %s', projectname(5:end), templatename));
            set(findall(wp,'type','text'),'Interpreter','none')
            for p=1:length(pmfiles)
                waitbar(p/length(pmfiles), wp);
                pmfile = pmfiles{p};
                root_pms = 'PointModels';
                destpmfilename = pmfile(strfind(pmfile, root_pms)+length(root_pms)+1:end);
                [destdir, destfilename, ext, vers] = fileparts(destpmfilename);
                %destdir
                if ~exist([pwd, filesep, 'PointModels', filesep, destdir], 'dir');
                    mkdir([pwd, filesep, 'PointModels', filesep, destdir]);
                end;
                projectname2=projectname(5:end);
                ff=[filesep, destdir, filesep, projectname2,'_', destfilename, ext];
                disp(sprintf('From %s to %s',fullfile(destdir,destfilename),ff));
                [success, mesg, mesgid] = copyfile(pmfile, [project_directory, filesep, 'PointModels', filesep, ff]);
            end
            close(wp);
            if exist([project_directory, filesep, 'Cropped'], 'dir') & exist([projectpath, filesep, projectname, filesep, 'Cropped'], 'dir')
                files = [dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.JPG']), dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.jpg'])];
                files = {files.name};
                w = waitbar(0, sprintf('Copying %s\nCropped Files', projectname(5:end)));
                set(findall(w,'type','text'),'Interpreter','none')
                for f = 1:length(files)
                    waitbar(f/length(files), w);
                    ff=[projectname2, '_', files{f}];
                    disp(sprintf('From %s to %s',files{f},ff))
                    [success, mesg, mesgid] = copyfile([projectpath, filesep, projectname, filesep, 'Cropped', filesep, files{f}], [project_directory, filesep, 'Cropped', filesep, ff]);
                end
                close(w);
            end
        else
            % So if the templates are the same, then copy across
            % the point model files.
            [templatepath, templatename, ext, vers] = fileparts(templatefiles{f});

            if check_template(temps{1}, templatefiles{f})
                % Copy across the point models
                %pmfiles = FindFilenames('_pm.mat', [projectpath, filesep, projectname, filesep, 'PointModels'], [{'PRJ_'}, {'PointModels'}, {templatename}]);
                pmfiles = dir([projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, '*_pm.mat']);
                pmfiles = {pmfiles.name};
                project_details(f).prj_name = projectname2;
                project_details(f).temp_name = templatename;
                project_details(f).pmfiles = pmfiles;
                project_details(f).pca = [];
                project_details(f).mean_image = [];

                for i=1:length(pmfiles); pmfiles{i} = [projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, pmfiles{i}]; end;

                wp = waitbar(0, sprintf('Copying %s\nPoint Model Files for Template %s', projectname(5:end), templatename));
                set(findall(wp,'type','text'),'Interpreter','none')
                for p=1:length(pmfiles)
                    waitbar(p/length(pmfiles), wp);
                    pmfile = pmfiles{p};
                    root_pms = 'PointModels';
                    destpmfilename = pmfile(strfind(pmfile, root_pms)+length(root_pms)+1:end);
                    [destdir, destfilename, ext, vers] = fileparts(destpmfilename);
                    if ~exist([pwd, filesep, 'PointModels', filesep, destdir], 'dir');
                        mkdir([pwd, filesep, 'PointModels', filesep, destdir]);
                    end;
                    ff=[filesep, destdir, filesep, projectname2,'_', destfilename, ext];
                    disp(sprintf('From %s to %s',fullfile(destdir,destfilename),ff));
                    [success, mesg, mesgid] = copyfile(pmfile, [project_directory, filesep, 'PointModels', filesep, ff]);
                    %                     [success, mesg, mesgid] = copyfile(pmfile, [project_directory, filesep, 'PointModels', filesep, destdir, filesep, projectname2,'_', destfilename, ext]);
                end
                close(wp);
                % Copy the cropped dir from the selected projects
                if exist([project_directory, filesep, 'Cropped'], 'dir') & exist([projectpath, filesep, projectname, filesep, 'Cropped'], 'dir')
                    files = [dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.JPG']), dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.jpg'])];
                    files = {files.name};
                    w = waitbar(0, sprintf('Copying %s\nCropped Files', projectname(5:end)));
                    set(findall(w,'type','text'),'Interpreter','none')
                    for f = 1:length(files)
                        waitbar(f/length(files), w);
                        ff=[projectname2, '_', files{f}];
                        disp(sprintf('From %s to %s',files{f},ff))
                        [success, mesg, mesgid] = copyfile([projectpath, filesep, projectname, filesep, 'Cropped', filesep, files{f}], [project_directory, filesep, 'Cropped', filesep, ff]);
                        %                         disp(sprintf('From %s to %s',files{f},[projectname2, '_', files{f}]))
                        %                         [success, mesg, mesgid] = copyfile([projectpath, filesep, projectname, filesep, 'Cropped', filesep, files{f}], [project_directory, filesep, 'Cropped', filesep, projectname2, '_', files{f}]);
                    end
                    close(w);
                end
            else
                warnhandle = warndlg(sprintf('%s\nand\nTemplate: %s\nfrom\nProject: %s\nDo not match!!! Files not being copied', ['Templates', filesep, temps{1}],  [templatename, ext], projectname), 'Invalid Template Matching.');
            end
        end
    end
    close(wt);
    prj_details{indx} = project_details;
    indx = indx+1;
end
save([project_directory, filesep, 'combined_prj_details.mat'], 'prj_details');

return;


function groups = makegroupdata(prj_details)
for i=1:length(prj_details)
    groups(i).name = prj_details{i}.prj_name;
    groups(i).elements = prj_details{i}.pmfiles;
    groups(i).color = [0 0 1];
end
return;


function [handles] = ImportProjects(handles)
if ~checkDir(pwd, handles)
    uiwait(warndlg('Must be in a valid project to import other projects','Import Project Error'));
    return;
end
project_directory = pwd;
% From the root Models directory build a list of all projects and allow the
% user to select from this list.
% 1. Build the list of projects
% matlab_files_path = which ('AAMToolbox');
% matlab_files_path = fileparts(fileparts(fileparts(matlab_files_path)));
% files = dir(matlab_files_path);
% files = {files.name};
% found = 0;
% for f = 1:length(files)
%     if strcmp(files{f}, 'Models')
%         found = 1;
%     end
% end
%
%
% if found == 0
%     root_models_dir = uigetdir(pwd, 'Please choose the root projects directory, i.e. ''../Shape_Models/Models''');
% else
%     root_models_dir = [matlab_files_path, filesep, 'Models'];
% end



root_models_dir = uigetdir(pwd, 'Please choose the root projects directory, i.e. ''../Shape_Models/Models''');
if root_models_dir == 0
    fprintf('User pressed cancel\n');
    return;
end
if ~isempty(root_models_dir)
    projs = FindProjects(root_models_dir, {});
else
    fprintf('There must be a root project directory\n');
    return;
end
fprintf('Building list of project from root project directory %s\n', 'Models');
% 2. Display the list and allow the user to select
[s,v] = listdlg('PromptString','Select a file:', 'SelectionMode','multiple', 'ListString',projs, 'ListSize', [800 300]);
% 3. Combine the projects into the new desired project (we must append the project name to the {image/pointmodel/etc..} filenames
if isempty(s)
    return;
end
indx = 1;
for i=s
    projs{s}
    projectname = projs{i};
    [projectpath, projectname, ext, vers] = fileparts(projectname);
    projectname2=projectname(5:end);

    % Now we need to copy the templates, we also append the project
    % name so we know what template comes from where

    % There are 3 cases
    % i) if the template does not exist in the new directory copy
    % it across
    % ii) if the template does exist then check if it is identical,
    % if so then copy the point models across
    % iii) otherwise, flag an error and do not copy that template
    % or its point models.
    templatefiles = findfilesext('temp_dat', [projectpath, filesep, projectname, filesep, 'Templates']);
    wt = waitbar(0, sprintf('Copying %s\nTemplate Files', projectname(5:end)));
    set(findall(wt,'type','text'),'Interpreter','none')
    project_details = [];
    for f = 1:length(templatefiles)
        waitbar(f/length(templatefiles), wt);
        temps = template_exist('Templates', templatefiles{f});
        if isempty(temps)
            [templatepath, templatename, ext, vers] = fileparts(templatefiles{f});
            [success, mesg, mesgid] = copyfile(templatefiles{f}, [project_directory, filesep, 'Templates', filesep, templatename, ext]);
            % Copy across the point models
            wp = waitbar(0, sprintf('Copying %s\nPoint Model Files for Template %s', projectname(5:end), templatename));
            set(findall(wp,'type','text'),'Interpreter','none')

            %       pmfiles = FindFilenames('_pm.mat', [projectpath, filesep, projectname, filesep, 'PointModels'], [{'PRJ_'}, {'PointModels'}, {templatename}]);



            pmfiles = dir([projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, '*_pm.mat']);
            pmfiles = {pmfiles.name};
            project_details(f).prj_name = projectname2;
            project_details(f).temp_name = templatename;
            project_details(f).pmfiles = pmfiles;
            project_details(f).pca = [];
            project_details(f).mean_image = [];

            for i=1:length(pmfiles); pmfiles{i} = [projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, pmfiles{i}]; end;




            for p=1:length(pmfiles)
                waitbar(p/length(pmfiles), wp);
                pmfile = pmfiles{p};
                root_pms = 'PointModels';
                destpmfilename = pmfile(strfind(pmfile, root_pms)+length(root_pms)+1:end);
                [destdir, destfilename, ext, vers] = fileparts(destpmfilename);
                if ~exist([pwd, filesep, 'PointModels', filesep, destdir], 'dir'); mkdir(['PointModels', filesep, destdir]); end;
                [success, mesg, mesgid] = copyfile(pmfile, [project_directory, filesep, 'PointModels', filesep, destdir, filesep, projectname2,'_', destfilename, ext]);
            end
            close(wp);
            if exist([project_directory, filesep, 'Cropped'], 'dir') & exist([projectpath, filesep, projectname, filesep, 'Cropped'], 'dir')
                files = [dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.JPG']), dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.jpg'])];
                files = {files.name};
                w = waitbar(0, sprintf('Copying %s\nCropped Files', projectname(5:end)));
                set(findall(w,'type','text'),'Interpreter','none')
                for f = 1:length(files)
                    waitbar(f/length(files), w);
                    [success, mesg, mesgid] = copyfile([projectpath, filesep, projectname, filesep, 'Cropped', filesep, files{f}], [project_directory, filesep, 'Cropped', filesep, projectname2, '_', files{f}]);
                end
                close(w);
            end
        else
            % So if the templates are the same, then copy across
            % the point model files.
            [templatepath, templatename, ext, vers] = fileparts(templatefiles{f});




            if check_template(temps{1}, templatefiles{f})
                % Copy across the point models
                %pmfiles = FindFilenames('_pm.mat', [projectpath, filesep, projectname, filesep, 'PointModels'], [{'PRJ_'}, {'PointModels'}, {templatename}]);

                wp = waitbar(0, sprintf('Copying %s\nPoint Model Files for Template %s', projectname(5:end), templatename));
                set(findall(wp,'type','text'),'Interpreter','none')


                pmfiles = dir([projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, '*_pm.mat']);
                pmfiles = {pmfiles.name};
                project_details(f).prj_name = projectname2;
                project_details(f).temp_name = templatename;
                project_details(f).pmfiles = pmfiles;
                project_details(f).pca = [];
                project_details(f).mean_image = [];

                for i=1:length(pmfiles); pmfiles{i} = [projectpath, filesep, projectname, filesep, 'PointModels', filesep, templatename, filesep, pmfiles{i}]; end;





                for p=1:length(pmfiles)
                    waitbar(p/length(pmfiles), wp);
                    pmfile = pmfiles{p};
                    root_pms = 'PointModels';
                    destpmfilename = pmfile(strfind(pmfile, root_pms)+length(root_pms)+1:end);
                    [destdir, destfilename, ext, vers] = fileparts(destpmfilename);
                    if ~exist([pwd, filesep, 'PointModels', filesep, destdir], 'dir'); mkdir(['PointModels', filesep, destdir]); end;

                    [success, mesg, mesgid] = copyfile(pmfile, [project_directory, filesep, 'PointModels', filesep, destdir, filesep, projectname2,'_', destfilename, ext]);
                end
                close(wp);
                % Copy the cropped dir from the selected projects
                if exist([project_directory, filesep, 'Cropped'], 'dir') & exist([projectpath, filesep, projectname, filesep, 'Cropped'], 'dir')
                    files = [dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.JPG']), dir([projectpath, filesep, projectname, filesep, 'Cropped', filesep, '*.jpg'])];
                    files = {files.name};
                    w = waitbar(0, sprintf('Copying %s\nCropped Files', projectname(5:end)));
                    set(findall(w,'type','text'),'Interpreter','none')
                    for f = 1:length(files)
                        waitbar(f/length(files), w);
                        [success, mesg, mesgid] = copyfile([projectpath, filesep, projectname, filesep, 'Cropped', filesep, files{f}], [project_directory, filesep, 'Cropped', filesep, projectname2,'_', files{f}]);
                    end
                    close(w);
                end
            else
                warnhandle = warndlg(sprintf('%s\nand\nTemplate: %s\nfrom\nProject: %s\nDo not match!!! Files not being copied', ['Templates', filesep, temps{1}],  [templatename, ext], projectname), 'Invalid Template Matching.');
            end
        end
    end
    prj_details{indx} = project_details;
    indx = indx+1;
end
close(wt);
if exist('combined_prj_details.mat');
    combined_prj_details = load('combined_prj_details.mat');
    prj_details = [combined_prj_details.prj_details, prj_details];
end
save([project_directory, filesep, 'combined_prj_details.mat'], 'prj_details');
return;
%%%%%%%%%%%%%%%%%%%%
%
% check template
%
%%%%%%%%%%%%%%%%%%%%
function [res] = check_template(template1, template2)
pmt1 = load(['Templates', filesep, template1], '-mat');
pmt2 = load(template2, '-mat');
pmt1 = pmt1.PMTemplate;
pmt2 = pmt2.PMTemplate;
res = 0;
pts1 = get(pmt1, 'pts');
pts2 = get(pmt2, 'pts');
if size(pts1,2) ~= size(pts2,2)
    return;
else
    d = pts1 - pts2;
    if sum(d(:))==0
        res = 1;
    else
        res = 0;
    end
end
return;
%%%%%%%%%%%%%%%%%%%%
%
% template exist
%
%%%%%%%%%%%%%%%%%%%%
function [temps] = template_exist(d, templatefile)
[path, templatefile, ext, vers] = fileparts(templatefile);
templatefile = [templatefile, ext];
files = dir([d, filesep, '*.temp_dat']);
files = {files.name};
temps = {};
for f = 1:length(files)
    if strcmp(templatefile, files{f})
        temps{end+1} = files{f};
    end
end




function toggleButtons(handles, str)
set([handles.newSetBtn,handles.autoPlaceBtn, handles.pmEditorBtn, handles.modelGeneratorBtn, handles.pdmWalkBtn, handles.view_shape_space_btn], 'Enable', str);


%%%%%%%%%%%%%%%%%%%%
%
% Initialize the GUI
%
%%%%%%%%%%%%%%%%%%%%
function  handles=Update_AAMToolbox_GUI(handles)
toggleButtons(handles, 'off');
% now get the model names from the strings
set(handles.ProjectDetails,'title', sprintf('Project Details  (AAMToolbox Version %3.3f) [Today: %s]',handles.VersionNumber,datestr(now)));
Models=get(handles.currentModelTxt, 'String');
ind=get(handles.currentModelTxt, 'Value');
if ~isempty(Models)
    if iscell(Models)
        Modelname1=Models{ind};
        % strip out trailing blanks
        Modelname1=strip_out_trailing_blanks(Modelname1);
        %reconstruct correct models name
        Modelname2=fullfile('StatisticalModels',Modelname1);
        Modelname3=Modelname2(1:findstr(Modelname2,'[')-1);
        Modelname=fullfile(Modelname3,'model.aam_dat');

        if findstr(Modelname,'.aam_dat')
            ammModelname=Modelname; %(1:findstr(Modelname,'.aam_dat')+length('.aam_dat'));
            %ammModelname=Modelname(1:findstr(Modelname,'.aam_dat')+length('.aam_dat'));
            handles.dat.models = ammModelname;
            if exist(ammModelname)==2
                aam = load(ammModelname, '-mat');
                handles.AAM = aam.aam;
                handles.AAM = UpdateAAMFromDisk(handles.AAM);
                if isempty(get(handles.AAM,'modelDirec')) %'pdmDirec'))
                    handles = FreshAAM(handles);
                end
            else
                handles.AAM = AAM;
            end
        end
        % setup the delete menu item
        templatename=Modelname1(1:findstr(Modelname1,filesep)-1);
        set(handles.DelSMs,'label',sprintf('Delete all ''%s'' Statistical Models',templatename));
        handles.dat.templatename=templatename;
        % and extract the template name
        template=Modelname(findstr(Modelname,'StatisticalModels')+length('StatisticalModels')+1:end);
        if findstr(template,[filesep, 'Set_'])
            template=template(1:findstr(template,[filesep, 'Set_'])-1);
            templatename=[template,'.temp_dat'];
            % now check consistency between AAM and model strings
            if ~isempty(get(handles.AAM,'modelDirec'))
                pmt=get(handles.AAM, 'PointModelTemplate');
                templatenameAAM=get(pmt,'name');
                Facets=AreThereFacets(get(pmt,'direc'),templatenameAAM);
                if ~isempty(Facets)
                    handles.Facets=Facets;
                end
                if ~strcmpi(templatename,templatenameAAM)
                    msgbox('Disc files and AAM structure differ');
                end
                reload_image_model_icons(handles.AAMToolboxAxis,handles.AAMToolbox_plot,pmt);
                set([handles.newSetBtn,handles.imageProcBtn, handles.autoPlaceBtn, ...
                    handles.newModelBtn,handles.pmEditorBtn], 'Enable', 'on');
                if exist(fullfile('Templates',templatename))==2
                    set(handles.templateModelTxt, 'String', ...
                        sprintf('%s     with %d points',templatename,size(get(pmt,'pts'),2)));
                end
            else
                cla(handles.AAMToolboxAxis);
                cla(handles.AAMToolbox_plot);
                set(handles.templateModelTxt, 'String', '');
            end
        else
            set(handles.templateModelTxt, 'String', '');
        end
        % identify the set using the model name
        setname1=Modelname(findstr(Modelname,'Set_'):end);
        if findstr(setname1,filesep)
            setname=setname1(1:findstr(setname1,filesep)-1);
        else
            setname=setname1;
        end
        setfilename=Modelname(1:findstr(Modelname,setname)-1+length(setname));
        if exist(setfilename)
            setnamestr=setname;
            d=dir(fullfile(setfilename,'LN_*'));
            if ~isempty(d)
                setnamestr=[d.name];
                set(handles.SetList,'String',[setname,' (',setnamestr(4:end-4), ')']);
                set([handles.newModelBtn], 'Enable', 'on');
                % identify the imagelist using the model name
                imagelistname=Modelname(findstr(Modelname,'ImageList_'):end);
                imagelistname=imagelistname(1:findstr(imagelistname,filesep)-1);
                detailstr = '';
                if findstr(Modelname,[filesep, 'ImageList_'])
                    imagelistdir=Modelname(1:findstr(Modelname,'model.aam_dat')-2);
                    if exist(imagelistdir)
                        d = dir(fullfile(setfilename, filesep, imagelistname, 'LN_*'));
                        if ~isempty(d)
                            listname = [d.name];
                            set(handles.ImageList,'String',[imagelistname, ' (', listname(4:end-4), ')']);
                            if exist(fullfile(Modelname3,'details.mat'))==2
                                temp2=load(fullfile(Modelname3,'details.mat'),'-mat');
                                details=temp2.details;
                                detailstr=sprintf('Current Image List (%d pixels, normalised: ',details.pixelnumber);
                                if details.scaling==1
                                    detailstr=sprintf('%s Scaling',detailstr);
                                end
                                if details.rotation==1
                                    detailstr=sprintf('%s Rotation',detailstr);
                                end
                                if details.translation==1
                                    detailstr=sprintf('%s Translation',detailstr);
                                end
                                detailstr=sprintf('%s)',detailstr);
                                set(handles.CurrentImageList,'Title',detailstr);
                            else
                                details=[];
                                set(handles.CurrentImageList,'Title','Current Image List');
                            end
                        else
                            set(handles.ImageList,'String',[imagelistname]);

                            set(handles.CurrentImageList,'Title',detailstr);
                        end
                        set([handles.newSetBtn,handles.imageProcBtn, handles.autoPlaceBtn, handles.newModelBtn,handles.pmEditorBtn,...
                            handles.modelGeneratorBtn, handles.pdmWalkBtn, handles.view_shape_space_btn], 'Enable', 'on');
                    else
                        set(handles.ImageList,'String','Use: Template Editor then New Model then');
                    end
                else
                    set(handles.ImageList,'String','Use: Template Editor, New Model then');
                end
            else
                set(handles.ImageList,'String','Use: Template Editor, New Model then');
            end
        else
            set(handles.currentModelTxt,'String','''Choose Template'' to start creating a fresh statistical models.');
            set(handles.ImageList,'String','');
            set(handles.SetList,'String','');
        end
    else
        reload_image_model_icons(handles.AAMToolboxAxis,handles.AAMToolbox_plot,[]);
        Modelname=Models;
        set(handles.currentModelTxt, 'String', 'No models in this directory');
        set(handles.SetList, 'String', 'No set selected');
        set(handles.ImageList, 'String', 'No set selected');

        set(handles.templateModelTxt, 'String', 'No template model');
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Part of the initialisation process
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Facets=AreThereFacets(pathname,templatenameAAM)
    filename=[templatenameAAM(1:end-9),'.xls'];
    filename1=fullfile(pathname,filename);
    if exist(filename1)==2
        sheet='Sheet1';
        [num, txt]=xlsread(filename1,sheet);
        type=txt{1,1};
        labels=txt(3:end,:);
        Facets.facs=num(3:end,1:end)+1;
        Facets.name=filename1;
        Facets.labels=labels;
        Facets.type=type;
    else
        Facets=[];
        disp(sprintf('There is no 3D facet date, i.e. file %s',filename1));
    end
    return
    
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitGUI
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = InitGUI(handles)
handles.AAM = AAM;
if checkDir(pwd, handles)
    [handles, models, incompleteModels]=UpdateGUImodel_list_from_disc(handles);
    if length([models,incompleteModels])>0
        set(handles.currentModelTxt, 'Value',1)
    else
        set(handles.currentModelTxt, 'String', 'No models in this directory');
        set(handles.SetList, 'String', 'No set selected');
        set(handles.ImageList, 'String', 'No set selected');

        set(handles.templateModelTxt, 'String', 'No template model');
        handles.dat.models = [];
        set([handles.newSetBtn,handles.imageProcBtn, handles.autoPlaceBtn, handles.pmEditorBtn, ...
            handles.modelGeneratorBtn, handles.pdmWalkBtn, handles.view_shape_space_btn], 'Enable', 'off');
    end
    handles=Update_AAMToolbox_GUI(handles);
    set([handles.imageProcBtn, handles.autoPlaceBtn, handles.showDetailsBtn, handles.newSetBtn, ...
        handles.templateEditorBtn, handles.newModelBtn, handles.currentModelTxt, handles.pmEditorBtn, ...
        handles.modelGeneratorBtn, handles.pdmWalkBtn, handles.view_shape_space_btn,...
        handles.ViewGrowth], 'Enable', 'on');

else
    set(handles.cwdTxt, 'String', 'No Project Selected');
    set(handles.currentModelTxt, 'String', 'No models in this directory');
    set(handles.SetList, 'String', 'No set selected');
    set(handles.ImageList, 'String', 'No set selected');
    set(handles.templateModelTxt, 'String', 'No Template Model');
    set([handles.imageProcBtn, handles.autoPlaceBtn, handles.showDetailsBtn, handles.newSetBtn,...
        handles.templateEditorBtn, handles.newModelBtn, handles.currentModelTxt, handles.pmEditorBtn,...
        handles.modelGeneratorBtn, handles.pdmWalkBtn, handles.view_shape_space_btn,...
        handles.ViewGrowth],'Enable', 'off');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Setup Point Model Directories
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = SetupPointModelDirectories(handles)
pmt = get(handles.AAM, 'PointModelTemplate');
pts = get(pmt, 'pts');
pts = pts(:);
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);
if ~exist([pwd, filesep, 'PointModels', filesep, templatename], 'dir')
    mkdir([pwd, filesep, 'PointModels', filesep, templatename]);
    if exist([pwd, filesep, 'Cropped'], 'dir')

        % Begin change by js, 070312
        % Begin original code

        %         files = dir('Cropped/*.jpg');
        %         handles.AAM = set(handles.AAM, 'imageFilenames', {files.name});

        % End original code
        % Begin replacement code
        projectDirectory = pwd;

        if ~isProject3D(projectDirectory)

            files = dir(fullfile(projectDirectory, filesep, 'Cropped/*.jpg'));
            handles.AAM = set(handles.AAM, 'imageFilenames', {files.name});
        else
            files = dir(fullfile(projectDirectory, filesep, 'Cropped'));

            % Each volume is assumed to reside in its own directory, hence
            % remove all the non-directory files from the list
            volumeDirs = [];

            for i = 1:length(files)
                if ~isequal(files(i).name, '.') && ...
                        ~isequal(files(i).name, '..') && ...
                        isdir(fullfile('Cropped', filesep, files(i).name))

                    volumeDirs = [volumeDirs, files(i)];
                end
            end

            files = volumeDirs;
            handles.AAM = set(handles.AAM, 'imageFilenames', {files.name});
        end

        % End replacement code
        % End change by js, 070312
        handles.AAM = set(handles.AAM, 'imageDirectory', 'Cropped');
    else
        error('Could not find directory ''Cropped'' to build initial point model files');
    end
else
    uiwait(warndlg('The point model directory for this template exists, using this by default.','Point Model Exists'));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Setup Statistical Model Directories
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = SetupStatModelDirectories(handles)
pmt = get(handles.AAM, 'PointModelTemplate');
pts = get(pmt, 'pts');
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);
if ~exist([pwd, filesep, 'StatisticalModels', filesep, templatename], 'dir')
    mkdir([pwd, filesep, 'StatisticalModels', filesep, templatename]);
    mkdir([pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_1']);
    a  = [1];
    save([pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_1', filesep, 'LN_Original'],'a');
    mkdir([pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_1', filesep, 'ImageList_1']);
    save([pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_1', filesep, 'ImageList_1', filesep, 'LN_Original'],'a');
    indices = 1:size(pts,2);
    save([pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_1', filesep, 'indices'], 'indices');
    handles.dat.currentIndices = indices;
    handles.AAM = set(handles.AAM, 'pointindices', indices);
    if exist([pwd, filesep, 'Cropped'], 'dir')

        % Begin change by js, 070312
        % Begin original code

        %         files = dir([pwd, filesep, 'Cropped', filesep, '*.jpg']);

        % End original code
        % Begin replacement code
        projectDirectory = pwd;

        if ~isProject3D(projectDirectory)

            files = dir(fullfile(projectDirectory, filesep, 'Cropped/*.jpg'));
        else
            files = dir(fullfile(projectDirectory, filesep, 'Cropped'));

            % Each volume is assumed to reside in its own directory, hence
            % remove all the non-directory files from the list
            volumeDirs = [];

            for i = 1:length(files)
                if ~isequal(files(i).name, '.') && ...
                        ~isequal(files(i).name, '..') && ...
                        isdir(fullfile('Cropped', filesep, files(i).name))

                    volumeDirs = [volumeDirs, files(i)];
                end
            end

            files = volumeDirs;
        end

        % End replacement code
        % End change by js, 070312
        handles.AAM = set(handles.AAM, 'am_imagenames', {files.name});
        imageindex = 1:length(files);
        save([pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_1', filesep, 'ImageList_1', filesep, 'imageindex'], 'imageindex');
        handles.AAM = set(handles.AAM, 'imageFilenames', {files.name});
        handles.AAM = set(handles.AAM, 'imageDirectory', 'Cropped');
        w = waitbar(0, 'Setting up files for the new statistical model');
        set(findall(w,'type','text'),'Interpreter','none')
        for f = 1:length(files)
            [path, name, ext, v] = fileparts(files(f).name);
            temp = AAM_Element;
            % Comment out, we don't want to store the image in the
            % template, might put in  a 300x300 thumbnail.
            %thumbnail = imresize(imread(['Cropped', filesep, files(f).name]), [100 100]);
            %            temp = set(temp, 'image', thumbnail);
            temp = set(temp, 'imagefilename', files(f).name);
            temp = set(temp, 'pts', pts);
            temp = set(temp, 'primaries', get(pmt, 'primaries'));
            temp = set(temp, 'closedloops', get(pmt, 'closedloops'));
            temp = set(temp, 'loops', get(pmt, 'loops'));
            handles.AAM = add_element(handles.AAM, temp);
            %imwrite(thumbnail, [pwd, filesep, 'StatisticalModels', filesep, templatename, filesep, 'Set_1', filesep, 'ImageList_1', filesep, files(f).name], 'JPEG');
            waitbar(f/length(files), w);
        end
        close(w);
    else
        error('Could not find directory ''Cropped'' to build initial point model files');
    end
else
    uiwait(warndlg('The statistical model directory for this template exists, using this by default.','Statistical Model Exists'));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Create New Model
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = CreateNewModel(handles,pmt)
if nargin<2
    [filename, pathname] = uigetfile('*.temp_dat', 'Choose a point model template file', ['Templates', filesep]);
else
    return;
    filename='dummy';
    pathname='dummy';
end
templatename = filename(1:length(filename)-9);
if exist([pwd, filesep, 'StatisticalModels', filesep, templatename])
    return;
end
handles.AAM = AAM;
if isequal(filename,0) | isequal(pathname,0)
    disp('User pressed cancel')
    return;
else
    if nargin<2
        pmt = load([pathname, filesep, filename], '-mat');
        pmt = pmt.PMTemplate;
    end
    handles.AAM = set(handles.AAM, 'PointModelTemplate', pmt);
    if nargin<2
        handles = SetupPointModelDirectories(handles);
    end
    handles = SetupStatModelDirectories(handles);
    handles.AAM = set(handles.AAM, 'modelDirec', ['StatisticalModels', filesep, templatename,  filesep, 'Set_1', filesep, 'ImageList_1']);
    handles.AAM = set(handles.AAM, 'modelName', 'model.aam_dat');
    handles.AAM = set(handles.AAM, 'pointset', 1);
    handles.AAM = set(handles.AAM, 'imageset', 1);
    aam = handles.AAM;
    save([pwd, filesep, get(handles.AAM, 'modelDirec'), filesep, get(handles.AAM, 'modelName')], 'aam');
    set(handles.templateModelTxt, 'String', get(get(handles.AAM, 'PointModelTemplate'), 'name'));
    set(handles.SetList, 'String', 'Set_1 (Original)');
    models = findfilesext('aam_dat',pwd);
    for m =1:length(models)
        model = models{m};
        models{m} = model(length(pwd)+2:end);
    end
    handles.dat.models = models;
    [modelNames, dates] = getModelNames(models);
    set(handles.currentModelTxt, 'String', constructDateString(modelNames, dates));
    set(handles.currentModelTxt, 'value', 1);

    if exist('combined_prj_details.mat')
        indx = 1;
        groups = [];
        prj_details = load('combined_prj_details.mat');
        prj_details = prj_details.prj_details;
        for i=1:length(prj_details)
            project = prj_details{i};
            for ii=1:length(project)
                if strcmp(project(ii).temp_name, templatename)
                    groups(indx).name = project(ii).prj_name;
                    elements =  project(ii).pmfiles;
                    for iii=1:length(elements)
                        elements{iii} = [project(ii).prj_name, '_', elements{iii}];
                    end
                    groups(indx).elements = elements;
                    groups(indx).color = [0 0 1];
                    indx = indx + 1;
                end
            end
        end
        if ~isempty(groups)
            DESTINATION = [get(handles.AAM, 'modelDirec'), filesep, 'groups.mat'];
            save(DESTINATION, 'groups');
        end
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Change Project
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = ChangeProject(handles, directoryname)
if nargin<2
    directoryname = uigetdir(pwd, 'Select Project Directory');
end
if directoryname==0
    disp('User pressed Cancel');
else
    [pathname, rootDir] = fileparts(directoryname);
    username = getenv('USERNAME');
    cd(directoryname);
    if ~checkDir(directoryname, handles)
        set(handles.cwdTxt, 'String', 'No Project Selected');
        set(handles.currentModelTxt, 'String', 'No models in this directory');
        set(handles.SetList, 'String', 'No set selected');
        set(handles.ImageList, 'String', 'No set selected');
        set(handles.templateModelTxt, 'String', 'No Template Model');
        set([handles.showDetailsBtn, handles.newSetBtn, handles.templateEditorBtn, ...
            handles.newModelBtn, handles.currentModelTxt, handles.pmEditorBtn, ...
            handles.modelGeneratorBtn, handles.pdmWalkBtn, handles.view_shape_space_btn], 'Enable', 'off');
    else
        handles = InitGUI(handles);
    end
end
handles=Update_AAMToolbox_GUI(handles);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Construct a string with a date
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [datestring] = constructDateString(models, dates)
if iscell(models)
    k=0;
    for i=1:length(models)
        name1=models{i};
        name2=name1(findstr(name1,'StatisticalModels')+length('StatisticalModels')+1:end);
        name2b=name2(1:findstr(name2,'model.aam_dat')-2);
        name3= name1(1:findstr(name1,'ImageList')-2);
        d=dir(fullfile(name3,'LN_*'));
        temp=load(fullfile(name3,d(1).name),'-mat');
        if isfield(temp,'setnames')
            setnames=temp.setnames;
            if iscell(setnames{1})
                setname=cell2mat(setnames{1});
            else
                setname=setnames{1};
            end
        elseif isfield(temp,'setname')
            setnames=temp.setname;
            if iscell(setnames{1})
                setname=cell2mat(setnames{1});
            else
                setname=setnames{1};
            end
        else
            setname='Original';
        end
        d2=dir(fullfile(name3,'ImageList_*'));
        [mpath, mname, ext, vers] = fileparts(models{i});
        d3=dir([mpath, filesep, 'LN_*']);
        if ~isempty(d3)
            n=d3(1).name;
            Imagelistname=n(4:findstr(n,'.mat')-1);
            k=k+1;
            datestring{k} = sprintf('%-35s [%-48s] {%-36s} (%21s)',name2b, setname,Imagelistname,dates{i});
        else
            Imagelistname='No-name';
            k=k+1;
            datestring{k} = sprintf('%-35s [%-48s] {%-36s} (%21s)',name2b, setname,Imagelistname,dates{i});
        end
    end
else
    datestring = {'No models [set]{imagelist}(date)'};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Select Model
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = SelectModel(handles)
model = get(handles.currentModelTxt, 'String');
if isa(model, 'cell')
    models=get(handles.currentModelTxt, 'String');
    ind=get(handles.currentModelTxt, 'value');
    model = models{ind};
    %reconstruct correct models name
    Modelname2=fullfile('StatisticalModels',model);
    Modelname3=Modelname2(1:findstr(Modelname2,'[')-2);
    Modelname=fullfile(Modelname3,'model.aam_dat');
    %model=Modelname;
    %model = model(1:findstr(model,'.aam_dat')+length('.aam_dat'));
    if exist(Modelname)==2 % is an accessible file ~isempty(findfiles('aam_dat',model))
        aam = load(Modelname, '-mat');
        handles.AAM = aam.aam;
    else
        handles.AAM = AAM;
        set(handles.templateModelTxt, 'String', 'No template model');
    end
else
    handles.AAM = AAM;
    set(handles.templateModelTxt, 'String', 'No template model');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Select Set
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = SelectSet(handles)
% lets see what sets are in the StatisticalModels directory
handles = FindSets(handles);
sets1=handles.dat.sets;
ind=get(handles.SetList,'value');
sets = get(handles.SetList, 'String');
pmtname = get(get(handles.AAM, 'PointModelTemplate'), 'name');
[path, pmtname, ext, vers] = fileparts(pmtname);
if isa(sets, 'cell')
    sets = handles.dat.sets{get(handles.SetList, 'value')};
    indices = load( ['StatisticalModels', filesep, pmtname, filesep, sets, filesep, 'indices']);
    handles.dat.currentIndices = indices.indices;
else
    handles.dat.currentIndices = [];
end
handles = UpdateGUI(handles);
%%%%%%%%%%%%%%%%%%%%
%
% Builds the set string
%
%%%%%%%%%%%%%%%%%%%%
function [setString] = BuildSetString(handles, sets)
pmt = get(handles.AAM, 'PointModelTemplate');
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);
sets = handles.dat.sets;
logicalname = '';
if get(handles.AAM, 'pointset')==0
    setString = 'No set selected';
    return;
end
sets = sets{get(handles.AAM, 'pointset')};
files = dir(['StatisticalModels', filesep, templatename, filesep, sets, filesep, 'LN_*']);
if length(files)>0
    logicalname = files(1).name;
    logicalname = logicalname(4:end-4);
    setString = [sets, ' (', logicalname,')'];
else
    setString= [sets];
end
%%%%%%%%%%%%%%%%%%%%
%
% Find Existing Sets
%
%%%%%%%%%%%%%%%%%%%%
function [handles] = FindSets(handles)
pmt = get(handles.AAM, 'PointModelTemplate');
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);
sets = {};
if exist(['StatisticalModels', filesep, templatename], 'dir')
    files = dir(['StatisticalModels', filesep, templatename, filesep, 'Set_*']);
    sets = {files.name};
else
    warndlg('There is not a directory in statistical models for this template!!\n');
end
handles.dat.sets = sets;
%%%%%%%%%%%%%%%%%%%%
%
% Get models
%
%%%%%%%%%%%%%%%%%%%%
function models = getModels(d)
models = findfiles('model.aam_dat',d);
for m =1:length(models)
    model = models{m};
    models{m} = model(length(pwd)+2:end);
end
%%%%%%%%%%%%%%%%%%%%
%
% getUncomputedModels
%
%%%%%%%%%%%%%%%%%%%%
function sets=getUncomputedModels(d)
d=dir('StatisticalModels');
n=1;
sets=[];
for i=3:size(d,1)
    dd=dir(['StatisticalModels', filesep, d(i).name]);
    for j=3:size(dd,1)
        setfilename=['StatisticalModels', filesep, d(i).name, filesep ,dd(j).name];
        models=findfilesext('aam_dat',['StatisticalModels', filesep, d(i).name,filesep ,dd(j).name]);
        if isempty(models)
            sets{n}=setfilename;
            n=n+1;
        end
    end
end
%%%%%%%%%%%%%%%%%%%%
%
% UpdateGUI
%
%%%%%%%%%%%%%%%%%%%%
function [handles, models, incompleteModels]= UpdateGUImodel_list_from_disc(handles)
models = getModels(pwd);
incompleteModels=getUncomputedModels(pwd);
if length(models)>0 | length(incompleteModels)>0
    % This method sorts the names of the models according to the most
    % recent being changed.
    [modelNames, dates] = getModelNames(models);
    string=constructDateString(modelNames, dates);
    string=[string,incompleteModels];
    set(handles.currentModelTxt, 'String', string);
end
%%%%%%%%%%%%%%%%%%%%%%
%
% getModelNames
%
%%%%%%%%%%%%%%%%%%%%%%
function [modelsStr, dates] = getModelNames(names)
if length(names)==0
    modelsStr = 'No models in this directory';
    dates{1} = '';
    return;
end
for n = 1:length(names)
    modelsStr(n) = dir(names{n});
end
filenames = {modelsStr.name};
dates = {modelsStr.date};
dates = datevec(dates);
dates = datenum(dates);
[dates, ind] = sort(dates, 'descend');
dates = {modelsStr.date};
dates = dates(ind);
names = names(ind);
modelsStr = {};
for i=1:length(names)
    modelsStr{i} = cut_string([names{i}]);
end
