function varargout = histosettingGUI(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @histosettingGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @histosettingGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before histosettingGUI is made visible.
function histosettingGUI_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;

try
        def       = varargin{1};
        binvalue  = def{1};
        normhisto = def{2};
        chisto    = def{3};
        fitnormd  = def{4};
        cfitnorm  = def{5};
        nvalue   = def{6};
catch
        binvalue  = 'auto';
        normhisto = 0;
        chisto    = [1 0.5 0.2];
        fitnormd  = 0;
        cfitnorm  = [1 0 0];
        nvalue   = 100;
end
if isempty(binvalue)
        binvalue = 'auto';
end
if isempty(normhisto)
        normhisto = 0;
end
if isempty(chisto)
        chisto = [1 0.5 0.2];
end
if isempty(cfitnorm)
        cfitnorm = [1 0 0];
end
if isempty(fitnormd)
        fitnormd = 0;
end
if isempty(nvalue)
        nvalue = 100;
end

handles.binvalue  = binvalue;
handles.normhisto = normhisto;
handles.chisto    = chisto;
handles.cfitnorm  = cfitnorm;
handles.fitnormd  = fitnormd;
handles.nvalue    = nvalue;

%
% Name & version
%
version = geterplabversion;
set(handles.gui_chassis,'Name', ['ERPLAB ' version '   -   Histogram Settings GUI'],'WindowStyle','modal')

%
% Color GUI
%
handles = painterplab(handles);

%
% Set font size
%
handles = setfonterplab(handles);

% Update handles structure
guidata(hObject, handles);

if ischar(binvalue)
        set(handles.edit_nbinh, 'String', binvalue)
else
        set(handles.edit_nbinh, 'String', vect2colon(binvalue,'Delimiter', 'off'))
end
set(handles.checkbox_normhist, 'Value', normhisto)
set(handles.checkbox_fitnormal,'Value', fitnormd)

% if normhisto
%         set(handles.checkbox_fitnormal, 'Enable', 'on')
%         set(handles.checkbox_fitnormal,'Value', fitnormd)
%         set(handles.pushbutton_colornormdist, 'Enable', 'on')
% else
%         set(handles.checkbox_fitnormal, 'Value', 0)
%         set(handles.checkbox_fitnormal, 'Enable', 'off')
%         set(handles.pushbutton_colornormdist, 'Enable', 'off')
% end

% UIWAIT makes histosettingGUI wait for user response (see UIRESUME)
uiwait(handles.gui_chassis);

% --- Outputs from this function are returned to the command line.
function varargout = histosettingGUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

% The figure can be deleted now
delete(handles.gui_chassis);
pause(0.1)

%----------------------------------------------------------------
function edit_nbinh_Callback(hObject, eventdata, handles)

%----------------------------------------------------------------
function edit_nbinh_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%----------------------------------------------------------------
function pushbutton_cancel_Callback(hObject, eventdata, handles)
handles.output= [];
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

%----------------------------------------------------------------
function pushbutton_OK_Callback(hObject, eventdata, handles)

binvalue  = get(handles.edit_nbinh, 'String');
if isempty(binvalue)
        msgboxText =  'You have to specify one value at list!';
        title = 'Error: histosettingGUI';
        errorfound(sprintf(msgboxText), title);
        return
end
binvalue = strrep(binvalue,'''','');
if ~strcmpi(binvalue,'auto') && isempty(str2num(binvalue))
        msgboxText =  ['%s is not a valid input.\n\n'...
                'Enter a single value, a monotonically non-decreasing vector, or ''auto''.\n'...
                'Or just click the "suggest" button.'];
        title = 'Error: histosettingGUI';
        errorfound(sprintf(msgboxText, binvalue), title);
        return

elseif ~strcmpi(binvalue,'auto') && ~isempty(str2num(binvalue))
        binvalue = str2num(binvalue);
end

normhisto = get(handles.checkbox_normhist, 'Value');
chisto    = handles.chisto;
fitnormd  = get(handles.checkbox_fitnormal, 'Value');
cfitnorm  = handles.cfitnorm;

erpworkingmemory('BinHisto', binvalue);
erpworkingmemory('NormHisto', normhisto);
erpworkingmemory('FitNormd', fitnormd);

handles.output = {binvalue, normhisto, chisto, fitnormd, cfitnorm};
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

%----------------------------------------------------------------
function pushbutton_colorhist_Callback(hObject, eventdata, handles)
chisto = handles.chisto;
chisto = uisetcolor(chisto,'Histogram color') ;
erpworkingmemory('HistoColor', chisto);

handles.chisto = chisto;
% Update handles structure
guidata(hObject, handles);

%----------------------------------------------------------------
function checkbox_normhist_Callback(hObject, eventdata, handles)
% if get(hObject,'Value')
%         set(handles.checkbox_fitnormal, 'Enable', 'on')
%         set(handles.pushbutton_colornormdist, 'Enable', 'on')
% else
%         set(handles.checkbox_fitnormal, 'Value', 0)
%         set(handles.checkbox_fitnormal, 'Enable', 'off')
%         set(handles.pushbutton_colornormdist, 'Enable', 'off')
% end

%----------------------------------------------------------------
function checkbox_fitnormal_Callback(hObject, eventdata, handles)

%----------------------------------------------------------------
function pushbutton_colornormdist_Callback(hObject, eventdata, handles)
cfitnorm = handles.cfitnorm;
cfitnorm = uisetcolor(cfitnorm,'Curve color') ;
erpworkingmemory('FnormColor', cfitnorm);

handles.cfitnorm = cfitnorm;
% Update handles structure
guidata(hObject, handles);

%----------------------------------------------------------------
function pushbutton_autobinhisto_Callback(hObject, eventdata, handles)
nvalue = handles.nvalue;
binvalue = round(sqrt(nvalue));
handles.binvalue = binvalue;
% Update handles structure
guidata(hObject, handles);

set(handles.edit_nbinh, 'String', num2str(binvalue));

%--------------------------------------------------------------------------
function gui_chassis_CloseRequestFcn(hObject, eventdata, handles)
if isequal(get(handles.gui_chassis, 'waitstatus'), 'waiting')
        handles.output= [];
        % Update handles structure
        guidata(hObject, handles);
        uiresume(handles.gui_chassis);
else
        % The GUI is no longer waiting, just close it
        delete(handles.gui_chassis);
end

% chisto   = erpworkingmemory('HistoColor'); % histogram color
% cfitnorm = erpworkingmemory('FnormColor'); % line color for fitted normal distribution
% fitnormd = erpworkingmemory('FitNormd'); % select window measurement by mouse option


function AlignTsp2Whl_All(varargin)

% USAGE
%     AlignTsp2Whl_All('parameters','values')
%
% Inputs:
%    SIMPLEST THING TO DO: call AlignTsp2Whl_All()
%
%    WARNING: it is assumed that the root folder name and the final merge name are the same. If not, use
%    the 'mergename' option. Typically the root folder is something like
%    /xxx/yyy/AnimalZZZ-DayA/ and the merged data are in /xxx/yyy/AnimalZZZ-DayA/AnimalZZZ-DayA/
%
% - options:
%     'mergename': if the merged data are not in 'fbasename/fbasename' but in
%     'fbasename/mergename', then indicate with this option the name of the
%     merged data directory
%     'merge': if set to 1 (default 1) the function will merge the whl
%     dat into one single whl file 'fbasename/mergename/mergename.whl'.
%     'colorIx': a 2 value vector [colFront colRear] which defines which
%     color from [R G B] is the front and rear LEDs. Default: [1 3]*
%     'folderNames': a cell array of filenames in the order they will be
%     merged. If omitted, the program looks at the merged files in the xml
%     file contained in '/dir1/dir2/.../fbasename/mergename/mergename.xml'
%     'fromMpg': if 1 (default 0) will reconstruct the tracking from the
%     video
%
% Dependencies: xml_toolbox (easy to find on the web)
%
% Adrien Peyrache, 2012

merge=1;
colorIx=[1 3];
tspFiles = {};
tspFilesIx = [];
frommpg = 0;
[dummy fbasename dummy] = fileparts(pwd);

mergename = fbasename;

for i = 1:2:length(varargin),
  if ~isa(varargin{i},'char'),
    error(['Parameter ' num2str(i+3) ' is not a property (type ''help bz_LoadBinary'' for details).']);
  end
  switch(lower(varargin{i})),
    case 'mergename',
      mergename = varargin{i+1};
      if ~ischar(mergename)
        error('Incorrect value for property ''mergename''. Should be char array.');
      end
    case 'merge',
      merge = varargin{i+1};
      if merge ~= 1 || merge ~= 0
        error('Incorrect value for property ''merge''. Should be logical.');
      end
    case 'colorix',
      colorIx = varargin{i+1};
      if length(colorIx)~=2
        error('Incorrect value for property ''colorIx''. Should be 3 element vector of logical values.');
      end
    case 'folderNames',
      tspFiles = varargin{i+1};
      isachar = 1;
      for fix=1:length(tspFiles),isachar=isachar*isa(tspFiles{fix},'char');end
      if ~isa(tspFiles,'cell') || ~isachar
        error('Incorrect value for property ''tspFiles''. Should be a cell array of filenames');
      end
     case 'frommpg',
         frommpg = varargin{i+1};
         if ~isnumeric(frommpg)
            error('Incorrect value for property ''frommpg''. Should be 0 pr 1');
         end
     case 'tspFilesix',
         tspFilesIx = varargin{i+1};
  end
end

% if isempty(tspFiles)
%     xmldata = xml_load([fbasename '.xml']);
%     segnames = xmldata.multiFileProcessing.files;
%
%     if isempty(tspFilesIx)
%         tspFilesIx = (1:length(segnames));
%     else
%         tspFilesIx = tspFilesIx(:)';
%     end
%     tspFiles = cell(length(tspFilesIx),1);
%     for ii=1:length(tspFilesIx)
%         tspFiles{ii} = segnames(tspFilesIx(ii)).fileBaseName;
%     end
% end

tsptemp = dir('*.tsp');%get list of tsp files (to structure);
for a = 1:length(tsptemp)
    tspFiles{a}=tsptemp(a).name(1:end-4);
end

fprintf('Creating whl files...\n')
for fix=1:length(tspFiles)
    fname = tspFiles{fix};
    fprintf('\t%s\n',fname)
%     try
        AlignTsp2Whl(fname,colorIx,frommpg);
%     catch
%         keyboard
%     end
end

if merge
    fprintf('Merging files...\n')
    whlall = [];
    for fix=1:length(tspFiles)
        fname = tspFiles{fix};
        whl = load([fname '.whl']);
        whlall = [whlall;whl];
    end
    dlmwrite([mergename '.whl'],whlall,'delimiter','\t');
end


function fmri_loc2_GLMcontrasts

% LO Localizer scans processing code
%
% USER IMPORTANT!!!: Before running this script, make sure that all loloc
% scans have the correct annotation fields and scan groups (are grouped
% correctly). Otherwise, fmri_FFA_checkDataTypesForGLM will fail.
%
% 1. Set GLM parameters for all scans
% 2. Check LO localizer experiments for:
%    a. Datatype and scan numbers
%    b. Record parfiles
%    c. Make sure scan groupings are correct
% 3. Run GLM for LO localizer experiments
% 4. Run contrasts for the LO localizer experiments
%
% Calls the functions:
% * fmri_loc2_setGLMparams (subfunction)
% * fmri_loc2_checkDataTypesForGLM
% * fmri_loc2_computeContrastsLocalizer
%
%
% DY 06/05/2008
% Modified 06/18/2008: there are calls to er_setParams and saveSessions all
% over the place, which results in the params for the MotionComp_RefScan1
% being changed for the worse. I'm not sure how to efficiently prevent this
% from happening, so instead, I let it happen, and just fix the ANNOTATION
% and PARFILE fields at the end, since accuracy here is important.
%
% Code taken from fmri_FFA_motionCompFix
% AL 11/08 Modified for loc2 GLM

clear all

% Set directory and subject list
% Alternatively: subs = {'sess1','sess2','sess3',...};
if ispc
    fmriDir = 'W:\projects\Kids\fmri\localizer\';
else
    %fmriDir = '/biac1/kgs/projects/Kids/fmri/localizer/';
    fmriDir='/biac1/kgs/projects/Kids/fmri/code/Alina/Subject/';
end
cd(fmriDir); s=dir('*0*'); subs={s.name};

% Start a log text file to document successes and failures in preprocessing
dateAndTime=datestr(now); dateAndTime(12)='_'; dateAndTime(15)='h';dateAndTime(18)='m';
logDir=fullfile(fmriDir,'logs');
if ~isdir(logDir), mkdir(logDir), end;
logFile = fullfile(fmriDir,'logs',['LO2_Log_' dateAndTime '.txt']);
fid=fopen(logFile,'w');
[junk,logFileName]=fileparts(logFile)
scriptName = 'fmri_loc2_GLMcontrasts.m';
startTime = clock;

% 1. Set GLM parameters
params=fmri_loc2_setGLMparams(fid,logFileName,scriptName); % Subfunction within this script

for ii=1:length(subs)

    % Get rid of all mrVista globals in workspace. Put this at the top,
    % just in case we break from the rest of the loop.
    clear dataTYPES mrSESSION vANATOMYPATH HOMEDIR hI newDt newScan

    thisDir = fullfile(fmriDir,subs{ii}); cd(thisDir);
    fprintf(fid,'\n ------------------------------------------ \n');
    fprintf(fid,'Processing %s\n\n',thisDir);
    fprintf('Processing %s\n\n',thisDir);

    %% Check if the subject already has been processed by script (and thus
    %% should not be re-entered to this script). If they do, skip to the
    %% next subject by using CONTINUE.
    load mrSESSION.mat
    theglm=find(strcmp({dataTYPES.name},'GLMs'));
     if ~isempty(theglm)
        checkScans=length(dataTYPES(theglm).eventAnalysisParams);
        alreadyDone=[];
        for xx=1:checkScans
            tmp=(strfind(lower(dataTYPES(theglm).eventAnalysisParams(xx).annotation),'lo localizer run 2'));
            alreadyDone=[alreadyDone tmp];
        end
        if(~isempty(alreadyDone))
            fprintf(fid,'Error: Subject already processed (has GLM with ''LO localizer Run 2'' in annotation field), skipping... \n\n');
            fprintf('Error: Subject already processed (has GLM with ''LO localizer Run 2'' in annotation field), skipping... \n\n');
            continue
        end
    end

    %% 2a/b/c. Find datatype number for MotionComp_RefScan1, find scan
    %% numbers for lo localizer scans, record parfiles for these scans and
    %% make sure scan groupings are correct. If everything checks out,
    %% proceed with GLM. If not, SKIP THIS SUBJECT.
    [go,s2]=fmri_loc2_checkDataTypesForGLM(fid,dataTYPES);
    %clear dataTYPES mrSESSION vANATOMYPATH

    % If there was a problem in step 3, skip GLM and proceed to next
    % subject
    if go==0
        continue

    %% 3. Otherwise, run GLM (to debug: fid=1)
    elseif go==1
        try
            % Initialize a hidden view of the 'inplane' data (like invoking
            % mrVista without a GUI, dataTYPES/etc in workspace)
            hI = initHiddenInplane(s1.mc, s1.scan);
            params.parfiles={s1.parfile};
            er_setParams(hI, params, s2.scan, s2.mc); % write params as eventAnalysisParams fields
            tic; [hI, lo_scan] = applyGlm(hI,s2.mc, s2.scangroup,params);
            time=toc;
            fprintf(fid,'GLM COMPLETED -- dt %d, scan %d. Time: %d m %2.2f s \n\n',...
                hI.curDataType,lo_scan,floor(time/60),mod(time,60));
            fprintf('GLM COMPLETED -- dt %d, scan %d. Time: %d m %2.2f s \n\n',...
                hI.curDataType,lo_scan,floor(time/60),mod(time,60));
            glmOK=1;
        catch
            fprintf(fid,'FAILURE TO SUCCESSFULLY RUN GLM \n');
            fprintf('FAILURE TO SUCCESSFULLY RUN GLM \n');
            theerror=lasterror;
            fprintf(fid,'%s \n\n',theerror.message);
            fprintf('%s \n\n',theerror.message);
            glmOK=0;
        end

        %% 4. Compute contrast maps
        if glmOK

            try
                fmri_loc2_computeContrastsLocalizer(hI, lo_scan)
                fprintf(fid,'Computed contrasts using fmri_FFA_computeContrastsLocalizer \n');
                fprintf('Computed contrasts using fmri_FFA_computeContrastsLocalizer \n');
            catch
                fprintf(fid,'FAILURE TO SUCCESSFULLY COMPUTE CONTRASTS \n');
                fprintf('FAILURE TO SUCCESSFULLY COMPUTE CONTRASTS \n');
                theerror=lasterror;
                fprintf(fid,'%s \n\n',theerror.message);
                fprintf('%s \n\n',theerror.message);

            end
        end
    end

    % Fix the annotation and parfile fields for the MotionComp_RefScan
    % dataTYPE, since these are undesirably changed (collateral damage).
    dataTYPES(s2.mc).eventAnalysisParams(s2.scan).annotation='loloc_run2';
    par2=dataTYPES(s2.mc).scanParams(s2.scan).parfile;
    dataTYPES(s2.mc).eventAnalysisParams(s2.scan).parfiles=par2;
    save(fullfile(thisDir,'mrSESSION.mat'),'mrSESSION','dataTYPES', '-append');
    clear par1 par2

end

totalTime=etime(clock,startTime);

fprintf(fid,'\n ------------------------------------------ \n');
fprintf(fid,'Total running time for script: %f minutes \n',totalTime/60);
fprintf('Total running time for script: %f minutes \n',totalTime/60);

fclose(fid); % close out the log file

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function params=fmri_loc2_setGLMparams(fid,logFileName,scriptName)

% Set GLM parameters: We set the PARAMS struct fields to the values on the
% wiki, which are further explained there. Also we print the values to the
% log. http://vpnl.stanford.edu/internal/wiki/index.php/ROIanalysis#GLMs

fprintf(fid,'\n ------------------------------------------ \n');
fprintf(fid,'\n GLM PARAMETERS \n');
fprintf(fid,' ------------------------------------------ \n');

params=er_defaultParams % Initialize param struct with defaults
p.al='params.alpha=0.0500'; eval(p.al); fprintf(fid,'%s \n',p.al);
p.at='params.ampType=''betas'''; eval(p.at); fprintf(fid,'%s \n',p.at);
p.an='params.annotation=''LO localizer Run 2'''; eval(p.an); fprintf(fid,'%s \n',p.an);
p.ap='params.assignParfiles=0'; eval(p.ap); fprintf(fid,'%s \n',p.ap);
p.bp='params.bslPeriod=[-6 -5 -4 -3 -2 -1 0]'; eval(p.bp); fprintf(fid,'%s \n',p.bp);
p.dt='params.detrend=1'; eval(p.dt); fprintf(fid,'%s \n',p.dt);
p.df='params.detrendFrames=20;'; eval(p.df); fprintf(fid,'%s \n',p.df);
p.ea='params.eventAnalysis=1'; eval(p.ea); fprintf(fid,'%s \n',p.ea);
p.eb='params.eventsPerBlock=6'; eval(p.eb); fprintf(fid,'%s \n',p.eb);
p.fp='params.framePeriod=2'; eval(p.fp); fprintf(fid,'%s \n',p.fp);
p.gt='params.glmHRF=3'; eval(p.gt); fprintf(fid,'%s \n',p.gt);
p.gp='params.glmHRF_params=[6 16 1 1 6 0 24]'; eval(p.gp); fprintf(fid,'%s \n',p.gp);
p.gw='params.glmWhiten=0'; eval(p.gw); fprintf(fid,'%s \n',p.gw); % temporal autocorrelation
p.ic='params.inhomoCorrect=1'; eval(p.ic); fprintf(fid,'%s \n',p.ic);
p.lp='params.lowPassFilter=0'; eval(p.lp); fprintf(fid,'%s \n',p.lp);
p.nb='params.normBsl=1'; eval(p.nb); fprintf(fid,'%s \n',p.nb);
p.od='params.onsetDelta=0'; eval(p.od); fprintf(fid,'%s \n',p.od);
p.pf='params.parfiles='''''; eval(p.pf); fprintf(fid,'%s \n',p.pf); % fill in after checkDataTypes...
p.pp='params.peakPeriod=[4 5 6 7 8 9 10 11 12 13 14]'; eval(p.pp); fprintf(fid,'%s \n',p.pp);
p.sh='params.setHRFParams=0'; eval(p.sh); fprintf(fid,'%s \n',p.sh);
p.sc='params.snrConds=1'; eval(p.sc); fprintf(fid,'%s \n',p.sc);
p.tn='params.temporalNormalization=0'; eval(p.tn); fprintf(fid,'%s \n',p.tn);
p.tw='params.timeWindow=[-6:1:24]'; eval(p.tw); fprintf(fid,'%s \n',p.tw);
p.log=['params.logFile=''' logFileName '''']; eval(p.log); fprintf(fid,'%s \n',p.log)
p.script=['params.scriptName=''' scriptName '''']; eval(p.script); fprintf(fid,'%s \n',p.script)

% params.framePeriod = dataTYPES(dt).scanParams(scan).framePeriod;


% pop_delset() - Delete a dataset from the variable containing
%                all datasets.
%
% Usage: >> ALLEEG = pop_delset(ALLEEG, indices);
%
% Inputs:
%   ALLEEG   - array of EEG datasets
%   indices  - indices of datasets to delete. None -> a pop_up window asks
%              the user to choose. Index < 0 -> it's positive is given as
%              the default in the pop-up window (ex: -3 -> default 3).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_copyset(), eeglab()

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% load a set and store it in the current set
% ------------------------------------------
function [ALLSET, command] = pop_delset(ALLSET, set_in);

command = '';
if nargin < 1
	help pop_delset;
	return;
end;
if isempty( ALLSET )
	error('Cannot delete dataset. Restart eeglab to clear all dataset information');
    return;
end;

if nargin < 2 | set_in < 0
	% which set to delete
	% -----------------
	promptstr    = { 'Dataset(s) to delete:' };
	if nargin == 2
		inistr       = { int2str(-set_in) };
	else
		inistr       = { '1' };
	end;
	result       = inputdlg2( promptstr, 'Delete dataset -- pop_delset()', 1,  inistr, 'pop_delset');
	size_result  = size( result );
	if size_result(1) == 0 return; end;
	set_in   	 = eval( [ '[' result{1} ']' ] );
end;

if isempty(set_in)
	return;
end;

A = fieldnames( ALLSET );
A(:,2) = cell(size(A));
A = A';
for i = set_in
   try
   		ALLSET(i) = struct(A{:});
		%ALLSET = setfield(ALLSET, {set_in}, A{:}, cell(size(A)));
	catch
		error('Error: no such dataset');
		return;
	end;
end;

command = sprintf('%s = pop_delset( %s, [%s] );', inputname(1), inputname(1), int2str(set_in));
return;


%%generate data config
param.split_data_num=1;
param.file_path_cam1=fullfile(fileparts(pwd),'people_tuples','scen1');%for test
param.file_path_cam2=fullfile(fileparts(pwd),'people_tuples','scen2');%for train
param.file_path_cam3=fullfile(fileparts(pwd),'people_tuples','scen3');%for train
param.save_traindata_filename='train_data_LPW';
param.save_testdata_filename='test_data_LPW';
%%generate ten split train/test data
for split_num_start=1:param.split_data_num
    if ~exist(strcat(param.save_traindata_filename,num2str(split_num_start)),'file')
        mkdir(strcat(param.save_traindata_filename,num2str(split_num_start)));
    end
    if ~exist(strcat(param.save_testdata_filename,num2str(split_num_start)),'file')
        mkdir(strcat(param.save_testdata_filename,num2str(split_num_start)));
    end
    subdir_cam3_view1=dir(strcat(param.file_path_cam3,'view1'));
    subdir_cam3_view2=dir(strcat(param.file_path_cam3,'view2'));
    subdir_cam3_view3=dir(strcat(param.file_path_cam3,'view3'));
    subdir_cam3_view4=dir(strcat(param.file_path_cam3,'view4'));
    subdir_cam2_view1=dir(strcat(param.file_path_cam2,'view1'));
    subdir_cam2_view2=dir(strcat(param.file_path_cam2,'view2'));
    subdir_cam2_view3=dir(strcat(param.file_path_cam2,'view3'));
    subdir_cam2_view4=dir(strcat(param.file_path_cam2,'view4'));

    subdir_cam1_view1=dir(strcat(param.file_path_cam1,'view1'));
    subdir_cam1_view2=dir(strcat(param.file_path_cam1,'view2'));
    subdir_cam1_view3=dir(strcat(param.file_path_cam1,'view3'));

    label_train_cam2_view1=[];
    train_image_name_cam2_view1={};
    label_train_cam2_view2=[];
    train_image_name_cam2_view2={};
    label_train_cam2_view3=[];
    train_image_name_cam2_view3={};
    label_train_cam2_view4=[];
    train_image_name_cam2_view4={};
    label_train_cam3_view1=[];
    train_image_name_cam3_view1={};
    label_train_cam3_view2=[];
    train_image_name_cam3_view2={};
    label_train_cam3_view3=[];
    train_image_name_cam3_view3={};
    label_train_cam3_view4=[];
    train_image_name_cam3_view4={};
    nameMapLabel_cam2=[];
    nameMapLabel_cam3=[];
    for i=3:(length(subdir_cam2_view3))
        fprintf('process test data cam2 view3:%d/%d\n',i,(length(subdir_cam2_view3)));
        image_path_cam2=strcat(param.file_path_cam2,'view3/',subdir_cam2_view3(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        nameMapLabel_cam2=[nameMapLabel_cam2;str2num(subdir_cam2_view3(i).name)];
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view3=[label_train_cam2_view3;str2num(subdir_cam2_view3(i).name)];
            train_image_name_cam2_view3=[train_image_name_cam2_view3,image_name];
        end
    end
    for i=3:(length(subdir_cam2_view1))
        fprintf('process test data cam2 view1:%d/%d\n',i,(length(subdir_cam2_view1)));
        image_path_cam2=strcat(param.file_path_cam2,'view1/',subdir_cam2_view1(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view1=[label_train_cam2_view1;str2num(subdir_cam2_view1(i).name)];
            train_image_name_cam2_view1=[train_image_name_cam2_view1,image_name];
        end
    end
    for i=3:(length(subdir_cam2_view2))
        fprintf('process test data cam2 view2:%d/%d\n',i,(length(subdir_cam2_view2)));
        image_path_cam2=strcat(param.file_path_cam2,'view2/',subdir_cam2_view2(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view2=[label_train_cam2_view2;str2num(subdir_cam2_view2(i).name)];
            train_image_name_cam2_view2=[train_image_name_cam2_view2,image_name];
        end
    end
    for i=3:(length(subdir_cam2_view4))
        fprintf('process test data cam2 view2:%d/%d\n',i,(length(subdir_cam2_view4)));
        image_path_cam2=strcat(param.file_path_cam2,'view4/',subdir_cam2_view4(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view4=[label_train_cam2_view4;str2num(subdir_cam2_view4(i).name)];
            train_image_name_cam2_view4=[train_image_name_cam2_view4,image_name];
        end
    end
    %generate data for cam3
    for i=3:(length(subdir_cam3_view3))
        fprintf('process test data cam3 view3:%d/%d\n',i,(length(subdir_cam3_view3)));
        image_path_cam3=strcat(param.file_path_cam3,'view3/',subdir_cam3_view3(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        nameMapLabel_cam3=[nameMapLabel_cam3;str2num(subdir_cam3_view3(i).name)];
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view3=[label_train_cam3_view3;str2num(subdir_cam3_view3(i).name)];
            train_image_name_cam3_view3=[train_image_name_cam3_view3,image_name];
        end
    end
    for i=3:(length(subdir_cam3_view1))
        fprintf('process test data cam3 view1:%d/%d\n',i,(length(subdir_cam3_view1)));
        image_path_cam3=strcat(param.file_path_cam3,'view1/',subdir_cam3_view1(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view1=[label_train_cam3_view1;str2num(subdir_cam3_view1(i).name)];
            train_image_name_cam3_view1=[train_image_name_cam3_view1,image_name];
        end
    end
    for i=3:(length(subdir_cam3_view2))
        fprintf('process test data cam3 view2:%d/%d\n',i,(length(subdir_cam3_view2)));
        image_path_cam3=strcat(param.file_path_cam3,'view2/',subdir_cam3_view2(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view2=[label_train_cam3_view2;str2num(subdir_cam3_view2(i).name)];
            train_image_name_cam3_view2=[train_image_name_cam3_view2,image_name];
        end
    end
    for i=3:(length(subdir_cam3_view4))
        fprintf('process test data cam3 view4:%d/%d\n',i,(length(subdir_cam3_view4)));
        image_path_cam3=strcat(param.file_path_cam3,'view4/',subdir_cam3_view4(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view4=[label_train_cam3_view4;str2num(subdir_cam3_view4(i).name)];
            train_image_name_cam3_view4=[train_image_name_cam3_view4,image_name];
        end
    end
    for i=1:length(label_train_cam2_view1)
        temp=find(nameMapLabel_cam2==label_train_cam2_view1(i));
        label_train_cam2_view1(i)=temp;
    end
    for i=1:length(label_train_cam2_view2)
        temp=find(nameMapLabel_cam2==label_train_cam2_view2(i));
        label_train_cam2_view2(i)=temp;
    end
    for i=1:length(label_train_cam2_view3)
        temp=find(nameMapLabel_cam2==label_train_cam2_view3(i));
        label_train_cam2_view3(i)=temp;
    end
    for i=1:length(label_train_cam2_view4)
        temp=find(nameMapLabel_cam2==label_train_cam2_view4(i));
        label_train_cam2_view4(i)=temp;
    end
    cam_label_max=size(nameMapLabel_cam2,1);
    for i=1:length(label_train_cam3_view1)
        temp=find(nameMapLabel_cam3==label_train_cam3_view1(i));
        label_train_cam3_view1(i)=temp+cam_label_max;
    end
    for i=1:length(label_train_cam3_view2)
        temp=find(nameMapLabel_cam3==label_train_cam3_view2(i));
        label_train_cam3_view2(i)=temp+cam_label_max;
    end
    for i=1:length(label_train_cam3_view3)
        temp=find(nameMapLabel_cam3==label_train_cam3_view3(i));
        label_train_cam3_view3(i)=temp+cam_label_max;
    end
    for i=1:length(label_train_cam3_view4)
        temp=find(nameMapLabel_cam3==label_train_cam3_view4(i));
        label_train_cam3_view4(i)=temp+cam_label_max;
    end
    save(strcat(param.save_traindata_filename,num2str(split_num_start),'/train_data.mat'),'label_train_cam2_view1','label_train_cam2_view2','label_train_cam2_view3','label_train_cam2_view4', ...
        'label_train_cam3_view1','label_train_cam3_view2','label_train_cam3_view3','label_train_cam3_view4', ...
        'train_image_name_cam2_view1','train_image_name_cam2_view2','train_image_name_cam2_view3','train_image_name_cam2_view4', ...
        'train_image_name_cam3_view1','train_image_name_cam3_view2','train_image_name_cam3_view3','train_image_name_cam3_view4','-v7.3');
    %generate test data
    test_data_cam1=[];
    label_test_cam1=[];
    test_image_name_cam1={};
    test_data_cam2=[];
    label_test_cam2=[];
    test_image_name_cam2={};
    test_data_cam3=[];
    label_test_cam3=[];
    test_image_name_cam3={};
    nameMapLabel=[];
    for i=3:(length(subdir_cam1_view2))
        fprintf('process test data view2:%d/%d\n',i,(length(subdir_cam1_view2)));
        image_path_cam2=strcat(param.file_path_cam1,'view2/',subdir_cam1_view2(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        nameMapLabel=[nameMapLabel;str2num(subdir_cam1_view2(i).name)];
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_test_cam2=[label_test_cam2;str2num(subdir_cam1_view2(i).name)];
            test_image_name_cam2=[test_image_name_cam2,image_name];
        end
    end
    for i=3:(length(subdir_cam1_view1))
        fprintf('process test data view1:%d/%d\n',i,(length(subdir_cam1_view1)));
        image_path_cam1=strcat(param.file_path_cam1,'view1/',subdir_cam1_view1(i).name,'/');
        image_list_cam1=dir(image_path_cam1);
        for j=3:length(image_list_cam1);
            image_name=strcat(image_path_cam1,image_list_cam1(j).name);
            label_test_cam1=[label_test_cam1;str2num(subdir_cam1_view1(i).name)];
            test_image_name_cam1=[test_image_name_cam1,image_name];
        end
    end
    for i=3:(length(subdir_cam1_view3))
        fprintf('process test data view3:%d/%d\n',i,(length(subdir_cam1_view3)));
        image_path_cam3=strcat(param.file_path_cam1,'view3/',subdir_cam1_view3(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_test_cam3=[label_test_cam3;str2num(subdir_cam1_view3(i).name)];
            test_image_name_cam3=[test_image_name_cam3,image_name];
        end
    end
    for i=1:length(label_test_cam1)
        temp=find(nameMapLabel==label_test_cam1(i));
        label_test_cam1(i)=temp;
    end
    for i=1:length(label_test_cam2)
        temp=find(nameMapLabel==label_test_cam2(i));
        label_test_cam2(i)=temp;
    end
    for i=1:length(label_test_cam3)
        temp=find(nameMapLabel==label_test_cam3(i));
        label_test_cam3(i)=temp;
    end
    save(strcat(param.save_testdata_filename,num2str(split_num_start),'/test_data.mat'),'label_test_cam1','label_test_cam2','label_test_cam3','test_image_name_cam1','test_image_name_cam2','test_image_name_cam3','-v7.3');
end


function prtUtilSplitLegend(axisH,symbolH,labelH)
% prtUtilSplitLegend split the current legend into two parts on either
%   side of the axes
%
% prtUtilSplitLegend with no input arguments splits the current legend in half
%
% prtUtilSplitLegend(axisHandle,lineHandles,strings) makes a legend on the current
% axes for the specified lines, with the specified strings.
%
% % Examples:
% close all;
% h = plot(rand(5,40));
% strings = prtUtilCellPrintf('%d',num2cell(1:40));
% legend(h,strings);
% prtUtilSplitLegend
%
% % Or:
% h = plot(rand(5,40));
% strings = prtUtilCellPrintf('%d',num2cell(1:40));
% prtUtilSplitLegend(gca,h,strings);
%

if nargin == 0
    axisH = gca;
    [legendH,~,symbolH] = legend;
    labelH = get(legendH,'String');
end

border = 0.05;        % Normalized
innerBorder = 0;

% Test legend width
midPt = round(length(symbolH)/2);
lgEastH = legend(gca,symbolH(midPt+1:end),labelH(midPt+1:end),'Location','EastOutside');
lgEastPos = get(lgEastH,'Position');
legendWidth = lgEastPos(3);

% Set axis location
legend(axisH,'off')
currentAxisPos = get(axisH,'OuterPosition');
newAxisPos = [...
    (border+innerBorder+legendWidth),...
    currentAxisPos(2),...
    (1 -(2*border)- (2*innerBorder)-(2*legendWidth)),...
    currentAxisPos(4)];
set(axisH,'OuterPosition',newAxisPos);

% Set up east legend
eastLegendPos = [...
    ((2*innerBorder)+border+legendWidth+newAxisPos(3)),...
    lgEastPos(2),...
    legendWidth,...
    lgEastPos(4)];
lgEastH = legend(gca,symbolH(midPt+1:end),labelH(midPt+1:end),'Location','EastOutside');
set(lgEastH,'Position',eastLegendPos);

% Set up west legend
extraAxisH = axes('Position',get(gca,'Position'),'Visible','off');
lgWestH = legend(extraAxisH,symbolH(1:midPt),labelH(1:midPt),'Location','WestOutside');
lgWestPos = get(lgWestH,'Position');
westLegendPos = [...
    border,...
    lgWestPos(2),...
    legendWidth,...
    lgWestPos(4)];
set(lgWestH,'Position',westLegendPos)

axes(axisH);


function prtUtilClassStructurePlot(classNamesStrCell)
% prtUtilClassStructurePlot(classNamesStrCell);
%
% Mostly Ripped from viewClassTree() from MATLAB central by Matthew Dunham.
%
% View a class inheritence hierarchy. All classes residing in the directory
% or any subdirectory are discovered. Parents of these classes are also
% discovered as long as they are in the matlab search path.
% There are a few restrictions:
% (1) classes must be written using the new 2008a classdef syntax
% -This is no longer true-(2) classes must reside in their own @ directories.
% (3) requires the bioinformatics biograph class to display the tree.
% (4) works only on systems that support 'dir', i.e. windows.
%
%Written by Matthew Dunham

suppliedDir = false;
if nargin == 0
    directory = pwd;
    suppliedDir = true;
elseif ischar(classNamesStrCell)
    if isdir(classNamesStrCell)
        directory = classNamesStrCell;
        suppliedDir = true;
    else
        classNamesStrCell = {classNamesStrCell};
    end
else
    classNamesStrCell = {class(classNamesStrCell)};
    suppliedDir = false;
end

if suppliedDir
    %fileNames = what(directory);
    fileNames = prtUtilRecursiveWhat(directory);
    classNamesStrCell = cellfun(@(c)c(1:end-2), fileNames.m,'uniformOutput',false);
end

allClasses = classNamesStrCell;
for c=1:numel(classNamesStrCell)
    allClasses = union(allClasses,ancestors(classNamesStrCell{c}));
end
allClasses = unique(allClasses);

matrix = zeros(numel(allClasses));
map = struct;
for i=1:numel(allClasses)
    map.(allClasses{i}) = i;
end

keepClass = false(numel(allClasses),1);
for i=1:numel(allClasses)
    try
        m = eval(['?',allClasses{i}]);
        %m = meta(allClasses{i});
        parents = m.SuperClasses;
        if ~isempty(m)
            keepClass(i) = true;
        end
    catch ME %#ok
        warning('CLASSTREE:discoveryWarning',['Could not discover information about class ',allClasses{i}]);
        continue;
    end
    for j=1:numel(parents)
        matrix(map.(allClasses{i}),map.(parents{j}.Name)) = 1;
    end
end

matrix = matrix(keepClass,keepClass);
allClasses = allClasses(keepClass);

if isscalar(matrix)
    matrix = 1;
end

plotGraph(matrix, allClasses)

end

function info = dirinfo(directory)
%Recursively generate an array of structures holding information about each
%directory/subdirectory beginning, (and including) the initially specified
%parent directory.
info = what(directory);
flist = dir(directory);
dlist =  {flist([flist.isdir]).name};
for i=1:numel(dlist)
    dirname = dlist{i};
    if(~strcmp(dirname,'.') && ~strcmp(dirname,'..'))
        info = [info, dirinfo([directory,'\',dirname])]; %#ok
    end
end
end

function list = ancestors(className)
%Recursively generate a list of all of the superclasses, (and superclasses
%of superclasses, etc) of the specified class.
list = {};

try
    m = eval(['?',className]);
    parents = m.SuperclassList;
catch %#ok
    disp('error')
    return;
end

list = getAncestorsFromMeta(parents);

list = unique(list);

end

function list = getAncestorsFromMeta(m)
list = {};

for p = 1:numel(m)
    if(p > numel(m)),continue,end %bug fix for version 7.5.0 (2007b)
    list = cat(2, list, {m(p).Name}, getAncestorsFromMeta(m(p).SuperclassList));
end
end

function plotGraph(connectivity, nodeStrs)

% plotGraph a simple quick plot of the graph layout for validation.

% Call GraphViz to get a good layout - Call the MATLAB version
graphLayoutInfo = prtPlotUtilGraphVizRun(connectivity');

% Plot each node as a box with a string of it's actionId
nNodes = length(graphLayoutInfo.Nodes);
for iNode = 1:nNodes
    cN = graphLayoutInfo.Nodes(iNode);

    cNHandles.rect = rectangle('Position',[cN.x cN.y cN.w cN.h]);
    cNHandles.text = text(cN.x+cN.w/2,cN.y+cN.h/2, nodeStrs{iNode}, 'VerticalAlignment','Middle','HorizontalAlignment','Center','Interpreter','none');

    if iNode == 1
        nodeHandles = repmat(cNHandles,nNodes,1);
    else
        nodeHandles(iNode) = cNHandles;
    end
end

% Get the scale of the axes so we know how big to make arrow heads
v = axis;
scale = mean([v(2)-v(1),v(4)-v(3)]);

% Plot each edge
nEdges = length(graphLayoutInfo.Edges);
for iEdge = 1:nEdges
    cE = graphLayoutInfo.Edges(iEdge);

    cStartN = graphLayoutInfo.Nodes(cE.startIndex);
    cStopN = graphLayoutInfo.Nodes(cE.stopIndex);

    cArrowStart = cat(2,cStartN.x + cStartN.w/2, cStartN.y + cStartN.h);
    cArrowStop = cat(2,cStopN.x + cStopN.w/2, cStopN.y);

    cEHandles.arrow = prtPlotUtilPlotArrow(cat(1,cArrowStart(1),cArrowStop(1)), cat(1,cArrowStart(2),cArrowStop(2)), [],'headWidth',0.01*scale,'realHeadLength',0.01*scale);

    if iNode == 1
        edgeHandles = repmat(cEHandles,nEdges,1);
    else
        edgeHandles(iNode) = cEHandles;
    end
end

set(gca,'XTick',[],'YTick',[]);
end


function nameout = cleanvarname(namein)

% Routine to remove unallowed characters from strings
% nameout can be use as a variable or field in a structure

% custom change
if strcmp(namein,'#')
    namein = 'nb';
end

% 1st char must be a letter
for l=1:length(namein)
    if isletter(namein(l))
        nameout = namein(l:end);
        break % exist for loop
    end
end

% remove usual suspects
stringcheck = [strfind(namein,'('), ...
    strfind(namein,')') ...
    strfind(namein,'[') ...
    strfind(namein,']') ...
    strfind(namein,'{') ...
    strfind(namein,'}') ...
    strfind(namein,'-') ...
    strfind(namein,'+') ...
    strfind(namein,'*') ...
    strfind(namein,'/') ...
    strfind(namein,'#') ...
    strfind(namein,'%') ...
    strfind(namein,'&') ...
    strfind(namein,'@') ...
    ];

if ~isempty(stringcheck)
    nameout(stringcheck) = [];
end

% last check
if ~isvarname(nameout)
    error('the variable name to use is still invalid, check chars to remove')
end