%==================================================================
%
%	Avg2Ascii.m
%
%	Markus Junghoefer	[1996]
%   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[AscFileMat,AvgFileMat]=Avg2Ascii(AvgFileMat,Dec,ChanPointStatus)
%
%==================================================================
if nargin<3; ChanPointStatus=[]; end
if nargin<2; Dec=[]; end
if nargin<1; AvgFileMat=[]; end

[NFiles,AvgFileMat]=ReadFileNames(AvgFileMat,'*.at*','Transform files:');
if NFiles<1; return; end
[AscFileMat]=FileNameExt2Mat(AvgFileMat,'.asc');
[Dec]=IfEmptyInputValInt(['Please insert the decimal places:'],[],Dec,3,0,10,1);

[ChanPointStatus]=IfEmptyInputSpecVal(ChanPointStatus,[1 2],1,...
'Save data in format\n\n',...
'Channels Points      [1]',...
'Points Channels      [2]');


for FileIndex=1:NFiles
	[AvgFile,AvgPath,AvgFilePath]=GetFileNameOfMat(AvgFileMat,FileIndex);
	[AscFile,AscPath,AscFilePath]=GetFileNameOfMat(AscFileMat,FileIndex);
	[AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,SampRate,AvgRef]=ReadAvgFile(AvgFilePath);
	if ChanPointStatus==2; AvgMat=AvgMat'; end
	[Size1,Size2]=size(AvgMat);
	
	fprintf('\n');clc;
	fprintf('Write data to file...\n\n');
	fprintf(AscFilePath);
	
	AscFid=fopen(AscFilePath,'w');
	
	fprintf(AscFid,'%g\t',Size1);
	fprintf(AscFid,'%g\n',Size2);

	MaxMaxAbs=max(max(abs(AvgMat)));
	Degt=['%' num2str(floor(log10(MaxMaxAbs))+1) '.' num2str(Dec) 'f\t'];
	Degn=['%' num2str(floor(log10(MaxMaxAbs))+1) '.' num2str(Dec) 'f\n'];

	for ChanInd=1:Size1
		fprintf(AscFid,Degt,AvgMat(ChanInd,1:Size2-1));
		fprintf(AscFid,Degn,AvgMat(ChanInd,Size2));
	end

	fclose(AscFid);
end
