
% ===========================================================================
% modifySPMcfg.m
% --------------
% This script modifies the SPMcfg.mat file as follows: 
% If the current image files contained in the SPMcfg.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 SPMcfg.mat, replacing the earlier broken paths.
%                           Pavithra Srinivasan, 15th August, 2002, Thursday.
% ===========================================================================

curr_cfg = spm_get(1,'SPMcfg.mat','Choose SPMcfg 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 SPMcfg.mat''s image file settings....');
for i = 1 : size(VY, 1)
    if ~exist( 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 SPMcfg.mat']);
    image_filenames = image_files{1};
    for i = 1 : size(image_filenames, 1) % number of functional images selected.
        VY = setfield(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 SPMcfg.mat file has been modified with the new paths and saved to disk.');
end
clear cache_cfg;


%-------------------------------------------------------------------------
% very inefficient now, to be modified later.....

curr_spmfile = spm_get(1,'SPM.mat','Choose SPM File');
load(curr_spmfile);
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(VY, 1)
    if ~exist( 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 SPM.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.
        VY = setfield(VY, {i}, 'fname', deblank(image_filenames(i, :)));
    end
    cache_spmfile = curr_spmfile;
    clear curr_spmfile;
    save(cache_spmfile); % saving the modified SPM.mat file.
    disp('The SPM.mat file has been modified with the new paths and saved to disk.');
end
clear cache_spmfile;
clear image_filenames;
clear image_files;
