clc
clear all
close all

global Defaults
Defaults=spm_get_defaults
spm_jobman('initcfg');

working_dir='C:\Users\Giuseppe\Desktop\per_matlab' 
scripts_dir='C:\Users\Giuseppe\Desktop\per_matlab\script'

%% list of subject folders
[files,dir]=spm_select('List',working_dir,'^00*');

for j=1:size(files,1)
    file_to_unzip{j}=files(j,:);
end
    
    for j=1:size(files,1)
    i=strfind(files(j,:),' ');
     if ~isempty(i)
         path_to_im{j,:}=[fullfile(working_dir,files(j,1:i-1)),',1']; 
     else
         path_to_im{j,:}=[fullfile(working_dir,files(j,:)),',1'];     
     end
end

%% segmentation with new_segment (default in spm12)
load(fullfile(scripts_dir,'segment.mat'));

matlabbatch{1}.spm.spatial.preproc.channel.vols=path_to_im;

save(fullfile(scripts_dir,'segment.mat'),'matlabbatch');

output_list= spm_jobman('run',matlabbatch);

%% create template with Dartel
load(fullfile(scripts_dir,'create_template.mat'));  %%cambia
gm=spm_select('List',working_dir,'^rc100*.*nii');
wm=spm_select('List',working_dir,'^rc200*.*nii');

for j=1:size(gm,1)
    i=strfind(gm(j,:),' ');
     if ~isempty(i)
         gm_files{j,:}=[fullfile(working_dir,gm(j,1:i-1)),',1']; 
         wm_files{j,:}=[fullfile(working_dir,wm(j,1:i-1)),',1']; 
     else
         gm_files{j,:}=[fullfile(working_dir,gm(j,:)),',1']; 
         wm_files{j,:}=[fullfile(working_dir,wm(j,:)),',1'];     
     end
end

matlabbatch{1}.spm.tools.dartel.warp.images{1}=gm_files;
matlabbatch{1}.spm.tools.dartel.warp.images{2}=wm_files;

save(fullfile(scripts_dir,'create_template.mat'),'matlabbatch');

output_list= spm_jobman('run',matlabbatch);

%% normalize all brains to MNI space using dartel template and flow fields (u_) from each subject RIPARTI DA QUI
load(fullfile(scripts_dir,'normalize_to_MNI.mat'));  %%cambia

% ricordati di spostare il template nella working directory
matlabbatch{1}.spm.tools.dartel.mni_norm.template{1}=fullfile(working_dir,'Template_6.nii'); %% cambia con il percorso in cui c'e il template di tutti

flow=spm_select('List',working_dir,'^u_rc*.*nii');
gm=spm_select('List',working_dir,'^c101*.*nii');
for j=1:size(flow,1)    
    i=strfind(flow(j,:),' ');    
    if ~isempty(i)
         flowfields{j,:}=fullfile(working_dir,flow(j,1:i-1)); 
    else
         flowfields{j,:}=fullfile(working_dir,flow(j,:)); 
    end
    i=strfind(gm(j,:),' ');    
    if ~isempty(i)
        images_gm{j,:}=fullfile(working_dir,gm(j,1:i-1)); 
    else
        images_gm{j,:}=fullfile(working_dir,gm(j,:)); 
    end   
end

matlabbatch{1}.spm.tools.dartel.mni_norm.data.subjs.flowfields=flowfields;
matlabbatch{1}.spm.tools.dartel.mni_norm.data.subjs.images{1}=images_gm;

matlabbatch{1}.spm.tools.dartel.mni_norm.fwhm=[6 6 6];

save(fullfile(scripts_dir,'normalize_to_MNI.mat'),'matlabbatch');

output_list= spm_jobman('run',matlabbatch);