clear;clc;

cd /home/subhadip/Autism_AnatNet/other_subjects

subjdir=dir('H*');

maindir='/home/subhadip/Autism_AnatNet/other_subjects/';



for l=1:length(subjdir)
 
setenv('FSLOUTPUTTYPE','NIFTI_GZ');
  
datafiles=strcat(maindir,subjdir(l).name,'/data*.nii.gz');

tempfiles=dir(datafiles)

    
 inputfile1= strcat(maindir,subjdir(l).name,'/',tempfiles(1).name);
 inputfile2= strcat(maindir,subjdir(l).name,'/',tempfiles(2).name);
 inputfile3= strcat(maindir,subjdir(l).name,'/',tempfiles(3).name);
% outputfile= strcat(maindir,subjdir(l).name,'/','eddycorrected_',tempfiles(m).name);

[status currdir] = system([' fslmaths ' inputfile1 ' -add ' inputfile2 ' -add ' inputfile3  ' added.nii.gz ' ]);
[status currdir] = system([' fslmaths  added.nii.gz  -div 3  data.nii.gz '   ]);

destination_path=strcat(maindir,subjdir(l).name,'/');
movefile('data.nii.gz',destination_path);

[status currdir] = system([' rm added.nii.gz '   ]);
[status currdir] = system([' rm data.nii.gz '   ]);

b0file=strcat(maindir,subjdir(l).name,'/b0.nii.gz');
[status currdir] = system([' bet ' b0file  ' nodif_brain.nii.gz  -n -m  -f  0.45 '    ]);
movefile('nodif_brain_mask.nii.gz',destination_path);

setenv('FSLOUTPUTTYPE','NIFTI');
[status currdir] = system([' bet ' b0file  ' nodif_brain.nii.gz  -n -m  -f  0.45 '    ]);

chk=load_untouch_nii('nodif_brain_mask.nii');

newfilename=strcat('nodif_brain_mask_',subjdir(l).name);
save_untouch_nii(chk, newfilename);

[status currdir] = system([' rm nodif_brain_mask.nii ' ]);

[status currdir] = system([' fslchfiletype NIFTI_GZ  ' newfilename ]);

[status currdir] = system([' cp bvals bvecs ' destination_path  ]);
% newfile=load_untouch_nii('chk.nii');
% strrep('chk.nii','chk',)



end