%-----------------------------------------------------------------------
% Job configuration created by cfg_util (rev $Rev: 4252 $)
%-----------------------------------------------------------------------

function first_level_job(data_path,stat_dir,subjects,sessions,conditions,tParams,conOpt)
%% loop over subjects and session
for i = 1:numel(subjects)
    for j = 1:numel(sessions)
        
        % navigate to data_path
        matlabbatch{1}.cfg_basicio.cfg_cd.dir = cellstr(data_path);
        
        % directory where specified design matrix SPM.mat will be written
        dir = fullfile(data_path,subjects{i},'spm',sessions{j});
        
        % create parent directory (statistical) for the new stat folders to be created
        % first check if it exists. if so then skip mkdir
        type = exist(fullfile(data_path,subjects{i},'spm',stat_dir),'dir');
        if type ~= 7
            mkdir(fullfile(data_path,subjects{i},'spm'),stat_dir);
        end
        parent_dir = fullfile(data_path,subjects{i},'spm',stat_dir);
        
        % directory where SPM.mat will be written
        session_dir = fullfile(parent_dir,strcat(sessions{j}));         
        % check if session dir exists, if not create it
        type = exist(session_dir,'dir');
        if type ~= 7
            mkdir(parent_dir,strcat(sessions{j}));
        end       
        
        % specify session directory
        matlabbatch{2}.spm.stats.fmri_spec.dir = {session_dir};
        
        matlabbatch{2}.spm.stats.fmri_spec.timing.units = tParams.units;
        matlabbatch{2}.spm.stats.fmri_spec.timing.RT = tParams.TR;
        matlabbatch{2}.spm.stats.fmri_spec.timing.fmri_t = tParams.mic_res;
        matlabbatch{2}.spm.stats.fmri_spec.timing.fmri_t0 = tParams.mic_onset;
        
        % load functional data
        files = spm_select('FPList',fullfile(data_path,subjects{i},'spm',sessions{j}), '^sw.*\.img$');
        matlabbatch{2}.spm.stats.fmri_spec.sess.scans = cellstr(files);
        
        % assign condition name, onset, duration
        matlabbatch{2}.spm.stats.fmri_spec.sess.cond.name = conditions(j).name;
        matlabbatch{2}.spm.stats.fmri_spec.sess.cond.onset = conditions(j).onsets;
        matlabbatch{2}.spm.stats.fmri_spec.sess.cond.duration = conditions(j).durations;
        matlabbatch{2}.spm.stats.fmri_spec.sess.cond.tmod = 0;
        matlabbatch{2}.spm.stats.fmri_spec.sess.cond.pmod = struct('name', {}, 'param', {}, 'poly', {});
        matlabbatch{2}.spm.stats.fmri_spec.sess.multi = {''};
        matlabbatch{2}.spm.stats.fmri_spec.sess.regress = struct('name', {}, 'val', {});
        
        % load multiple regressors? if yes, then do it
        if strcmp(tParams.motion_regress,'yes')
            reg_file = spm_select('FPList', fullfile(data_path,subjects{i},'spm',sessions{j}), '^rp.*\.txt$');
        else
            reg_file = [];
        end
        matlabbatch{2}.spm.stats.fmri_spec.sess.multi_reg = {reg_file};
        
        matlabbatch{2}.spm.stats.fmri_spec.sess.hpf = 128;
        matlabbatch{2}.spm.stats.fmri_spec.fact = struct('name', {}, 'levels', {});
        matlabbatch{2}.spm.stats.fmri_spec.bases.hrf.derivs = [0 0];
        matlabbatch{2}.spm.stats.fmri_spec.volt = 1;
        matlabbatch{2}.spm.stats.fmri_spec.global = 'None';
        matlabbatch{2}.spm.stats.fmri_spec.mask = {''};
        matlabbatch{2}.spm.stats.fmri_spec.cvi = 'AR(1)';
        
        % Estimation
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1) = cfg_dep;
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).tname = 'Select SPM.mat';
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).tgt_spec{1}(1).name = 'filter';
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).tgt_spec{1}(1).value = 'mat';
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).tgt_spec{1}(2).name = 'strtype';
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).tgt_spec{1}(2).value = 'e';
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).sname = 'fMRI model specification: SPM.mat File';
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).src_exbranch = substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1});
        matlabbatch{3}.spm.stats.fmri_est.spmmat(1).src_output = substruct('.','spmmat');
        matlabbatch{3}.spm.stats.fmri_est.method.Classical = 1;
        
        % Compute contrasts
        matlabbatch{4}.spm.stats.con.spmmat(1) = cfg_dep;
        matlabbatch{4}.spm.stats.con.spmmat(1).tname = 'Select SPM.mat';
        matlabbatch{4}.spm.stats.con.spmmat(1).tgt_spec{1}(1).name = 'filter';
        matlabbatch{4}.spm.stats.con.spmmat(1).tgt_spec{1}(1).value = 'mat';
        matlabbatch{4}.spm.stats.con.spmmat(1).tgt_spec{1}(2).name = 'strtype';
        matlabbatch{4}.spm.stats.con.spmmat(1).tgt_spec{1}(2).value = 'e';
        matlabbatch{4}.spm.stats.con.spmmat(1).sname = 'Model estimation: SPM.mat File';
        matlabbatch{4}.spm.stats.con.spmmat(1).src_exbranch = substruct('.','val', '{}',{3}, '.','val', '{}',{1}, '.','val', '{}',{1});
        matlabbatch{4}.spm.stats.con.spmmat(1).src_output = substruct('.','spmmat');
        matlabbatch{4}.spm.stats.con.consess{1}.tcon.name = conditions(j).name;
        matlabbatch{4}.spm.stats.con.consess{1}.tcon.convec = conditions(1).vector;
        matlabbatch{4}.spm.stats.con.consess{1}.tcon.sessrep = 'none';
        matlabbatch{4}.spm.stats.con.delete = 0;
        
        % Print results
        matlabbatch{5}.spm.stats.results.spmmat(1) = cfg_dep;
        matlabbatch{5}.spm.stats.results.spmmat(1).tname = 'Select SPM.mat';
        matlabbatch{5}.spm.stats.results.spmmat(1).tgt_spec{1}(1).name = 'filter';
        matlabbatch{5}.spm.stats.results.spmmat(1).tgt_spec{1}(1).value = 'mat';
        matlabbatch{5}.spm.stats.results.spmmat(1).tgt_spec{1}(2).name = 'strtype';
        matlabbatch{5}.spm.stats.results.spmmat(1).tgt_spec{1}(2).value = 'e';
        matlabbatch{5}.spm.stats.results.spmmat(1).sname = 'Contrast Manager: SPM.mat File';
        matlabbatch{5}.spm.stats.results.spmmat(1).src_exbranch = substruct('.','val', '{}',{4}, '.','val', '{}',{1}, '.','val', '{}',{1});
        matlabbatch{5}.spm.stats.results.spmmat(1).src_output = substruct('.','spmmat');
        matlabbatch{5}.spm.stats.results.conspec.titlestr = '';
        % print all contrasts found in SPM.mat file by setting it to Inf
        matlabbatch{5}.spm.stats.results.conspec.contrasts = conOpt.whichCon;
        matlabbatch{5}.spm.stats.results.conspec.threshdesc = conOpt.threshType;
        matlabbatch{5}.spm.stats.results.conspec.thresh = conOpt.thresh;
        matlabbatch{5}.spm.stats.results.conspec.extent = conOpt.extent;
        matlabbatch{5}.spm.stats.results.conspec.mask = struct('contrasts', {}, 'thresh', {}, 'mtype', {});
        matlabbatch{5}.spm.stats.results.units = 1;
        matlabbatch{5}.spm.stats.results.print = true;
        
        % save mat file and run job
        batch_file_name = strcat('firstLev_batch_',sessions{j},'.mat');
        save(fullfile(data_path,subjects{i},'spm','statistical',batch_file_name),'matlabbatch');
        spm_jobman('serial', matlabbatch , '');
        clear matlabbatch

    end
end
