function [OutFilePathImg,OutFilePathHdr]=Img2Img(FilePathImg,MinLim,MaxLim)

%   Img2Img

%   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; MaxLim=[-2.53]; end
if nargin<2; MinLim=[-6]; end
if nargin<1; FilePathImg=[]; end

if isempty(FilePathImg)
    DefFolder=['D:\ValAro\00_Stats_Scaling\RandStatsSmooth08\All\XContrasts\016_AroLinHiGTLoAll']
    %DefFolder=['D:\ValAro\00_Stats_NoScaling\RandStatsSmooth08\All\XContrasts\016_AroLinHiGTLoAll']
    Mask=['*.img'];
    FilePathImg=spm_get(1,Mask,'Choose a "Write filtered" analyze file',DefFolder);
    FilePathExt=lower(FilePathImg(length(FilePathImg)-3:length(FilePathImg)));
    if strcmp(FilePathExt,'.hdr')
        FilePathImg=[FilePathImg(1:length(FilePathImg)-4),'.img'];
        FilePathExt='.img';
    end
    if ~strcmp(FilePathExt,'.img')
        error('Please choose an analyze .img format file.')
    end
end
FilePathHdr=[FilePathImg(1:length(FilePathImg)-4),'.hdr'];
OutFilePathHdr=[FilePathImg(1:length(FilePathImg)-4),'Min',num2str(MinLim),'Max',num2str(MaxLim),'.hdr']
OutFilePathImg=[FilePathImg(1:length(FilePathImg)-4),'Min',num2str(MinLim),'Max',num2str(MaxLim),'.img']

[Dim,Vox,Scale,Type,Offset,Origin,Descrip]=spm_hread(FilePathHdr);
spm_hwrite(OutFilePathHdr,Dim,Vox,Scale,Type,Offset,Origin,Descrip);
ProdDim=prod(Dim);
if Type==2
    ImgDataFormat='ubit8';
elseif Type==3
    ImgDataFormat='ubit16';
elseif Type==16
    ImgDataFormat='float';
else
    error('Unknown Type')
end 
fid=fopen(FilePathImg,'r','ieee-le');
[ImgMat,Count]=fread(fid,ProdDim,ImgDataFormat);
fclose(fid);
ImgMat(find(ImgMat<MinLim))=0.*ImgMat(find(ImgMat<MinLim));
ImgMat(find(ImgMat>MaxLim))=0.*ImgMat(find(ImgMat>MaxLim));
fid=fopen(OutFilePathImg,'w','ieee-le');
fwrite(fid,ImgMat,ImgDataFormat);
fclose(fid);
return