
% ===========================================================================
% modifySPM2.m
% --------------
% This script modifies the SPM.mat file as follows: 
% If the current image files contained in the SPM.mat file are not
% accessible due to broken or invalid paths, then the user is prompted 
% to provide the path for all the image files and this new path is saved in
% the SPM.mat, replacing the earlier broken paths.
%                           Sue Whitfield   9/1/03
% ===========================================================================

curr_cfg = spm_get(1,'SPM.mat','Choose SPM.mat File');
load(curr_cfg);
valid = 1; % setting flag.

% Testing to see if the image filenames contained in SPMcfg.mat
% have a valid path and are accessible:
disp('Detecting SPM.mat''s image file settings....');
for i = 1 : size(SPM.xY.VY, 1)
    if ~exist( SPM.xY.VY(i).fname, 'file')
        disp('Image file paths are broken. Please enter new path.');
        valid = 0;
        break;
    end
end


if valid
    disp('All image-file paths are valid.');
else
    % User specifies the new/valid path of the *.img scans that make up the above SPMcfg.mat:
    image_files{1} = spm_get(Inf,'.img',...
				     ['Select scans, to modify SPM.mat']);
    image_filenames = image_files{1};
    for i = 1 : size(image_filenames, 1) % number of functional images selected.
        SPM.xY.VY = setfield(SPM.xY.VY, {i}, 'fname', deblank(image_filenames(i, :)));
    end
    cache_cfg = curr_cfg;
    clear curr_cfg;
    save(cache_cfg); % saving the modified SPMcfg.mat file.
    disp('The SPM.mat file has been modified with the new paths and saved to disk.');
end
clear cache_cfg;
clear image_filenames;
clear image_files;


