function DataMain=SetPicker(arg)
    % function DataMain=SetPicker(arg)
    %
    % This program is a bit of a shambles - it has never been used in anger and so never got refined
    %
    % It is designed to do two things
    % 1) to allow the user to select subsets of the points in the pointmodel template and give them logical names
    %    this data is stored in the template directory with the suffix .edit_sets and prefix of the template name.
    %    Within the SetPicker GUI, these names and associated lists of indices appear in a drop down list.
    %    This data also appears to be stored in the AAMToolbox data structure: DataMain.handles.dat in the fields
    %    and the SetPicker data structure Data
    %    Data.handles.dat.pointSetNumber=pointSetNumber; % index to the current AAM subdirectory (see 2 below)
    %    Data.handles.dat.AllPointSets=EditSetNames; % names of all the subsets
    %    Data.handles.dat.EditIndices=EditIndices;   % associated indexes
    %    Data.handles.dat.EditSetNum=EditSetNum; % index to the subset currently selected in the SetPicker dropdown
    %    Data.handles.dat.edit_sets_filename=edit_sets_filename; % fullname of edit_sets file
    %
    % 2) to allow the user to select a named subset from the dropdown list and create a new AAM model directory in the
    %    hierachy: StatisticalModels:Templatename:Set_* which will contains
    %    indices.mat: the subset index list
    %    LN_name.mat: the logical name
    %    The statistical modelling tool will then create subdirectories for each image list and associated model
    %    Imagelist_*: which contains a list of images and the associated statistical models
    %
    % SaveToDropdownList
    %
    global AAMShapemodel_figure_handle
    global AAMModelGenerator_handle
    global AAMModelBuilder_handle
    global AAMSetPicker_handle
    global UpdateModel_handle
    
    % Need to be able to select set(s) from the current and other directories
    
    if strcmp(arg, 'init')
        % Open the GUI for display
        fig = openfig(mfilename, 'reuse');
        movegui(fig, 'center');
        
        %set(fig, 'WindowStyle', 'modal', 'Resize', 'on');
        % collect data about the current project direct from the AAMToolbox
        DataMain = guidata(findobj('Tag', 'AAMToolbox'));
        % Generate a structure of handles to pass to callbacks, and store
        Data.handles = guihandles(fig);
        set(fig, 'Color', get(Data.handles.uipanel9, 'BackgroundColor'));
        set(fig, 'Visible', 'on');
        Data.handles.dat=DataMain.handles.dat;
        Data.handles.AAM=DataMain.handles.AAM;
        Data.handles.figMain = fig;
        AAMSetPicker_handle=fig;
        Data.handles.dat.plotH = [];
        Data.handles.dat.currentLoopNumber = 0;
        aam=DataMain.handles.AAM;
        indices=get(aam,'pointindices');
        Data.handles.dat.indices=indices;
        Data.handles.dat.temp_indices=indices;
        Data.handles.dat.indices=Data.handles.dat.indices;
        
        modelDirec=get(DataMain.handles.AAM,'modelDirec');
        [pathstrA, nameA, extA] = fileparts(modelDirec);
        [pathstrB, CurrentSetName, extB, versnB] = fileparts(pathstrA);
        %     h = FindSets(DataMain.handles);
        pointSetNumber=get(DataMain.handles.AAM,'pointset');
        
        if isfield(Data.handles.dat,'setNum')
            Data.handles.dat=rmfield(Data.handles.dat,'setNum');
        end
        if isfield(Data.handles.dat,'EditSetNum')
            EditSetNum=Data.handles.dat.EditSetNum;
        else
            EditSetNum=1;
        end
        PMT=get(DataMain.handles.AAM,'PointModelTemplate');
        templatename=get(PMT,'name');
        edit_sets_filename=fullfile(get(PMT,'direc'),[templatename(1:end-9),'.edit_sets']);
        temp=load(edit_sets_filename,'-mat');
        %edit_sets=load(fullfile('Templates','Faces11.edit_sets'),'-mat');
        edit_sets=temp.edit_sets;
        haveModelFlag=[];
        for i=1:length(edit_sets)
            EditSetNames{i}=edit_sets{i}.label;
            EditIndices{i}=edit_sets{i}.indexes;
            haveModelFlag(i)=false;
            %SetListString{i}=[edit_sets{i}.label,' ',num2str(length(edit_sets{i}.indexes)),' points'];
        end
        [SetDirectories, SetNames, SetIndices]=harvestLegacyPointSets(DataMain.handles.AAM);
        for i=1:length(SetNames)
            add_it=true;
            name=SetNames{i};
            for j=1:length(EditSetNames)
                if strcmpi(EditSetNames{j},name)
                    add_it=false;
                    haveModelFlag(i)=true;
                    break
                end
            end
            if add_it
                haveModelFlag(end+1)=true;
                EditSetNames{end+1}=name;
                EditIndices{end+1}=SetIndices{i};
            end
        end
        for i=1:length(EditSetNames)
            edit_sets{i}.label=EditSetNames{i};
            edit_sets{i}.indexes=EditIndices{i};
            %if haveModelFlag(i)
            %    SetListString{i}=[edit_sets{i}.label,' ',num2str(length(edit_sets{i}.indexes)),' points *'];
            %else
                SetListString{i}=[edit_sets{i}.label,' ',num2str(length(edit_sets{i}.indexes)),' points'];
            %end
        end
        set(Data.handles.SetList,'string',SetListString);
        set(Data.handles.SetList, 'Value', EditSetNum);
        save(edit_sets_filename,'edit_sets');
        
        %handles.dat.indices=EditIndices{pointSetNumber};
        
        %     % Discover all the possible pointsets available for the current template model
        %     AllPointSets=DiscoverPointSets(fullfile(pwd,'StatisticalModels'));
        %     set(Data.handles.SetList,'string',{AllPointSets.name});
        %     set(Data.handles.SetList, 'Value', pointSetNumber);
        Data.handles.dat.pointSetNumber=pointSetNumber;
        Data.handles.dat.AllPointSets=EditSetNames;
        Data.handles.dat.EditIndices=EditIndices;
        Data.handles.dat.EditSetNum=EditSetNum;
        Data.handles.dat.edit_sets_filename=edit_sets_filename;
        
        Data.handles.dat.tosave = 0;
        Data.handles.dat.currentLoop = [];
        set(Data.handles.txtCurrentStatus, 'ForegroundColor', 'blue','String', 'Please Choose an Operation');
        %DataMain = guidata(findobj('Tag', 'AAMToolbox'));
        Data.handles.AAM = aam;
        Data.handles.PointModelTemplate = get(Data.handles.AAM, 'PointModelTemplate');
        if ~isempty(get(Data.handles.PointModelTemplate, 'image'))
            set(Data.handles.mainAxes, 'Visible', 'off');
            cla(Data.handles.mainAxes);
            %         im=get(Data.handles.PointModelTemplate, 'image');
            %         Data.handles.dat.plotimH=imagesc(im,'parent',Data.handles.mainAxes,'HitTest', 'on'); axis image ij;
            Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
            set(Data.handles.templateDirTxt, 'String', cut_string(get(Data.handles.PointModelTemplate, 'direc')));
            set(Data.handles.templateNameTxt, 'String', get(Data.handles.PointModelTemplate, 'name'));
            set(Data.handles.projectnametxt, 'String', getCurrentAAMProjectName);
            % Now create a button down environment
            
        end
        guidata(fig, Data);
        if exist('AAMShapemodel_figure_handle')
            if ishandle(AAMShapemodel_figure_handle)
                set(AAMShapemodel_figure_handle,'visible','off');
            end
        end
        % We will pass back the data in another way because using uiwait makes debugging and interacting with this code
        % extremely cumbersome
        %     uiwait(Data.handles.figMain);
        %     Data = guidata(Data.handles.figMain);
        %     DataMain.handles.AAM = Data.handles.AAM;
        %     DataMain.handles.dat = Data.handles.dat;
        %     guidata(DataMain.handles.figMain, DataMain);
        %     delete(Data.handles.figMain);
        return;
    else
        
        Data = guidata(gcbo);
        DataMain = guidata(findobj('Tag', 'AAMToolbox'));
        switch arg
            case 'ButtonDownOnAxis'
                
            case 'DeleteGroup'
                Data.handles = DeleteGroup(Data.handles);
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
                guidata(gcbo, Data);
            case 'ClearAll'
                Data.handles = ClearAll(Data.handles);
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
                guidata(gcbo, Data);
                %         case 'ImportSetFromElsewhere' % handles.dat.allsets_indices{2:end}
                %             Data = ImportSetFromElsewhere(Data);
                %             guidata(gcbo, Data);
            case 'ImportList'
                Data.handles = ImportSets(Data.handles);
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
                Data.handles.dat.tosave=1;
                guidata(gcbo, Data);
            case 'ChangeSet'
                Data.handles = ChangeSet(Data.handles);
                Data.handles.dat.tosave=2;
                guidata(gcbo, Data);
            case 'UpdatePlot'
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
                guidata(gcbo, Data);
            case 'ToggleZoom'
                Data.handles = ToggleZoom(Data.handles);
                guidata(gcbo, Data);
            case 'TogglePan'
                Data.handles = TogglePan(Data.handles);
                guidata(gcbo, Data);
            case 'SelectLandmarks'
                set([Data.handles.panChk,Data.handles.zoomChk], 'Value', 0);
                pan off; zoom off;
                Data.handles = SelectPoints(Data.handles);
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
                guidata(gcbo, Data);
            case 'SelectMoreLandmarks'
                set([Data.handles.panChk,Data.handles.zoomChk], 'Value', 0);
                pan off; zoom off;
                Data.handles = SelectMorePoints(Data.handles);
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
                guidata(gcbo, Data);
            case 'SelectAPoint'
                set([Data.handles.panChk,Data.handles.zoomChk], 'Value', 0);
                pan off; zoom off;
                Data.handles = SelectAPoint(Data.handles);
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
                guidata(gcbo, Data);
            case 'SaveNewSet' % save the new subset of points to the listbox menu and *.edit_sets file in Templates
                Data.handles = SaveNewSet(Data.handles,'Save');
            case 'UseCurrentSet' % select the currently selected set for modelling, i.e. change DataMain in AAMToolbox
                EditSetNum = get(Data.handles.SetList, 'value');
                sets =Data.handles.dat.AllPointSets;
                %pmt = handles.PointModelTemplate;
                %[path, tname, ext] = fileparts(get(pmt, 'name'));
                %ind = load(['StatisticalModels', filesep, tname, filesep, sets{setNum}, filesep, 'indices']);
                % ind = load(['StatisticalModels', filesep, tname, filesep, sets(setNum), filesep, 'indices']);
                % union_of_indices=ExtractIndices(ind);
                % handles.dat.indices = union_of_indices;
                Data.handles.dat.indices = cell2mat(Data.handles.dat.EditIndices(EditSetNum));
                Data.handles.dat.EditSetNum = EditSetNum;                                
                Data.handles = SaveNewSet(Data.handles,'Use'); % should have set Data.handles.dat.pointSetNumber=pointSetNumber;
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
            case 'NoSubsets' % if necessary change DataMain in AAMToolbox
                DataMain = guidata(findobj('Tag', 'AAMToolbox'));
                DataMain=guidata(DataMain.handles.AAMToolbox); % get its data and modify pointsets
                pdm=get(Data.handles.AAM,'PointModelTemplate');
                pts=get(pdm,'pts');
                allindices=1:size(pts,2);
                Data.handles.dat.indices=allindices;
                pointSetNumber=[];
                for i=1:length(Data.handles.dat.AllPointSets)
                    if strcmpi(Data.handles.dat.AllPointSets{i},'Original')
                        pointSetNumber=i;
                    end
                end
                Data.handles.dat.pointSetNumber=pointSetNumber;
                Data.handles.dat.plotH = PlotTemplate(Data.handles.mainAxes, 1, ...
                    Data.handles.PointModelTemplate, Data.handles, Data.handles.dat.plotH);
            case 'Quit'
                DataMain = guidata(findobj('Tag', 'AAMToolbox'));
                DataMain=guidata(DataMain.handles.AAMToolbox); % get its data and modify pointsets
                DataMain.handles.AAM=set(DataMain.handles.AAM,'pointset',Data.handles.dat.pointSetNumber); % ALL Data.handles.dat.EditSetNum);
                DataMain.handles.AAM=set(DataMain.handles.AAM,'pointindices',Data.handles.dat.indices);
                %DataMain.handles.AAM = Data.handles.AAM;
                %DataMain.handles.dat = Data.handles.dat;
                guidata(DataMain.handles.AAMToolbox,DataMain); % put its data back and reveal AAMToolbox
                set(DataMain.handles.AAMToolbox,'visible','on');
                AAMToolbox('refresh');
                delete(AAMSetPicker_handle);
                %             uiresume;
                % %             Data = guidata(Data.handles.figMain);
                % %              delete(Data.handles.figMain);
            otherwise
                error('Unknown Option in Active Appearance Model Toolbox!!!');
        end
        %if isfield(Data.handles, 'figMain')
        %if ishandle(Data.handles.figMain)
        %  guidata(gcbo, Data);
        %end
%         DataMain.handles.AAM = Data.handles.AAM;
%         DataMain.handles.dat = Data.handles.dat;
%         % DataMain should NOT be returned to caller direct but poked into its Figure handle
%         guidata(DataMain.handles.figMain, DataMain);
%         AAMToolbox('refresh');
    end
    
function [SetDirectories, SetNames, SetIndices]=harvestLegacyPointSets(AAM)
    pmt=get(AAM,'PointModelTemplate');
    name=get(pmt,'name');
    models_for_current_template=name(1:end-9);
    %templatedir=modelDirec(1:findstr(modelDirec,'Set_')-2);
    d=dir(fullfile('StatisticalModels',models_for_current_template,'Set*'));
    subsetName='';
    indices=[];
    pointset=[];
    for i=1:length(d)
       tempDir=d(i).name;
        D=dir(fullfile('StatisticalModels',models_for_current_template,tempDir,'LN_*.mat'));
        if ~isempty(D)
            SetDirectories{i}=tempDir;
            SetNames{i}=D.name(4:end-4);
            temp=load(fullfile('StatisticalModels',models_for_current_template,SetDirectories{i},'indices.mat'));
            field=fieldnames(temp);
            indices=temp.(field{1});
            if iscell(indices)
                SetIndices(i)=indices;
            else
                SetIndices{i}=indices;
            end
        end
    end
%%%%%%%%%%%%%%%%%%%%%%
    %
    %  Save a new set
    %
    %%%%%%%%%%%%%%%%%%%%%%
function [handles] = SaveNewSet(handles,option)
    % if a set has been chosen using the listbox then
    %  handles.dat.pointSetNumber indexes into
    %  handles.dat.AllPointSets to give the name of the pointset
    %  and
    %  handles.dat.indices index the pointmodel elements that make the set
    %  (not sure what temp_indices and EditIndices do)
    
    if strcmpi(option,'Save') %~isempty(handles.dat.EditSetNum)
        prompt={'Enter the name of the new set:'};
        name='Set Name';
        numlines=1;
        defaultanswer={'New set'};
        SelectedSubsetName=inputdlg(prompt,name,numlines,defaultanswer);
        temp=load(handles.dat.edit_sets_filename);
        edit_sets=temp.edit_sets;
        edit_sets{end+1}.label=SelectedSubsetName{1};
        edit_sets{end}.indexes=handles.dat.indices;
        %save(handles.dat.edit_sets_filename,'edit_sets');
    else
        SelectedSubsetName=handles.dat.AllPointSets(handles.dat.EditSetNum);
        templatename = get(handles.PointModelTemplate, 'name');
        templatename = templatename(1:length(templatename)-9);
        modelDirec=get(handles.AAM,'modelDirec');
        templatedir=modelDirec(1:findstr(modelDirec,'Set_')-2);
        d=dir(fullfile(templatedir,'Set*'));
        for i=1:length(d)
            numbers(i)=str2num(d(i).name(5:end));
        end
        [s,sind]=sort(numbers);
        subsetName='';
        indices=[];
        pointset=[];
        for i=1:length(d)
            subsetDirTemp=d(sind(i)).name;
            D=dir(fullfile(templatedir,subsetDirTemp,'*.mat'));
            for j=1:length(D)
                if strcmpi(D(j).name(1:3),'LN_')
                    subsetNameTemp=D(j).name(4:end-4);
                    if strcmpi(subsetNameTemp,SelectedSubsetName{1})
                        pointset=i;
                        subsetIndj=j;
                        subsetDir=fullfile(templatedir,subsetDirTemp);
                    end
                end
            end
        end
        if ~isempty(pointset)
            subsetDirTemp=d(sind(pointset)).name;
            D=dir(fullfile(templatedir,subsetDirTemp,'*.mat'));
            temp=load(fullfile(templatedir,subsetDirTemp,'indices.mat'));
            %handles.dat.indices=q.setlist;
            field=fieldnames(temp);
            indices=temp.(field{1});
            if iscell(indices)
                handles.dat.indices=indices{1};
            else
                handles.dat.indices=indices;
            end
            handles.dat.pointSetNumber=pointset;
        end
        if isempty(pointset) %  it has not been modelled before
            maxset = length(d); %str2num(maxset(5:end));
            pointset=maxset+1;
            subsetDir=fullfile('StatisticalModels', templatename, ['Set_', num2str(pointset)]);
            mkdir(subsetDir);
            k=1;
            setlist{k}=handles.dat.indices;
            if isfield(handles.dat,'allsets_indices')
                for i=2:length(handles.dat.allsets_indices)
                    k=k+1;
                    setlist{k}=handles.dat.allsets_indices{i};
                end
            end
            save(fullfile(subsetDir,'indices'), 'setlist');
            set(handles.saving_message,'visible','on');
            k=1;
            setnames{k}  = SelectedSubsetName;
            if isfield(handles.dat,'allsets_names')
                for i=1:length(handles.dat.allsets_names)
                    k=k+1;
                    setnames{k}=handles.dat.allsets_names{i};
                end
            end
            save(fullfile(subsetDir, ['LN_', SelectedSubsetName{1}]),'setnames');
            mkdir(fullfile(subsetDir,'ImageList_1'));
            handles.dat.AllPointSets{end+1}=SelectedSubsetName{1};
            handles.dat.pointSetNumber=length(handles.dat.AllPointSets);
            handles.dat.pointSetNumber=pointset;
        end
        % details of the subset should now be in the dat data structure
%         % copy details of the subset to the aam data structure
%         handles.dat.pointSetNumber=pointset;
%         handles.AAM = set(handles.AAM, 'modelDirec', fullfile(subsetDir,'ImageList_1'));
%         handles.AAM = set(handles.AAM, 'pdmDirec', get(handles.AAM, 'modelDirec')); % this looks odd
%         handles.AAM = set(handles.AAM, 'sfamDirec', get(handles.AAM, 'modelDirec'));% this looks odd
%         handles.AAM = set(handles.AAM, 'pointset', pointset);
%         handles.AAM = set(handles.AAM, 'imageset', 1);
%         handles.AAM = set(handles.AAM, 'pointindices',  handles.dat.indices);
        
        % I think all the following belongs to the statistical model generator
        %     if exist('Cropped', 'dir')
        %         files = dir('Cropped/*.jpg');
        %         imageindex = 1:length(files);
        %         save(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1),filesep, 'ImageList_1', filesep, 'imageindex'], 'imageindex');
        %         handles.AAM = set(handles.AAM, 'am_imagenames', {files.name});
        %
        %         %for f = 1:length(files)
        %         %    thumbnail = imresize(imread(['Cropped', filesep, files(f).name]), [100 100]);
        %         %    imwrite(thumbnail,['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1), filesep, 'ImageList_1', filesep, files(f).name], 'JPEG');
        %         %end
        %     else
        %         error('Could not find directory ''Cropped'' to build initial point model files');
        %     end
        %     aam = handles.AAM;
        %     %RevisedAAMdataFilename=fullfile('StatisticalModels', templatename, ['Set_', num2str(maxset+1)], 'ImageList_1','model.aam_dat');
        %     RevisedAAMdataFilename=fullfile(subsetDir, 'ImageList_1','model.aam_dat');
        %     save(RevisedAAMdataFilename, 'aam');
        
    end
    
    set(handles.saving_message,'visible','off');
    return
    %%%%%%%%%%%%%%%%%%%%%%
    %
    %  ToggleZoom
    %
    %%%%%%%%%%%%%%%%%%%%%%
function [handles] = ToggleZoom(handles)
    set(handles.panChk, 'Value', 0);
    switch(get(handles.zoomChk, '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
    %%%%%%%%%%%%%%%%%%%%%%
    %
    %  Save Template    //Pretty Obvious
    %
    %%%%%%%%%%%%%%%%%%%%%%
function [handles] = TogglePan(handles)
    set(handles.zoomChk, 'Value', 0);
    switch(get(handles.panChk, '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
    %%%%%%%%%%%%%%%%%%%%%%
    %
    %  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
    %%%%%%%%%%%%%%%%%%%%
    %
    % Check that the directory is valid, i.e. it has Original and Cropped
    %
    %%%%%%%%%%%%%%%%%%%%
function [validDir] = checkDir(d, handles)
    validDir = 0;
    [cwd, direc] = fileparts(d);
    if strcmp(direc(1:4), 'PRJ_') & exist('Cropped', 'dir') & exist('Original', 'dir')
        validDir = 1;
        set([handles.currentModelTxt, handles.markBasePoints, handles.newModelBtn, handles.selectDirectory,handles.buildHierarchyBtn, handles.modelGeneratorBtn, handles.pdmWalkBtn], 'Enable', 'on');
    else
        set([handles.currentModelTxt, handles.markBasePoints, handles.newModelBtn, handles.selectDirectory,handles.buildHierarchyBtn, handles.modelGeneratorBtn, handles.pdmWalkBtn], 'Enable', 'off');
    end
    set(handles.cwdTxt, 'String', cut_string(direc));
    set(handles.matlabFilesTxt, 'String', cut_string(which('AAMToolbox')));
    return;
    
    %%%%%%%%%%%%%%%%%%%%%%
    %
    %
    %  Change Set
    %
    %%%%%%%%%%%%%%%%%%%%%%
function handles = ImportSets(handles);
    pmt=get(handles.AAM,'PointModelTemplate');
    template=get(pmt,'name');
    template=template(1:findstr(template,'.temp_dat')-1);
    set(handles.figMain, 'Pointer', 'watch');
    [lists,indices,importable_sets,edit_sets] = ImportList(template); %importable_sets,handles.dat.edit_sets);
    set(handles.figMain, 'Pointer', 'arrow');
    
    if isempty(lists)
        return;
    end
    handles.dat.importable_sets=importable_sets;
    handles.dat.edit_sets=edit_sets;
    set(handles.ListOfSets, 'String', lists);
    handles.dat.allsets_names=lists;
    handles.dat.indices=indices;
    set(handles.figMain, 'Pointer', 'arrow');
    
function [handles] = ClearAll(handles)
    handles.dat.indices=[];
    
function [handles] = DeleteGroup(handles)
    [bw,xi,yi]=roipoly;
    pts = get(handles.PointModelTemplate, 'pts');
    in=inpolygon(pts(1,:),pts(2,:),xi,yi);
    handles.dat.tosave = 1;
    ev_in=find(in>0);
    ind=intersect(handles.dat.indices,ev_in);
    for i=1:length(ind)
        ii=find(ind(i)==handles.dat.indices);
        handles.dat.indices(ii)=[];
    end
    
function [handles] = ChangeSet(handles)
    EditSetNum = get(handles.SetList, 'value');
    sets =handles.dat.AllPointSets;
    % if ~iscell(sets)
    %     sets = {sets};
    % end
    pmt = handles.PointModelTemplate;
    [path, tname, ext] = fileparts(get(pmt, 'name'));
    %ind = load(['StatisticalModels', filesep, tname, filesep, sets{setNum}, filesep, 'indices']);
    % ind = load(['StatisticalModels', filesep, tname, filesep, sets(setNum), filesep, 'indices']);
    % union_of_indices=ExtractIndices(ind);
    % handles.dat.indices = union_of_indices;
    handles.dat.indices = cell2mat(handles.dat.EditIndices(EditSetNum));
    handles.dat.EditSetNum = EditSetNum;
    handles.dat.plotH = PlotTemplate(handles.mainAxes, 1, pmt, handles, handles.dat.plotH);
    
    %%%%%%%%%%%%%%%%%%%%%%
    %
    %
    %  Select Points
    %
    %%%%%%%%%%%%%%%%%%%%%%
function [handles] = SelectPoints(handles)
    % WHY NOT USE roipoly ?
    [bw,xi,yi]=roipoly;
    pts = get(handles.PointModelTemplate, 'pts');
    
    in=inpolygon(pts(1,:),pts(2,:),xi,yi);
    if sum(in)<3
        uiwait(warndlg('You must select at least 3 points.'));
        return;
    end
    handles.dat.tosave = 1;
    ev_in=find(in>0);
    handles.dat.indices = ev_in;
    return;
    
    %%%%%%%%%%%%%%%%%%%%%%
function [handles] = SelectMorePoints(handles)
    % WHY NOT USE roipoly ?
    [bw,xi,yi]=roipoly;
    pts = get(handles.PointModelTemplate, 'pts');
    in=inpolygon(pts(1,:),pts(2,:),xi,yi);
    handles.dat.tosave = 1;
    ev_in=find(in>0);
    handles.dat.indices = [handles.dat.indices, ev_in];
    
    %%%%%%%%%%%%%%%%%%%%%%
function [handles] = SelectAPoint(handles)
    %[bw,xi,yi]=roipoly;
    disp('Select one point');
    pts = get(handles.PointModelTemplate, 'pts');
    g=ginput(1);
    %get(gcbo)
    distances=(((g(1)-pts(1,:)).^2)+(g(2)-pts(2,:)).^2);
    in=find(distances==min(distances));
    %in=inpolygon(pts(1,:),pts(2,:),xi,yi);
    handles.dat.tosave = 1;
    handles.dat.indices = [handles.dat.indices, in];
    handles.dat.plotH = PlotTemplate(handles.mainAxes, 1, ...
        handles.PointModelTemplate, handles, handles.dat.plotH);
    
    %%%%%%%%%%%%%%%%%%%%%%
function [handles] = SelectAPointWithButton(handles)
    
    handles.dat.tosave = 1;
    handles.dat.indices = [handles.dat.indices, in];
    handles.dat.plotH = PlotTemplate(handles.mainAxes, 1, ...
        handles.PointModelTemplate, handles, handles.dat.plotH);
    
