function DataMain=SetPicker(arg)
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, versnA] = 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
    edit_sets=load(fullfile('Templates','Faces11.edit_sets'),'-mat');
    edit_sets=edit_sets.edit_sets;
    for i=1:length(edit_sets)
        EditSetNames{i}=edit_sets{i}.label;
        EditIndices{i}=edit_sets{i}.indexes;
        SetListString{i}=[edit_sets{i}.label,' ',num2str(length(edit_sets{i}.indexes)),' points'];
    end
    set(Data.handles.SetList,'string',SetListString);
    set(Data.handles.SetList, 'Value', EditSetNum);
    
    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.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
%     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);
            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 'Quit'
            if isempty(Data)
                delete(AAMSetPicker_handle);
            end
            if Data.handles.dat.tosave ==1
                answer = questdlg('Do you want to save your set before quitting?');
                switch answer
                    case 'Yes'
                        Data.handles = SaveNewSet(Data.handles);
                end
            end
            delete(AAMSetPicker_handle);
            %delete(Data.handles.figMain);
            if exist('AAMShapemodel_figure_handle')
                if ishandle(AAMShapemodel_figure_handle)
                    set(AAMShapemodel_figure_handle,'visible','on');
                    AAMToolbox('refresh');
                end
            end
%             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);
end

%%%%%%%%%%%%%%%%%%%%%%
%
%  Save a new set
%
%%%%%%%%%%%%%%%%%%%%%%
function [handles] = SaveNewSet(handles)

prompt={'Enter the logical name of the new set:'};
name='Set Name';
numlines=1;
defaultanswer={'New set'};
answer=inputdlg(prompt,name,numlines,defaultanswer);
if ~isempty(answer)
    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*'));
    maxset = length(d); %str2num(maxset(5:end));
    mkdir(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1)]);
    %indices = handles.dat.indices;
    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(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1), filesep, 'indices'], 'setlist');
    indices = handles.dat.indices;
    set(handles.saving_message,'visible','on');
    k=1;
    setnames{k}  = answer;
    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(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1), filesep, 'LN_', answer{1}],'setnames');
    mkdir(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1), filesep, 'ImageList_1']);
    d = 0;
        save(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1), filesep, 'ImageList_1', filesep, 'LN_Original'], 'd');

    handles.AAM = set(handles.AAM, 'modelDirec', ['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1), filesep, 'ImageList_1']);
    handles.AAM = set(handles.AAM, 'pdmDirec', get(handles.AAM, 'modelDirec'));
    handles.AAM = set(handles.AAM, 'sfamDirec', get(handles.AAM, 'modelDirec'));
    handles.AAM = set(handles.AAM, 'pointset', maxset+1);
    handles.AAM = set(handles.AAM, 'imageset', 1);
    handles.AAM = set(handles.AAM, 'pointindices', indices);
    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;
    save(['StatisticalModels', filesep, templatename, filesep, 'Set_', num2str(maxset+1), filesep, 'ImageList_1', filesep,'model.aam_dat'], 'aam');
    set(handles.saving_message,'visible','off');
end
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, version] = 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);

