%% set up Conn batch needed info and parameters through Excel sheet ruuning the whole analysis from preprocessing to
clear all;

%%%%%%%% user input starts (optional parameters can be defined in later
%%%%%%%% parts)
[num,txt,raw] = xlsread('/data/fmridata/xiaozhen/imagingscripttools/data_info_spm.xls'); 
data_info=cell2dataset(raw);
btw_sub_factor={'Group','Age','pcaloading','cluster','T_MI','T_BRI'}; % names must be the same as in the excel sheet; note Group should be always present even if just one group
project_folder='/data/fmridata/xiaozhen/imagingscripttools/Salienceproject';
roi_folder='/data/fmridata/xiaozhen/imagingscripttools/masks/Parcels/';  % here put all the rois image files with meaningful names that want to investigate, the script will load all ROIs automatically.
mask_folder='/data/fmridata/xiaozhen/imagingscripttools/masks/';
brain_mask=[fullfile(fileparts(which('spm')),'apriori','brainmask.nii')]; % set up aprior masks to search for (whole brain or specific structure)
greymask=[mask_folder  '/grey_mask_wfu.nii']; 
csfmask=[mask_folder  '/csf.nii'];% ventricle ROi of no interest   
whitemask=[mask_folder  '/white.nii'];  % white matter ROi of no interest    

conn_projectname='DCNL_SALSALBR_conn2session_spm.mat'; % names for the conn project;
nsessions=2;
preprocessing=0; % 1 if need to run preprocessing steps to get smoothed data
setup_done=1;
denoise_done=1;
tr=2;
smoothk =8; % smooth kernel
img_savedim=3;% voxel size to reslice the data
  
%%% if it's task data excel file should have a column pointing to their  condition file set up in SPM 
%or can specify here if onset, name, and duration etc are all the same across subjects.
%   onsets{ncondition}{nsub}{nses}=  %vector of condition onsets (in seconds)
% durations     : conditions.durations{ncondition}{nsub}{nses} vector of condition durations (in seconds)
task_flag=1; % put 0 if just pure resting state data then onset is 0, duration is inf
cond_names={'task_on','task_off'};  
for nsub=1:length(data_info.SubID)
    cond_onsets{1}{nsub}{1}=[10 30 50]; % first condition at 1 st session
    cond_onsets{1}{nsub}{2}=[10 30 50]; % first condition at 2nd session
    cond_onsets{2}{nsub}{1}=[10 30 50]; % 2nd condition at 1 st session
    cond_onsets{2}{nsub}{2}=[10 30 50]; % 2nd condition at 2nd session
    cond_durations{1}{nsub}{1}=[1 1 1]; % first condition at 1 st session
    cond_durations{1}{nsub}{2}=[1 1 1]; % first condition at 2nd session
    cond_durations{2}{nsub}{1}=[1 1 1]; % 2nd condition at 1 st session
    cond_durations{2}{nsub}{2}=[1 1 1]; % 2nd condition at 2nd session
end
      
% first level covariates: either art_regression_outliers_and_movement*.mat [1], art_regression_outliers [2] pure 6 motion rp*.txt [3]  
first_level_cov=1;
%%%%%%% user input ends

% under a new project folder
if ~exist(project_folder,'dir')
    mkdir(project_folder);
end
cwd=project_folder;
%% finds functional and structural files and copy them to the project folder/data/subject/ if not existing
subnames=data_info.SubID;
imgtype=data_info.imgtype;
prefix=data_info.prefix;
NSUBJECTS=length(data_info.SubID);
motion_cov={'art_regression_outliers_and_movement*.mat','art_regression_outliers*.mat','rp*.txt'};
sess_folder_all={{'SAL','SAL_BR'},{'SAL1/functional','SAL2_BR/functional'}};
clear FUNCTIONAL_FILE STRUCTURAL_FILE 
for sub_index=1:NSUBJECTS
    if isnumeric(subnames{sub_index})
        subnames{sub_index}=num2str(subnames{sub_index});
    end
    subname=subnames{sub_index};
    data_prefix=prefix{sub_index};
    data_imgtype=imgtype{sub_index};
    % get functional files
    for session_i=1:nsessions
        eval(['subfolder_i=data_info.Sessionfolder' num2str(session_i) '{sub_index};']);
        inputdir= [data_info.func_parent_dir{sub_index} '/' subname '/' subfolder_i '/'];
        spmfile_i=[inputdir 'SPM.mat'];
        load(spmfile_i,'SPM');
   for nses=1:length(SPM.Sess),
      for ncondition=1:length(SPM.Sess(nses).U),
         SPM.Sess(nses).U(ncondition).name{1}=[SPM.Sess(nses).U(ncondition).name{1}, sprintf('_Session%d',nses)];
      end
   end
          save(spmfile_i,'SPM');
          spmfiles{sub_index}{session_i}=[inputdir 'SPM.mat'];

        if strcmp(inputdir(1:4),'/fmr')
            sess_folder=sess_folder_all{2};
        else
                        sess_folder=sess_folder_all{1};

        end
        motion_file=dir([data_info.func_parent_dir{sub_index} '/' subname '/' sess_folder{session_i} '/' motion_cov{1}]);
        if length(motion_file)>1
            covariatefiles{1}{sub_index}{session_i}=[data_info.func_parent_dir{sub_index} '/' subname '/' sess_folder{session_i} '/' motion_file(2).name ];
        else
            covariatefiles{1}{sub_index}{session_i}=[data_info.func_parent_dir{sub_index} '/' subname '/' sess_folder{session_i} '/' motion_file(1).name ];
        end

    end
        % get structural
   

    
end

%% setup guide
%New                 PERFORMS DATA PREPROCESSING (realignment/slicetiming/coregistration/segmentation/normalization/smoothing) AND INITIALIZES conn_* PROJECT
clear batch;
batch.filename=fullfile(project_folder,conn_projectname);            % New conn_*.mat experiment name

%  end %note: each subject's data is defined by  sessions and one single (4d) file per session

    batch.Setup.isnew=1;%           : 1/0 is this a new conn project [0]
    batch.Setup.done=setup_done;%            : 1/0: 0 defines fields only; 1 performs processing steps [0]
    batch.Setup.overwrite=1;%       : 1/0 overwrites target files if they exist [1]
%     spmfiles        : Optionally, spmfiles{nsub} is a char array pointing to the 'SPM.mat' source file to extract Setup information from for each subject
    batch.Setup.nsubjects = NSUBJECTS; %     : Number of subjects
    batch.Setup.RT=tr; %              : Repetition time (seconds) [2]
    batch.Setup.acquisitiontype=1;%  : 1/0: Continuous acquisition of functional volumes [1] 
    batch.Setup.analyses=[1,2,3,4];%        : Vector of index to analysis types (1: ROI-to-ROI; 2: Seed-to-voxel; 3: Voxel-to-voxel); 4: Dynamic FC [1,2,3,4] 
    batch.Setup.voxelmask=1;%       : Analysis mask type (voxel-level analyses): 1: Explicit mask (brainmask.nii); 2: Implicit mask (subject-specific) [1] 
   % ++++ usual input needed

    batch.Setup.voxelmaskfile=brain_mask;%   : Explicit mask file (only when voxelmask=1) [fullfile(fileparts(which('spm')),'apriori','brainmask.nii')] 
    batch.Setup.voxelresolution=3;% : Voxel resolution (voxel-level analyses): 1: Volume-based template (SPM; default 2mm isotropic or same as explicit mask if specified); 2: Same as structurals; 3: Same as functionals; 4: Surface-based template (Freesurfer) [1] 
    batch.Setup.analysisunits=1; %   : BOLD signal units: 1: PSC units (percent signal change); 2: raw units [1] 
   % ++++ usual input needed
   batch.Setup.outputfiles=[0,0,0,0,0,0];%     : Optional output files (outputfiles(1): 1/0 creates confound beta-maps; outputfiles(2): 1/0 creates confound-corrected timeseries; outputfiles(3): 1/0 creates seed-to-voxel r-maps) ;outputfiles(4): 1/0 creates seed-to-voxel p-maps) ;outputfiles(5): 1/0 creates seed-to-voxel FDR-p-maps); outputfiles(6): 1/0 creates ROI-extraction REX files; [0,0,0,0,0,0] 
    batch.Setup.surfacesmoothing=50;%: Smoothing level for surface-based analyses (number of discrete diffusion steps) [50]
    batch.Setup.spmfiles= spmfiles;%     : functionals{nsub}{nses} char array of functional volume files (typically spatially smoothed BOLD signal volumes) 
%     batch.Setup.structurals= norm_structurals;%     : structurals{nsub} char array of structural volume files 
    batch.Setup.roiextract=1;%      : Source of functional data for ROI timeseries extraction (typically unsmoothed BOLD signal volumes); 1: same as 'functionals' field; 2: same as 'functionals' field after removing leading 's' from filename; 3: other (define rule programmatically; see help conn_rulebasedfilename); 4: other (different set of functional volume files) [2] 
%     batch.Setup.roiextract_rule : (for roiextract==3) regexprep(filename,roiextract_rule{2},roiextract_rule{3}) converts filenames in 'functionals' field (typically non-spatially smoothed BOLD signal volumes) to filenames that will be used when extracting BOLD signal ROI timeseries (if roiextract_rule{1}==2 filename is interpreted as a full path; if roiextract_rule{1}==1 filename is interpreted as only the file *name* -no file path, no file extension-)    
%     batch.Setup.roiextract_functionals: (for roiextract==4) roiextract_functionals{nsub}{nses} char array of functional volume files (typically non-spatially smoothed BOLD signal volumes) to be used when extracting BOLD signal ROI timeseries 
 
  % set up  masks

for nsub=1:NSUBJECTS
    batch.Setup.masks.CSF.files{nsub}=csfmask; % or set to standard roi 
    batch.Setup.masks.Grey.files{nsub}=greymask;
    batch.Setup.masks.White.files{nsub}=whitemask;

end    
  %: masks.Grey{nsub} char array of grey matter mask volume file [defaults to Grey mask extracted from structural volume] 
%       White         : masks.White{nsub} char array of white matter mask volume file [defaults to White mask extracted from structural volume] 
%       CSF           : masks.CSF{nsub} char array of CSF mask volume file [defaults to CSF mask extracted from structural volume] 
%                     : each of these fields can also be defined as a structure with fields files/dimensions/etc. fields (see 'Setup.rois' below).
batch.Setup.masks.Grey.dimensions=1;
batch.Setup.masks.CSF.dimensions=16; % 16 components (PCA decomposition) 
batch.Setup.masks.White.dimensions=16;

% other ROIs for analysis (if not set use all rois in conn/rois folder
batch.Setup.rois.files{1}={[fullfile(fileparts(which('conn')),'rois','Parcels_MNI_333.nii')]};
 batch.Setup.rois.names={'Parcel'};
% rois=dir([roi_folder '/*.nii']);
% for i=1:length(rois)
% batch.Setup.rois.names{i}=rois(i).name(1:end-4);%rois.names{nroi} char array of ROI name [defaults to ROI filename]
% batch.Setup.rois.dimensions{i}=1; %rois.dimensions{nroi} number of ROI dimensions - # temporal components to extract from ROI [1]
% batch.Setup.rois.files{i}=[roi_folder rois(i).name];%rois.files{nroi}{nsub} char array of roi file (or rois.files{nroi} char array of roi file, to use the same roi for all subjects)
% end
% batch.Setup.rois.mask=0;%whether to mask (1) or not (0) each ROI with gray-matter voxels (defaults to 0)
% batch.Setup.rois.regresscovariates=0;% regress (1) or not (0)covariates before PCA decomposition of ROI BOLD timecourses (only applies when Setup.rois.dimensions>1)
%       regresscovariates: rois.regresscovariates(nroi) 1/0 to regress known first-level covariates before computing PCA decomposition of BOLD signal within ROI [1 if dimensions>1; 0 otherwise] 

% batch.Setup.rois.roiextract=1;%whether to use the ROI-specific BOLD timeseries specified in the BATCH.Setup.roiextract field
% (1) or use the original functional BOLD timeseries specified in the BATCH.Setup.functionals field
% (0) when extracting ROI BOLD timecourses. (defaults to 1)


%      batch.Setup.conditions

% subjects' motion covariates

batch.Setup.covariates.names{1}='scrubbing'; % : covariates.names{ncovariate} char array of covariate name
batch.Setup.covariates.files= covariatefiles; %      : covariates.files{ncovariate}{nsub}{nses} char array of covariate file 
% names of temporal (first-level) covariates
% batch.Setup.covariates.names{2}={'sessions'};      
% % cell array of strings (one per covariate and subject and condition): batch.Setup.covariates.files{ncovariate}{nsub}{nses} is an array pointing the a file defining the covariate "ncoviarate" for subject "nsub" and sessions "nses" (note: valid files are .txt or .mat files and should contain as many rows as scans for each given subject/session)
% X=kron(eye(4),ones(90,1));save(fullfile(rootfolder,'sessions.mat'),'X');
% batch.Setup.covariates.files{2}{1}{1}=fullfile(rootfolder,'sessions.mat');
% 
 %%%    batch.Setup.subjects
 if length(btw_sub_factor)>1
 for neffect=2:length(btw_sub_factor)
      batch.Setup.subjects.effect_names{neffect-1}=btw_sub_factor{neffect}; %  : subjects.effect_names{neffect} char array of second-level effect name
      eval(['batch.Setup.subjects.effects{neffect-1}=data_info.' btw_sub_factor{neffect}]); % : subjects.effects{neffect} vector of size [nsubjects,1] defining second-level effects
 end
 end
 
[groupnames,IA,group_index] = unique(data_info.Group);
num_group=length(groupnames);
for gp_i=1:num_group
    batch.Setup.subjects.group_names{gp_i}=groupnames{gp_i};%       group_names  : subjects.group_names{ngroup} char array of second-level group name
    batch.Setup.subjects.groups=group_index;%       groups       : subjects.group vector of size [nsubjects,1] (with values from 1 to ngroup) defining second-level groups

end
conn_batch(batch);
conn
conn('load',batch.filename);
%  
%  
%   batch.Denoising       PERFORMS DENOISING STEPS (confound removal & filtering)
%  
    batch.Denoising.done=denoise_done; %            : 1/0: 0 defines fields only; 1 performs processing steps [0]
    batch.Denoising.overwrite=1; %       : 1/0: overwrites target files if they exist [1]
    batch.Denoising.filter=[.01, .1]; %          : vector with two elements specifying band pass filter: low-frequency & high-frequency cutoffs (Hz)
    batch.Denoising.detrending=1;%      : 0/1/2/3: BOLD times-series polynomial detrending order (0: no detrending; 1: linear detrending; ... 3: cubic detrending) 
    batch.Denoising.despiking=2; %       : 0/1/2: temporal despiking with a hyperbolic tangent squashing function (1:before regression; 2:after regression) [2] 
    batch.Denoising.regbp=2; %          : 1/2: order of band-pass filtering step (1 = RegBP: regression followed by band-pass; 2 = Simult: simultaneous regression&band-pass) [1] 
%     batch.Denoising.confounds.       : Cell array of confound names (alternatively see 'confounds.names' below
%     confounds       : alternatively confounds can be a structure with fields
      batch.Denoising.confounds.names={'White Matter','CSF','Effect of *'} ;%          : confounds.names{nconfound} char array of confound name (confound names can be: 'Grey Matter','White Matter','CSF',any ROI name, any covariate name, or 'Effect of *' where * represents any condition name])
    batch.Denoising.confounds.dimensions={1,1,1} ; %  : confounds.dimensions{nconfound} number of confound dimensions [defaults to using all dimensions available for each confound variable]
      batch.Denoising.confounds.deriv={0,0,0}   ;    %   : confounds.deriv{nconfound} numnber of derivatives for each dimension [0]
%  
%  
%   batch.Analysis.            PERFORMS FIRST-LEVEL ANALYSES (ROI-to-ROI and seed-to-voxel) 
%  
% %   batch.Analysis.            PERFORMS FIRST-LEVEL ANALYSES (ROI-to-ROI and seed-to-voxel) 
% %  
conn_batch(batch);
% 
% % clear batch;
% % batch.filename=fullfile(cwd,conn_projectname);            % New conn_*.mat experiment name
% 
    batch.Analysis.done=1;     %       : 1/0: 0 defines fields only; 1 performs processing steps [0]
    batch.Analysis.overwrite=0; %       : 1/0: overwrites target files if they exist [1] % overwrite existing results if they exist (set to 'No' if you want to skip Analysis steps for subjects/ROIs already analyzed)    
    batch.Analysis.analysis_number=1; % : sequential indexes identifying each set of independent analyses [1] 
    batch.Analysis.measure=1; %         : connectivity measure used, 1 = 'correlation (bivariate)', 2 = 'correlation (semipartial)', 3 = 'regression (bivariate)', 4 = 'regression (multivariate)'; [1] 
    batch.Analysis.weight=2; %          : within-condition weight, 1 = 'none', 2 = 'hrf', 3 = 'hanning'; [2] 
    batch.Analysis.modulation=0; %      : temporal modulation, 0 = standard weighted GLM analyses; 1 = PPI analyses of condition-specific temporal modulation factor, or a string for PPI analyses of other temporal modulation factor (same for all conditions; valid strings are ROI names and 1st-level covariate names)'; [0] 
    batch.Analysis.type=3; %            : analysis type, 1 = 'ROI-to-ROI', 2 = 'Seed-to-Voxel', 3 = 'all'; [3] 
   conn_batch(batch);
    
%          
%        
%     %     batch.Analysis.sources=1; %         : Cell array of sources names (seeds) (source names can be: any ROI name) (if this variable does not exist the toolbox will perform the analyses for all of the existing ROIs which are not defined as confounds in the Denoising step) 
%  
% %     sources         : alternatively sources can be a structure with fields
% %       names         : sources.names{nsource} char array of source names (seeds)
% %       dimensions    : sources.dimensions{nsource} number of source dimensions [1]
% %       deriv         : sources.deriv{nsource} number of derivatives for each dimension [0]
% %       fbands        : sources.fbands{nsource} number of frequency bands for each dimension [1]
% %  
% %  
% %   Analysis            PERFORMS FIRST-LEVEL ANALYSES (voxel-to-voxel) 
% %  
% %     done            : 1/0: 0 defines fields only; 1 performs processing steps [0]
% %     overwrite       : 1/0: overwrites target files if they exist [1]
    batch.Analysis.analysis_number=0;% : 0 (set this variable to 0 to identify voxel-to-voxel analyses) [0] 
%     batch.Analysis.measures=       % : Cell array of voxel-to-voxel measure names (type 'conn_v2v measures' for a list of default measures) (if this variable does not exist the toolbox will perform the analyses for all of the default voxel-to-voxel measures) 
%  
%     measures        : alternatively voxel-to-voxel measures can be a structure with fields
      batch.Analysis.measures.names={ 'connectome-MVPA', 'IntegratedLocalCorrelation', 'RadialCorrelationContrast', 'IntrinsicConnectivityContrast','RadalSimilarityContrast'}; %        : measures.names{nmeasure} char array of measure names 
      batch.Analysis.measures.type={2,1,1,1,1}; %          : measures.type{nmeasure} measure type (0:local measures; 1: global measures) [1]
      batch.Analysis.measures.kernelsupport={0,8,8,0,0}; %: measures.kernelsupport{nmeasure} local support (FWHM) of smoothing kernel [12]
      batch.Analysis.measures.kernelshape={1,1,1,1,1}; %  : measures.kernelshape{nmeasure} kernel type (0: gaussian; 1: gradient; 2: laplacian) [1]
      batch.Analysis.measures.dimensions={16,16,16,16,16}; %   : measures.dimensions{nmeasure} number of SVD dimensions to retain (dimensionality reduction) [16]
 conn_batch(batch);




conn_batch(batch);

%% CONN Display
% launches conn gui to explore results
conn
conn('load',batch.filename);
conn gui_results

 