% change the root dir in the volume pathnames in SPM.mat and SPMcfg.mat 
% works with both SPM99 and SPM2 result files
% input (from GUI): subject results dir
% by Dara Ghahremani (dara@psych.stanford.edu) - 11/01/03

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % get subject res dir
    dirs = spm_get(-Inf, '.img', 'Select subject results dir');
    dirs = cellstr(dirs);
    dirs = deblank(dirs);
    for i = 1:length(dirs)
        [dummy_dir, dummy_file, dummy_ext] = fileparts(dirs{i});
        if (strcmp(dummy_ext,'.') | strcmp(dummy_ext,'')) & isempty(dummy_file)
            % we've selected a directory from within it, and
            % hence subj_name ends in /.  So let's strip it
            dirs{i} = dummy_dir;
        end
    end


subjects=dirs;
cwd=pwd;
%-----------------------------------------------------------------------
%-GUI setup
%-----------------------------------------------------------------------
[Finter,Fgraph,CmdLine] = spm('FnUIsetup','Change Volume Path Info',0);
spm_help('!ContextHelp',mfilename)

SPMversion=spm_input('Which version of SPM?',1,'SPM99|SPM2',[99 2]);

for subj=1:length(subjects),

   subjdir = subjects{subj};

   cd(subjdir)

   if exist('SPM.mat'),
	load SPM.mat       
       cd(subjdir)
   elseif SPMversion==99 & exist('SPMcfg.mat')
	load SPMcfg.mat               
   else
        error('No SPM.mat or SPMcfg.mat file exists in this dir');
   end

   % temporarily give assign SPM2 var name (SPM.xY.VY) to SPM99 name (VY)
   if SPMversion==2, VY=SPM.xY.VY; end

   %% search for differing path names in VY
   VYpaths={};	% differing paths
   VYpathsIndex=[];   % index of these paths in VY
   for i=1:length(VY),
     [filepath,name,ext]=fileparts(VY(i).fname);
      filepath=fullfile(filepath,name(1:length(name)-3));
     if i==1,
	VYpaths{1}=filepath;
	VYpathsIndex(1)=1;
     elseif ~isequal(VYpaths{[length(VYpaths)]},filepath),
	VYpaths{[length(VYpaths)+1]}=filepath;
   	VYpathsIndex(length(VYpathsIndex)+1)=i;
     end
   end

   fprintf('\nNumber of paths found in this file: %d\n',length(VYpaths));

   %% collect replacement paths   
   pathToChange={};
   newDataPath={};
   for path=1:length(VYpaths),

       fprintf('\n');
       oldDataPath=VYpaths{path};
       fprintf('Enter which part of the following path you would like to change:\n%s\n',oldDataPath);
       pathToChange{path}=input('--> ','s');
       fprintf('Enter replacement path:\n');
       newDataPath{path}=input('--> ','s');

       if ~isempty(findstr(pathToChange{path},VY(VYpathsIndex(path)).fname)),
        if ~isequal(path,length(VYpaths)),
           for i=VYpathsIndex(path):VYpathsIndex(path+1)-1,
	       newFilePath=strrep(VY(i).fname,pathToChange{path},newDataPath{path});
               if exist(newFilePath),
                  VY(i).fname=newFilePath;
	          fprintf('%s\n',newFilePath);
               else
	          error(['\nFile does not exist: ' newFilePath]);
               end              
           end
        elseif path==length(VYpaths),
           for i=VYpathsIndex(path):length(VY),
	       newFilePath=strrep(VY(i).fname,pathToChange{path},newDataPath{path});
               if exist(newFilePath),
                  VY(i).fname=newFilePath;
	          fprintf('%s\n',newFilePath);
               else
	          error(['File does not exist: ' newFilePath]);
               end              
           end
        end

       else
	error(['\nCould not find the string: ' newDataPath ' in ' pathToChange]);
       end

   end  

   fprintf('\n');
   clear P;
   filesSaved=[];
   saveSwitch=input('To save these changes type y: ','s');
   if saveSwitch=='y',
	if SPMversion==2,
	   SPM.xY.VY=VY;
           for i=1:length(SPM.xY.VY),
               P(i,:)=getfield(SPM.xY.VY(i),'fname');
           end
	   SPM.xY.P=P;
	   save SPM SPM
           filesSaved='SPM.mat';
	elseif SPMversion==99,
	   if exist('SPM.mat'), 
		save SPM VY -append
                filesSaved='SPM.mat';
           end
	   save SPMcfg VY -append	
           filesSaved=[filesSaved ' and SPMcfg.mat'];
	end
   	fprintf('\nPath names changed in %s in: \n%s\n',filesSaved,subjects{subj});
   end

end    




