%==================================================================
%
%	Avg2KNPC.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[File,Path,FilePath]=Avg2KNPC(AvgFileMat,AvgFileVersion)
%
%==================================================================
if nargin<2; AvgFileVersion=1; end
if nargin<1; AvgFileMat=[]; end

[NFiles,AvgFileMat]=ReadFileNames(AvgFileMat,'*.at*','Transform files:');

for FileIndex=1:NFiles
	
	[AvgFile,AvgPath,AvgFilePath]=GetFileNameOfMat(AvgFileMat,FileIndex);
	
	[AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,SampRate,AvgRef]=ReadAvgFile(AvgFilePath,AvgFileVersion);
	[NChan,NPoints]=size(AvgMat);
	fprintf('\n');clc;
	fprintf('Write data to file...\n\n');
	KNFilePath=[AvgFilePath,'.KN'];
	fprintf(KNFilePath)
	
	KNFid=fopen(KNFilePath,'w+');
	
	LHeaderBase=40;
	LHdrString=4;
	LHdrArray=6.*NChan.*2;
	LHdr=LHeaderBase+LHdrString+LHdrArray;
	
	LTrialBase=62;
	LTrialArray=NChan.*4;
	LTrialHdr=LTrialBase+LTrialArray;
	LTrialData=NChan.*NPoints.*2;
	LTrial=LTrialHdr+LTrialData;
	
	TrialByteAdress=LHdr;
	TableByteAdress=LHdr+LTrial;
	
	%===================================================================
	%========Header Base================================================
	fwrite(KNFid,LHdr,'int16'); 	 		%LHdr 1-2
	fseek(KNFid,-2,0);
	a=fread(KNFid,2,'int8');
	fseek(KNFid,-2,0);
	fwrite(KNFid,[a(2) a(1)],'int8');
	
	fwrite(KNFid,LHdrString,'int16'); 	 	%LHdrString 3-4 5 for test\0
	
	
	fwrite(KNFid,1,'int16'); 	 			%NFiles 5-6
	fwrite(KNFid,1,'int16'); 				%MaxNoOfTrials 7-8
	fwrite(KNFid,1,'int16'); 	 			%MaxNoOfCond 9-10
	fwrite(KNFid,NChan,'int16'); 			%NChan 11-12
	NByteSeek=8;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	b=zeros(NByteSeek,1);
	b(2:2:NByteSeek)=a(1:2:NByteSeek-1);
	b(1:2:NByteSeek)=a(2:2:NByteSeek);
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,b,'int8');	
	
	fwrite(KNFid,TableByteAdress,'int32'); %NextTrialByteAdress 13-16, da nur ein trial TableByteAdress
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');
	
	fwrite(KNFid,0,'int32'); 	 			%StartTime 17-20
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');
	
	fwrite(KNFid,1,'int32'); 	 			%EndTime 21-24
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');

	fwrite(KNFid,-1,'int16'); 	 			%-1 if avg 25-26
	fwrite(KNFid,1,'int16'); 	 			%Group	27-28
	fwrite(KNFid,[0 0 0 0],'int16');		%Spare 29-36
	
	if AvgRef; Word19=LTrialBase+512; else; Word19=LTrialBase; end
	
	fwrite(KNFid,Word19,'int16'); 			%??0 if 62 trialbase	37-38 Word 19
	TimeStatus=1000;
	fwrite(KNFid,TimeStatus,'int16'); 	 	%0 if milliseconds; 1000 if microseconds	39-40
	
	NByteSeek=16;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	b=zeros(NByteSeek,1);
	b(2:2:NByteSeek)=a(1:2:NByteSeek-1);
	b(1:2:NByteSeek)=a(2:2:NByteSeek);
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,b,'int8');	

	%========Header String===========================================
	fwrite(KNFid,'test','char');
	%================================================================
	
	%================================================================
	%========HeaderArray=============================================
	fwrite(KNFid,zeros(6,NChan),'int16');
	NByteSeek=12.*NChan;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	b=zeros(NByteSeek,1);
	b(2:2:NByteSeek)=a(1:2:NByteSeek-1);
	b(1:2:NByteSeek)=a(2:2:NByteSeek);
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,b,'int8');	
	
	%================================================================
	%================================================================
	%========TrialBase===============================================
	fwrite(KNFid,1,'int16'); 				 			%TrialNo	1-2
	fwrite(KNFid,1,'int16'); 	 						%NMarker	3-4
	fwrite(KNFid,floor(median(NTrialAvgVec)),'int16'); 	%NTrials	5-6
	fwrite(KNFid,NChan,'int16');  						%NChan	7-8
	if TimeStatus==0; SampInt=1000./SampRate; elseif TimeStatus==1000; SampInt=1000000./SampRate; end
	fwrite(KNFid,SampInt,'int16'); 	 					%Sampling Int depending on word 20 in haederbase 9-10
	NByteSeek=10;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	b=zeros(NByteSeek,1);
	b(2:2:NByteSeek)=a(1:2:NByteSeek-1);
	b(1:2:NByteSeek-1)=a(2:2:NByteSeek);
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,b,'int8');		

	fwrite(KNFid,NChan.*NPoints,'int32');  %NChan.*NPoints	11-14
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');
			
	fwrite(KNFid,[1 0 0],'int16');  					%Condition nos1-3  15-16
	fwrite(KNFid,[0 0 0 0 0],'int16');    				%Trial markers1-5  21-22
	fwrite(KNFid,0,'int16');  							%latency of marker	31-32
	fwrite(KNFid,1,'int16');  							%Group No	33-34
	fwrite(KNFid,[0 0 0 0 0 0],'int16');  				%Free No	35-46
	NByteSeek=32;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	b=zeros(NByteSeek,1);
	b(2:2:NByteSeek)=a(1:2:NByteSeek-1);
	b(1:2:NByteSeek)=a(2:2:NByteSeek);
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,b,'int8');	
	
	fwrite(KNFid,LTrial,'int32');  						%Size of trial in bytes 	47-50
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');
	
	fwrite(KNFid,LTrialHdr,'int32');  					%Size of trial header in bytes 	51-54  !!!!!!!!!!!!!!!
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');
	
	fwrite(KNFid,0,'int32');  							%Byte Adress of previous trial 	55-58  da nur ein trial
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');
	
	fwrite(KNFid,TableByteAdress,'int32');  			%Byte Adress of next trial 	59-62 falls nur einer Byte Adress of adress table !!!!!!!!!!
	NByteSeek=4;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,[a(4) a(3) a(2) a(1)],'int8');	

	%===================================================
	%========Trial Array================================
	
	fwrite(KNFid,zeros(NChan,1),'int16'); 	 	 		 %RT's
	BinsPerMV=100;
	fwrite(KNFid,BinsPerMV.*ones(NChan,1),'int16'); 	 %Bins per µV per Channel
	NByteSeek=4.*NChan;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	b=zeros(NByteSeek,1);
	b(2:2:NByteSeek)=a(1:2:NByteSeek-1);
	b(1:2:NByteSeek)=a(2:2:NByteSeek);
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,b,'int8');	

	%===================================================
	%===================================================
	%=========Data======================================
	%===================================================
	
	if max(max(abs(AvgMat))).*BinsPerMV>32767; fprintf('Warning: Bad scaling in Avg2KN !!!!!!!!\n'); end
	fwrite(KNFid,AvgMat.*BinsPerMV,'int16');
	NByteSeek=LTrialData;
	fseek(KNFid,-NByteSeek,0);
	a=fread(KNFid,NByteSeek,'int8');
	b=zeros(NByteSeek,1);
	b(2:2:NByteSeek)=a(1:2:NByteSeek-1);
	b(1:2:NByteSeek)=a(2:2:NByteSeek);
	fseek(KNFid,-NByteSeek,0);
	fwrite(KNFid,b,'int8');	

	%===================================================
	%=======Adress Table================================
	%TellAdressTable=ftell(KNFid);
	fwrite(KNFid,TrialByteAdress,'int32');
	fseek(KNFid,-4,0);
	a=fread(KNFid,4,'int8');
	fseek(KNFid,-4,0);
	fwrite(KNFid,[a(4),a(3),a(2),a(1)],'int8'); 
	
	fwrite(KNFid,TableByteAdress,'int32');	
	fseek(KNFid,-4,0);
	a=fread(KNFid,4,'int8');
	fseek(KNFid,-4,0);
	fwrite(KNFid,[a(4),a(3),a(2),a(1)],'int8'); 

	fclose(KNFid);
end
