%==================================================================
%
%	ExtractAsciiBesa
%
%	Markus Junghoefer	[1998]
%   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.                                                                      
%
%
%	Function definition
%

function[FileMat]=ExtractAsciiBesa(NChan,FilePath);

%
%
%=================================================================
if nargin<2; FilePath=[]; end
if nargin<1; return; end

if isempty(FilePath)
	[File,Path]=uigetfile('*.avr*','Choose Besa Ascii file:');
	if File==0
		return
	end
	FilePath=[Path,File];
end

fid=fopen(FilePath,'r','b');
NoUse=fscanf(fid,'%s',1);
NPoints=fscanf(fid,'%g',1);
NoUse=fscanf(fid,'%s',1);
TSB=fscanf(fid,'%g',1);
NoUse=fscanf(fid,'%s',1);
DI=fscanf(fid,'%g',1);
NoUse=fscanf(fid,'%s',1);
SB=fscanf(fid,'%g',1);
NoUse=fscanf(fid,'%s',1);
SC=fscanf(fid,'%g',1);
[AsciiVec,Count]=fscanf(fid,'%g');
fclose(fid);

NCond=Count./(NPoints.*NChan);
if round(NCond)~=NCond;
	Count=Count
	NPointsxNChan=NPoints.*NChan
	NCond=NCond
	return;
end
Count=Count
AvgMat=reshape(AsciiVec,NPoints,NChan,NCond);
for i=1:NCond
	if NCond>9
		CondStr=['0',int2str(i)];
	else
		CondStr=int2str(i);
	end
	ExpFilePath=[FilePath,'.',CondStr];
	if i==1
		FileMat=char(ExpFilePath);
	else
		FileMat=char(FileMat,ExpFilePath);
	end
	SaveAsciiBesa(squeeze(AvgMat(:,:,i))',TSB,DI,SB,SC,ExpFilePath);
end
return;
