function [AppFid] = SaveAppData(Version,AppFid,FilePath,ScaleBins,NChan,NPoints,NTrials,ActTrial, ...
		SampRate,AvgRefStatus,EegMegStatus,NChanExtra,TrialMat)
     
%   SaveAppData

%   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<13;TrialMat=[];end;
if nargin<12;NChanExtra=[];end;
if nargin<11;EegMegStatus=[];end;
if nargin<10;AvgRefStatus=[];end;
if nargin<9;SampRate=[];end;
if nargin<8;ActTrial=[];end;
if nargin<7;NTrials=[];end;
if nargin<6;NPoints=[];end;
if nargin<5;NChan=[];end;
if nargin<4;ScaleBins=[];end;
if nargin<3;FilePath=[];end;
if nargin<2;Version=[];end;
if nargin<1;AppFid=[]; return; end;

LAppHeader=1000;
if isempty(AppFid)
	AppFid=fopen(FilePath,'w+','b');
	fwrite(AppFid,Version,'int16');
	fwrite(AppFid,ScaleBins,'int16');
	fwrite(AppFid,NChan,'int16');
	fwrite(AppFid,NPoints,'int16');
	fwrite(AppFid,NTrials,'int16');
	fwrite(AppFid,SampRate,'int16');
	if Version>1
		fwrite(AppFid,AvgRefStatus,'int16');
		fwrite(AppFid,EegMegStatus,'int16');
		fwrite(AppFid,NChanExtra,'int16');
	end
	AppTell=ftell(AppFid);
	ZeroVec=zeros(LAppHeader-AppTell,1);
	fwrite(AppFid,ZeroVec,'int8');
end
if ~strcmp(ActTrial,'all')
	MaxAbsTrialMat=max(max(abs(TrialMat)));
	if MaxAbsTrialMat.*ScaleBins>32768; fprintf('WARNING: Bad scaling in SaveAppData !!!!!'); end
	SeekStatus=fseek(AppFid,LAppHeader+NChan.*NPoints.*(ActTrial-1).*2,-1);
	if SeekStatus==-1; error('fseek error'); end
	fwrite(AppFid,TrialMat.*ScaleBins,'int16');
	if ActTrial==NTrials;
		fclose(AppFid);
		AppFid=[];
	end
	return;
else
	for TrialInd=1:NTrials
		TrialMatTmp=squeeze(TrialMat(:,:,TrialInd));
		MaxAbsTrialMat=max(max(abs(TrialMat)));
		if MaxAbsTrialMat.*ScaleBins>32768; fprintf('WARNING: Bad scaling in SaveAppData !!!!!'); end
		fwrite(AppFid,TrialMat.*ScaleBins,'int16');
	end
	fclose(AppFid); 
	AppFid=[];
end
