function [FuncMat,FilePath,SizeFuncMat]=ReadEPI(DefPath,SaveStatus,SaveFilePath)

%	ReadEPI.m

%   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; SaveFilePath=[]; end
if nargin<2; SaveStatus=1; end
if nargin<1; DefPath=[]; end

EPIFormat='KN';

if isempty(DefPath)
	DefPath=SetDefPath(1)
	[File,DefPath]=ReadFilePath([],DefPath,'Choose an image file:');
	if File==0; return; end
else
	if ~strcmp(DefPath(length(DefPath)),filesep)
		DefPath=[DefPath,filesep];
	end
end
SetDefPath(2,DefPath);
if strcmp(EPIFormat,'KN')
	NImg=768;
	NSlice=6;
	NShot=128;
	NSeek=0;
else
	NImg=504;
	NSlice=7;
	NShot=NImg./NSlice;
	NSeek=7904;
end
clc;
for ShotInd=1:NShot
	for SliceInd=1:NSlice
		if strcmp(EPIFormat,'KN')
			
			FilePath=[DefPath,'I.',ImgIndStr];
		else	
			ImgInd=(ShotInd-1).*NSlice+SliceInd;
			if ImgInd<10
				ImgIndStr=['00' int2str(ImgInd)];
			elseif ImgInd>9 & ImgInd <100
				ImgIndStr=['0' int2str(ImgInd)];
			elseif ImgInd>99 & ImgInd <1000
				ImgIndStr=[int2str(ImgInd)];
			else 
				error('ImgInd>1000 in Read504')
			end
			FilePath=[DefPath,'I.',ImgIndStr];
		end
		[FileSize]=GetFileSize(FilePath);
		DataSize=FileSize-NSeek;
		m=round(sqrt(DataSize./2));
		if ShotInd==1 & SliceInd==1
			FuncMat=zeros(m,m,NSlice,NShot);
		end
		fprintf('\n')
		fprintf('Read file:  ')
		fprintf(FilePath)
		fprintf(';  Size: %g x %g',m,m);
		ImgFid=fopen(FilePath,'r');
		SeekStatus=fseek(ImgFid,NSeek,-1);
		FuncMat(:,:,SliceInd,ShotInd)=fread(ImgFid,[m,m],'int16')';
		fclose(ImgFid);
	end
end
SizeFuncMat=[m,m,NSlice,NShot];
if SaveStatus
	if isempty(SaveFilePath)
		SaveFilePath=[DefPath,'Func'];
	end
	SaveNDimData(FuncMat,SaveFilePath,'int16');
end
return;
