%% DICOM Import script 
%  This script converts DICOM files into nifti Files using SPMs DICOM
%  Import sequence. It follows a particular directory structure which must
%  be adhered to.
%
% Glad Mihai, University of Greifswald, Jan. 2012

%% Clear variables and command window
clear all, clc

%% Specify paths
%  Experiment folder
data_path = '/media/System/Glad/Matlab Kurs';

%  Subject folders
subjects = {
            'subject1',...
            'subject2'
            };
%  Sequence folders
sequences = {
            '01_gre_field_34_2x_betrag',...
            '02_gre_field_34_2x_phase',...
            'jaw',...
            'wasser',...
            't1vol'
            };

%%  Initialise SPM defaults
spm('defaults', 'FMRI');
spm_jobman('initcfg');

%% Loop to load data from folders and run the job
for i = 1:numel(subjects)
    
    % load raw data for each sequence without a prompt
    for j = 1:numel(sequences)
        raw = cellstr(spm_select('FPList',fullfile(data_path,...
            subjects{i},'raw',sequences{j}),'^I\w*'));
        outdir = cellstr(fullfile(data_path,subjects{i},...
            'spm',sequences{j}));
        
        % display which subject and sequence is being processed
        fprintf('Preprocessing subject "%s", "%s" (%s files)\n',...
            subjects{i},sequences{j},sprintf('%d',size(raw,1)));
        
        % set up SPM-readable structure array
        matlabbatch = dicom_import_job(raw,outdir);
        %% SAVE AND RUN JOB
        %----------------------------------------------------------------------
        save(fullfile(data_path,subjects{i},'raw',sequences{i},'dicom_import.mat')...
            ,'matlabbatch');
        spm_jobman('serial', matlabbatch, '' );
    end
end

