%% 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 = '2mod3vRAW'; % '2half2mod2vRAW''2cond2mod1vRAW' '2mod2vRAW' 'mod2vBehavCor' %2vRAW''2block2mod2vRAW','2mod2vRAW' '2mod2vBehavCor' %; '2blocksSDT';  % '2mod2v '2blocks2mod2v'; '2blocksSDT'  '2mod2v'% how are u organizing the data?
%param.design = '3vRAW'; % '2half2mod2vRAW''2cond2mod1vRAW' '2mod2vRAW' 'mod2vBehavCor' %2vRAW''2block2mod2vRAW','2mod2vRAW' '2mod2vBehavCor' %; '2blocksSDT';  % '2mod2v '2blocks2mod2v'; '2blocksSDT'  '2mod2v'% how are u organizing the data?
%param.design = '3vRAW_CV'; % '2half2mod2vRAW''2cond2mod1vRAW' '2mod2vRAW' 'mod2vBehavCor' %2vRAW''2block2mod2vRAW','2mod2vRAW' '2mod2vBehavCor' %; '2blocksSDT';  % '2mod2v '2blocks2mod2v'; '2blocksSDT'  '2mod2v'% how are u organizing the data?
param.design = '2mod3vRAW_CV';
param.design = 'univ3_fullpipeline_CV';

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
% 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 =  [47 48 49 50 51 52 53 55 56  57 58 59 60 61 62 63 64 65 66 67 68 69 70 71]; % 47 48 49 50

for isubj = subject
    %isubj = 65;
    
    
    % Define globals
    global G;
    G = [];
    % First load the data file
    G.data_file_name = ['dformat_s',num2str(isubj)];
    
    G.anal_file_name = ['uni_',param.design,'_',param.trials_sel,'_s',num2str(isubj)];
    
    %    G.data_file_name = ['dformat_spilot031'];
    %    G.anal_file_name = ['uni_',param.design,'_',param.trials_sel,'_spilot031'];
    %% General paths
    
    
    exp_main_path = '/project/3018029.06';
    
    SUBJS = {['0',num2str(isubj)]}
    curSubj = SUBJS{1}
    % curSubj = 'pilot031'
    
    
    addpath(genpath( [exp_main_path filesep 'Matlab' filesep 'MEG3_scripts'])); % general processing scripts in this exp.
    
    G.subjPath = [exp_main_path filesep 'MEG' filesep 'AVE_MEG3' filesep curSubj filesep]; % main subject folder
    G.outputPath = [G.subjPath ,'func', filesep]; % subject saving artifact and preprocessing matrixes
    G.cfgbehavPath = [exp_main_path filesep 'Behavioral' filesep 'AVE_MEG3' filesep curSubj filesep] ; % behavioral data of participant
    
    subjscriptsPath = [G.subjPath ,'analysis', filesep]; %  participant specific scripts
    
    
    G.file_output = [G.outputPath 'univ_results' filesep];
    if ~exist(G.file_output,'dir')
        mkdir(G.file_output);
    end
    
    
    %% deleting useless files
    %     files = dir(fullfile( G.outputPath, 'subj*.mat'))univ_2v_prep
    %     for K = 1 : length( files )
    %         thisfile = fullfile(G.outputPath, files(K).name);
    %         delete(thisfile);
    %     end
    %
    %     files = dir(fullfile( G.outputPath, '_*.mat'))
    %         for K = 1 : length( files )
    %         thisfile = fullfile(G.outputPath, files(K).name);
    %         delete(thisfile);
    %     end
    %
    %    files = dir(fullfile( G.outputPath, 'uni*.mat'))
    %        for K = 1 : length( files )
    %         thisfile = fuluniv_2half2mod2v_preplfile(G.outputPath, files(K).name);
    %         delete(thisfile);
    %     end
    
    % initializing some flags
    do_analysis = 0;
    m = 0;
    n = 0;
    
    n = 1;
    
    %% 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')
        disp(['the output file already exist'])
    end
    
    disp(['No datasets for this participant, creating first analysis'])
    danalysis = [];
    do_analysis = 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
        fun_cfg.isubj = isubj;
        
        
        if strcmp(param.design,'3vRAW')
            % univ3_3v_prep(fun_cfg)
            qsubfeval( ...
                'univ3_3v_prep', ...
                fun_cfg, ...
                'memreq', 3*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 20*60, ...
                'timoverhead', 0);
        end
        
        
        if strcmp(param.design,'2mod3vRAW')
            % univ3_2mod3v_prep(fun_cfg)
            qsubfeval( ...
                'univ3_2mod3v_prep', ...
                fun_cfg, ...
                'memreq', 4*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 40*60, ...
                'timoverhead', 0);
        end
        
        
        if strcmp(param.design,'3vRAW_CV')
            % univ3_3v_CV_prep(fun_cfg)
            qsubfeval( ...
                'univ3_3v_CV_prep', ...
                fun_cfg, ...
                'memreq', 3*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 20*60, ...
                'timoverhead', 0);
        end
        
           
        if strcmp(param.design,'2mod3vRAW_CV')
            % univ3_cv_2mod3v_prep(fun_cfg)
            qsubfeval( ...
                'univ3_cv_2mod3v_prep', ...
                fun_cfg, ...
                'memreq', 7*1024^3, ...  % 3 gbytes
                'memoverhead', 0, ...
                'timreq', 80*60, ...
                'timoverhead', 0);
        end
        
        
         if strcmp(param.design,'univ3_fullpipeline_CV')
            univ3_fullpipeline_CV_prep(fun_cfg)
%              qsubfeval( ...
%                 'univ3_fullpipeline_CV_prep', ...
%                 fun_cfg, ...
%                 'memreq', 6*1024^3, ...  % 3 gbytes
%                 'memoverhead', 0, ...
%                 'timreq', 1400*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);
