function [] = WriteMat2App(Mat,FilePath,ShiftDimOrder,ScaleBins,SampRate,AvgRefStatus,EegMegStatus,NChanExtra)
%   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.                                                                      
%==================================================================
%
%	WriteMat2App.m
%
%
%	Markus Junghoefer	[2000]
%
%
%
%	Function definition
%
%	function [] = WriteMat2App(Mat,FilePath,ShiftDimOrder)
% 
% 	if nargin<3; ShiftDimOrder=0; end
% 	if nargin<2; FilePath=[]; end
% 	if nargin<1; FileMat=[]; end
%
%	[NTrials,NChan,NPoints]=size(Mat);
%
%=================================================================
if nargin<8; NChanExtra=0; end
if nargin<7; EegMegStatus=1; end
if nargin<6; AvgRefStatus=1; end
if nargin<5; SampRate=125; end
if nargin<4; ScaleBins=100; end
if nargin<3; ShiftDimOrder=[]; end
if nargin<2; FilePath=[]; end
if nargin<1; Mat=[]; end
if isempty(Mat) | length(size(Mat))~=3
	return; 
else
	[NTrials,NChan,NPoints]=size(Mat);
end
if ~isempty(ShiftDimOrder)
	Mat=shiftdim(Mat,ShiftDimOrder);
end
Version=2;
LHeader=1000;
Mat=Mat.*ScaleBins;
Fid=fopen(FilePath,'w','b');
fwrite(Fid,Version,'int16');
fwrite(Fid,LHeader,'int16');
fwrite(Fid,ScaleBins,'int16');
fwrite(Fid,NChan,'int16');
fwrite(Fid,NPoints,'int16');
fwrite(Fid,NTrials,'int16');
fwrite(Fid,SampRate,'int16');
fwrite(Fid,AvgRefStatus,'int16');
fwrite(Fid,EegMegStatus,'int16');
fwrite(Fid,NChanExtra,'int16');		
if EegMegStatus==1 %EEG
    DataFormat='int16';
elseif EegMegStatus==2 %MEG
    DataFormat='float32';
end
Tell=ftell(Fid);
ZeroVec=zeros(LHeader-Tell,1);
fwrite(Fid,ZeroVec,'int8');

fprintf(1,'Write %g trials containing %g sensors and %g points to file:\n\n',NTrials,NChan,NPoints);
Message=char(['Write ' int2str(NTrials) ' trials containing ' int2str(NChan) ' channels and ' int2str(NPoints) ' points to file:']);
Message=char(Message,[]);
Message=char(Message,FilePath);
hmsgbox=msgbox(Message,'Info:','help');
pause(.001);
for TrialInd=1:NTrials
	fprintf(1,'%g\n',TrialInd)	
	fwrite(Fid,squeeze(Mat(TrialInd,:,:))',DataFormat); 
end
fclose(Fid);
return;

	
