%% Prepare_data_in_different_formats for UNIVARIATE analyses in each subject

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 = 'behav_meg_2mod3v_prep'; % '2mod2vRAW' '% how are u organizing the data?
param.iterations = 5; % '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

% subject = [47 48 49 50 51 52 53 54 55 56  57 58 59 60 61 62]

subject = [47 48 49 50 51 52 53 55 56  57 58 59 60 61 62 63 64 65 66 67 68 69 70 71]

for isubj = subject
    %isubj = 47;
    
    
    % Define globals
    global G;
    G = [];
    % First load the data file
    G.data_file_name = ['dformat_s',num2str(isubj)];
    G.anal_file_name = [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 'MEG3_analysis' filesep 'AVE_MEG' filesep 'scripts'])); % general processing scripts in this exp.
    
    G.subjPath = [exp_main_path filesep 'MEG' filesep  'AVE_MEG3' 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/MEG3_scripts/'));
  

    G.file_output = [G.outputPath 'behav_meg_results' filesep];
    if ~exist(G.file_output,'dir')
        mkdir(G.file_output);
    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
%   
        disp(['No datasets for this participant, creating first analysis'])
        danalysis = [];
        do_analysis = 1;
        m = 1;

    
    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
      
        
        %selecte the type of analysis as a function of the design. Here you
        %could send the job to the cluster
        if strcmp(param.design,'behav_meg_2mod3v_prep')
            %behav_meg_2mod3v_prep(fun_cfg)
            qsubfeval( ...
                'behav_meg_2mod3v_prep', ...
                fun_cfg, ...
                'memreq', 10*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 180*60, ...
                'timoverhead', 0);
        end
        
  
     
        
    end
end





% Plot AVERAGE data


figure('Name',['Subj n ' num2str(isubj)  ],'NumberTitle','off')
isubplot = 1;
for imod = [1: length(modalities)]
    for ivfield = [1: length(visualfields)]
        cfg = [];
        cfg.channel = {'MLO*','MZO*','MRO*'}; %'MEG'; {'MLO*','MZO*','MRO*'}
        cfg.baseline = [-0.2, 0];
        cfg.linewidth  = 1;
        cfg.parameter = 'avg';
        % cfg.linestyle = {'-','-'};
        cfg.graphcolor    =  [0 0 0;0.0 0.6 0.9]; % 'wkywrgbkywrgbkywrgbkyw'
        cfg.linewidth = [2.0];
        %  cfg.ylim = [-6e-14,14e-14]
        cfg.xlim = [-0.2,1.5];
        cfg.layout = 'CTF275_helmet.lay';
        % plot signal versus noise in each plo
        
        subplot(2, 2, isubplot); ft_singleplotER(cfg,avg_pg_cmb.cond(1).modals(imod).vfields(ivfield).participant, avg_pg_cmb.cond(2).modals(imod).vfields(ivfield).participant);
        
        %legend(['Modalities = ',modalities(imod), ' Visualfield = ',visualfields(ivfield), ' noise & signal']);
        title([char(modalities(imod)),' ' char(visualfields(ivfield))]);
        legend(['noise'],['signal']);
        
        isubplot = isubplot + 1;
    end
end



cfg = [];
cfg.channel = {'MLO*','MZO*','MRO*'}; %'MEG'; {'MLO*','MZO*','MRO*'}
cfg.baseline = [-0.2, 0];
cfg.linewidth  = 1;
%  cfg.ylim = [-6e-14,14e-14]
cfg.layout = 'CTF275_helmet.lay';
% plot signal versus noise in each plo

ft_singleplotER(cfg,avg_pg_cmb.cond(1).modals(imod).vfields(ivfield).participant)



now for the rest of the analyses, create a struct call
analyses.data.format
analyses.data.univariate(1).param.type = SDT, raw
analyses.data.multivariate(1).param.type


if exist('dformat','var')
    load([G.outputPath 'data_preproc_clean_',num2str(30),'Hz_filter_downsampled.mat'])
else
    dformat = [];
    save([G.outputPath 'data_preproc_clean_',num2str(30),'Hz_filter_downsampled'],'data','-v7.3')
end




cfg = [];
cfg.channel = {'MEG', 'UADC007'};
% cfg.channel = [cfg.channel, {'-MLF12', '-MLF14', '-MLF25', '-MLT31'}];
data = ft_selectdata(cfg, data);
