function [NewFileMat,Path,NFiles]=RenameFilesInDir(Path,OldStr,NewStr);

%   RenameFilesInDir

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION. 

if nargin<3; NewStr=[]; end
if nargin<2; OldStr=[]; end
if nargin<1; Path=[]; end

% Path='Tim:Data:EEG:Bologna:01:'
% OldStr='0123'
% NewStr='23.1';
if isempty(Path)
    Def=SetDefPath('r','*.*')
    [File,Path]=uigetfile(Def,'Pick a file:');
    if File==0; NewFileMat=[]; Path=[]; NFiles=0; return; end
    SetDefPath('w',Path)
end
[FileMat,Path,NFiles]=GetFilesInDir(Path);
NOldStr=length(OldStr);
NewFileMat=FileMat;
for FileInd=1:NFiles
    OldFile=deblank(FileMat(FileInd,:));
    if ~isdir(OldFile)
        if strcmp(Path(end),filesep)
            OldFilePath=[Path,OldFile];
        else
            OldFilePath=[Path,filesep,OldFile];
        end
        NewFilePath=OldFilePath;
        NStrOldFile=length(OldFile);
        if NStrOldFile>NOldStr
            Tmp=findstr(OldFile,OldStr);
            if ~isempty(Tmp)
                for i=1:length(Tmp)
                    if Tmp(i)==1
                        NewFile=[NewStr,OldFile(Tmp(i)+NOldStr:end)];
                    else
                        NewFile=[OldFile(1:Tmp(i)-1),NewStr,OldFile(Tmp(i)+NOldStr:end)];
                    end
                end
                NewFilePath=[Path,NewFile];
                [CopyStatus,CopyMsg]=copyfile(OldFilePath,NewFilePath,'writable');
                delete(OldFilePath);
                if ~CopyStatus
                    disp(CopyMsg)
                else
                    fprintf(1,'Rename file %g of %g\n',FileInd,NFiles)
                    fprintf(1,'Old file:    '); disp(OldFilePath);
                    fprintf(1,'New file:    '); disp(NewFilePath);
                end
                fprintf(1,'\n\n')    
            end
        end
    end
    if FileInd==1
        NewFileMat=char(NewFilePath);
    else
        NewFileMat=char(NewFileMat,NewFilePath);
    end			
end
disp(NewFileMat)
