%% Function used to launch multivariate analyses in each subject at the cluster


clear
%
overwrite = 1;

%% Select your parameters to select the data where you want to perform the analysis

format.baseline = [-0.2 0];
format.lpfreq = 30;
%format.hpfreq = 2;
format.resamplefs = 200;
format.detrend = 'no';
format.trigger_ref = 'target'; % what is the trigger used as a reference

%% Select your parameters to identify the analysis that you want to perform. Change everytime accordingly


param.trials_sel = 'all' %? correct/all % {'MEG'} what trials go in the analysis?
param.channels_sel = {'allchan'}; %{'MEG', 'UADC007'} ; % all, {'MLO*','MRO*','MZO*'}  % {'MEG', 'UADC007'} what channels go in the analyses ,'UADC007'
param.design = '2mod2vRAW'; %'2mod2vRAW_permatrix'; 'TG_2mod2vRAW' '2mod2vRAW''% how are u organizing the data?
param.iterations = 10; % 'auto', 5 10 iterations if you have very few data in one condition %3 6% n times that you have to iterate to use all the data in the analysis
% 10 11 12 13 14 15 16 17 19 20 21 22 23 24 25 26 27 28 29 30 31 32 34 35
subject = [10 11 12 13 14 15 16 17 19 20 21 22 23 24 25 26 27 28 29 30 31 32 34 35 ]
param.time = [-0.1, 1.5]; 

for isubj = subject
    %isubj = 10;
    
    
    % Define globals
    global G;
    G = [];
    % First load the data file
    G.data_file_name = ['dformat_s',num2str(isubj)];
    G.anal_file_name = ['decode_',param.design,'_',param.trials_sel,'_s',num2str(isubj)];
    
    %% General paths
    exp_main_path = '/project/3018029.06';
    
    SUBJS = {['0',num2str(isubj)]}
    curSubj = SUBJS{1}
    
    addpath(genpath( [exp_main_path , filesep 'MEG_analysis' filesep 'AVE_MEG' filesep 'scripts'])); % general processing scripts in this exp.
    
    G.subjPath = [exp_main_path filesep 'MEG' filesep curSubj filesep]; % main subject folder
    G.dataPath = [exp_main_path filesep 'raw', filesep 'sub-' curSubj  filesep]; % subjecf MEG data
    G.outputPath = [G.subjPath ,'func', filesep]; % subject saving artifact and preprocessing matrixes
    G.cfgbehavPath = [exp_main_path filesep 'Behavioral' filesep curSubj filesep] ; % behavioral data of participant
    
    subjscriptsPath = [G.subjPath ,'analysis', filesep]; %  participant specific scripts
    
    addpath(genpath('/project/3018029.06/Matlab/MEG_scripts/'));
  

    G.file_output = [G.outputPath 'multiv_results' filesep];
    if ~exist(G.file_output,'dir')
        mkdir(G.file_output);
    end
    
    
%     G.file_output = [G.outputPath 'multivariate' filesep];
%     if exist(G.file_output,'dir')
%          rmdir(G.file_output, 's')
%        
%     end
%     

%% deleting useless files     
% 
% % 
%      files = dir([G.outputPath 'multiv_results' filesep 'decode_*.mat'])
%          for K = 1 : length( files )
%          thisfile = fullfile([G.outputPath 'multiv_results'], files(K).name);
%          delete(thisfile);
%      end
% 
%    files = dir(fullfile( G.outputPath, 'uni*.mat'))
%        for K = 1 : length( files )
%         thisfile = fullfile(G.outputPath, files(K).name);
%         delete(thisfile);
%     end
   
    % initializing some flags
    do_analysis = 0;
    m = 0;
    n = 0;
    
    % Checking whether the selected data exist or not...
    
    
    if exist([G.outputPath G.data_file_name,'.mat'],'file')
        load([G.outputPath G.data_file_name,'.mat']);
        % file exist; checking whether the analyses is new...
        
        number_of_datasets = size(dformat,1);
        disp(['there are ' num2str(number_of_datasets) ' datasets in this participant file'])
        
        for i = 1 : number_of_datasets % lets find where are the data that we want to perform the analysis
            data_exist = 0;
            
            if strcmp(num2str(dformat(i).format.baseline), num2str(format.baseline)) & ...
                    strcmp(num2str(dformat(i).format.lpfreq) ,num2str(format.lpfreq)) & ...
                    strcmp(num2str(dformat(i).format.resamplefs) ,num2str(format.resamplefs)) & ...
                    strcmp(num2str(dformat(i).format.detrend) ,num2str(format.detrend)) & ...
                    strcmp(num2str(dformat(i).format.trigger_ref) ,num2str(format.trigger_ref));  data_exist = 1; end;
            
            if (data_exist > 0); n = i;
                disp(['the dataset is in field number ' num2str(n),' now preparing to validate the analysis type  ' ]); end; % overwrite in case that this is the dataset repeated
            if (i == number_of_datasets & data_exist == 0); error('This particular data preproc doesnt exist for this participant...'); end; % if we did not find this analyses already performed, save data in the next folder.
        end
        
    else
        error(['No datasets for this participant. You need to create the datase using prep_data_format function'])
        
    end
    
    %% If you want to delete the analysis file and start over again.
    %  if exist([G.outputPath anal_file_name,'.mat'],'file')
    %      delete([G.outputPath anal_file_name,'.mat']);
    %  end
    
    
    
    %% Checking whether the selected analysis is new or not and generating flags to save it...
    if exist([G.file_output G.anal_file_name,'.mat'],'file')
        load([G.file_output G.anal_file_name,'.mat']);
        % file exist; checking whether the analyses is new...
        
        number_of_datasets = size(dformat,1);
        disp(['there are ' num2str(number_of_datasets) ' datasets in this participant file'])
        
        %  isequal(multivariate(i).format, format) isequal(multivariate(i).param, param) %% YOU can also use this but
        %  careful if you want to ignore one argument
        for i = 1 : number_of_datasets % lets evaluate whether if we have performed this data transformation for this subject before+
            data_exist = 0
            % has this format been used before
            if strcmp(num2str(multivariate(i).format.baseline), num2str(format.baseline)) & ...
                    strcmp(num2str(multivariate(i).format.lpfreq) ,num2str(format.lpfreq)) & ...
                    strcmp(num2str(multivariate(i).format.resamplefs) ,num2str(format.resamplefs)) & ...
                    strcmp(num2str(multivariate(i).format.detrend) ,num2str(format.detrend)) & ...
                    strcmp(num2str(multivariate(i).format.trigger_ref) ,num2str(format.trigger_ref)) & ...  % has this analyses been performed before
                    strcmp(num2str(multivariate(i).param.trials_sel) ,num2str(param.trials_sel)) & ... %strcmp((multivariate(i).param.channels_sel) ,(param.channels_sel)) & ...
                    strcmp(num2str(multivariate(i).param.design) ,num2str(param.design)); data_exist = 1; end;
            % not, evaluate the previous results
            if (data_exist > 0 & overwrite == 0) ; error(['this analysis have been already performed this way in dataset number: ' num2str(i)]); break; end;
            if (data_exist > 0 & overwrite == 1); do_analysis = 1; m = i;  end; % overwrite in case that this is the dataset repeated
            if (i == number_of_datasets & data_exist == 0); do_analysis = 1;
                m = i + 1; end; % if we did not find this analyses already performed, save data in the next folder.
        end
        
    else
        disp(['No datasets for this participant, creating first analysis'])
        danalysis = [];
        do_analysis = 1;
        m = 1;
    end
    
    
    if do_analysis % GO!
        % analysis parameter saved here for sending funcion to the cluster.
        fun_cfg = [];
        %fun_cfg.dformat = dformat;
        fun_cfg.G = G;
        fun_cfg.n = n;
        fun_cfg.m = m;
        fun_cfg.param = param;
        fun_cfg.format = format
        %fun_cfg.multivariate = multivariate;
        

        %selecte the type of analysis as a function of the design. Here you
        %could send the job to the cluster
        if strcmp(param.design,'2mod2vRAW')
            %multiv_2mod2v_prep(fun_cfg)
            qsubfeval( ...
                'multiv_2mod2v_prep', ...
                fun_cfg, ...
                'memreq', 5*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 30*60, ...
                'timoverhead', 0);
        end
                %selecte the type of analysis as a function of the design. Here you
        %could send the job to the cluster
        if strcmp(param.design,'TG_2mod2vRAW')
            %TGmultiv_2mod2v_prep(fun_cfg)
            qsubfeval( ...
                'TGmultiv_2mod2v_prep', ...
                fun_cfg, ...
                'memreq', 8*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 60*60, ...
                'timoverhead', 0);
        end
        
           if strcmp(param.design, '2mod2vRAW_permatrix')
            %multiv_2mod2v_perm_matrix_prep(fun_cfg)
             qsubfeval( ...
                 'multiv_2mod2v_perm_matrix_prep', ...
                 fun_cfg, ...
                 'memreq', 30*1024^3, ...  % 3 gbytes
                 'memoverhead', 0, ...
                 'timreq', 35*60*60, ... % 2*4*3
                 'timoverhead', 0);
            
              %  multiv_2mod2v_prep(fun_cfg)
              
        end
        
        
       
        if strcmp(param.design,'2vRAW')
           % univ_2v_prep(fun_cfg)
             qsubfeval( ...
                'univ_2v_prep', ...
                fun_cfg, ...
                'memreq', 4*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 50*60, ...
                'timoverhead', 0);
        end         
    end
end


