function[HistFileMat,TRStatus]=ExpDin2Hist(FileMat,TRStatus,MaxMemory,TrigStatusMat);
%   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.                                                                      

%==================================================================
%
%	ExpDin2Hist.m
%
%	Markus Junghoefer	[2000]
%
%
%	Function definition
%
%	
%
%==================================================================
if nargin<4; TrigStatusMat=[]; end;
if nargin<3; MaxMemory=10; end;
if nargin<2; TRStatus=[]; end;
if nargin<1; FileMat=[]; end;

[TRStatus]=IfEmptyInputSpecVal(TRStatus,[-1 1],1,...
'File format:\n',...
'RAW                  [ 1]',...
'TAW                  [-1]');

if TRStatus==1
	[DefFilePath]=SetDefPath(1,'*.RAW');
	[NFiles,FileMat,VersionString,BatchFilePath]=ReadFileNames(FileMat,DefFilePath,'Choose NetStation RAW file:');
elseif TRStatus==-1
	[DefFilePath]=SetDefPath(1,'*.TAW');
	[NFiles,FileMat,VersionString,BatchFilePath]=ReadFileNames(FileMat,DefFilePath,'Choose NetStation TAW file:');
end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath(2,BatchPath);
[HistFileMat]=FileNameExt2Mat(FileMat,'HIST',3);
	
for FileIndex=1:NFiles
	
	if 	TRStatus==1			%RAW =>TAW
	
		[RAWFile,RAWPath,RAWFilePath]=GetFileNameOfMat(FileMat,FileIndex);
		if RAWFile==0; return; end;
		RAWFid=fopen(RAWFilePath,'r');
		Version=fread(RAWFid,1,'long');
		Year=fread(RAWFid,1,'short');
		Month=fread(RAWFid,1,'short');
		Day=fread(RAWFid,1,'short');
		Hour=fread(RAWFid,1,'short');
		Min=fread(RAWFid,1,'short');
		Sec=fread(RAWFid,1,'short');
		MSec=fread(RAWFid,1,'long');
		SampRate=fread(RAWFid,1,'short');
		NChan=fread(RAWFid,1,'short');
		Gain=fread(RAWFid,1,'short');
		Bits=fread(RAWFid,1,'short');
		Range=fread(RAWFid,1,'short');	
		NPoints=fread(RAWFid,1,'long');
		NEvents=fread(RAWFid,1,'short')
		EventCodes=fread(RAWFid,[4,NEvents],'char');
		EventCodes=EventCodes';
		EventCodesStr=setstr(EventCodes);
		if NEvents==0
			fprintf(1,'No Digital Input used in file :  ');
			fprintf(1,RAWFilePath);
			return;
		end
		NTotChan=NChan+NEvents;
		LHeader=ftell(RAWFid);
		LRawFile=LHeader+NTotChan.*NPoints.*2;
		
		MaxSizePoints=floor(MaxMemory.*1000000./(NTotChan.*8));
		NLoops=max([1,floor((NPoints./MaxSizePoints))]);
		RestPoints=NPoints-NLoops.*MaxSizePoints;

		if NLoops==1
			[DataMat,Count]=fread(RAWFid,[NTotChan,NPoints],'int16');
			if Count~=NTotChan.*NPoints; error('Count~=NTotChan.*NPoints in ExpDin2Hist'); end
			TrigMat=DataMat(NChan+1:NTotChan,:);
		else
			TrigMat=zeros(NEvents,NPoints);
			for LoopInd=1:NLoops
				fprintf('\n'); clc;
				fprintf(1,'%g of %g total loops done !',LoopInd,NLoops);
				DataMat=fread(RAWFid,[NTotChan,MaxSizePoints],'int16');
				TrigMat(:,(LoopInd-1).*MaxSizePoints+1:LoopInd.*MaxSizePoints)=DataMat(NChan+1:NTotChan,:);
			end
			if RestPoints>0
				DataMat=fread(RAWFid,[NTotChan,RestPoints],'int16');
				TrigMat(:,NLoops.*MaxSizePoints+1:NPoints)=DataMat(NChan+1:NTotChan,:);
			end
		end
		fclose(RAWFid);
		FileStr=RAWFilePath;
		
	elseif TRStatus==-1
		
		[TAWFile,TAWPath,TAWFilePath]=GetFileNameOfMat(FileMat,FileIndex);
		if TAWFile==0; return; end;

		TAWFid=fopen(TAWFilePath,'r');
		Version=fread(TAWFid,1,'long');
		Year=fread(TAWFid,1,'short');
		Month=fread(TAWFid,1,'short');
		Day=fread(TAWFid,1,'short');
		Hour=fread(TAWFid,1,'short');
		Min=fread(TAWFid,1,'short');
		Sec=fread(TAWFid,1,'short');
		MSec=fread(TAWFid,1,'long');
		SampRate=fread(TAWFid,1,'short');
		NChan=fread(TAWFid,1,'short');
		Gain=fread(TAWFid,1,'short');
		Bits=fread(TAWFid,1,'short');
		Range=fread(TAWFid,1,'short');	
		NPoints=fread(TAWFid,1,'long');
		NEvents=fread(TAWFid,1,'short');
		EventCodes=fread(TAWFid,[NEvents,4],'char');
		EventCodes=EventCodes';
		EventCodesStr=setstr(EventCodes);
		if NEvents==0
			fprintf(1,'No Digital Input used in file :  ');
			fprintf(1,TAWFilePath);
			return;
		end
		NTotChan=NChan+NEvents;
		MaxSizePoints=floor(MaxMemory.*1000000./(NTotChan.*2));
		NLoops=floor((NPoints./MaxSizePoints));
		RestPoints=NPoints-NLoops.*MaxSizePoints;

		if NLoops==1
			[DataMat,Count]=fread(TAWFid,[NPoints,NTotChan],'int16');
			if Count~=NTotChan.*NPoints; error('Count~=NTotChan.*NPoints in ExpDin2Hist'); end
			TrigMat=DataMat(:,NChan+1:NTotChan)';
		else
			TrigMat=zeros(NEvents,NPoints);
			for LoopInd=1:NLoops
				fprintf('\n'); clc;
				fprintf(1,'%g of %g total loops done !',LoopInd,NLoops);
				DataMat=fread(TAWFid,[MaxSizePoints,NTotChan],'int16');
				TrigMat(:,(LoopInd-1).*MaxSizePoints+1:LoopInd.*MaxSizePoints)=DataMat(:,NChan+1:NTotChan)';
			end
			if RestPoints>0
				DataMat=fread(TAWFid,[RestPoints,NTotChan],'int16');
				TrigMat(:,NLoops.*MaxSizePoints+1:NPoints)=DataMat(:,NChan+1:NTotChan)';
			end
		end
		fclose(TAWFid);
		FileStr=TAWFilePath;
		
	end
	hfig=figure('Units','normal','Position',[.5 .5 .5 .5],'Name',['DINs of file: ',FileStr],'NumberTitle','off');
	for i=1:NEvents
		subplot(NEvents,1,i);
		plot(TrigMat(i,:))
		axis([1 100000 0 1.1])
		title([EventCodesStr(i,:)])
	end
	pause(.01)
	[HistFile,HistPath,HistFilePath]=GetFileNameOfMat(HistFileMat,FileIndex);
	HistFid=fopen(HistFilePath,'w');
	fprintf(HistFid,'Event History\n\n')
	if MSec<10
		MSecStr=['00',int2str(MSec)];
	elseif MSec<100
		MSecStr=['0',int2str(MSec)];
	else
		MSecStr=int2str(MSec);
	end
	if Sec<10
		SecStr=['0',int2str(Sec)];
	else
		SecStr=int2str(Sec);
	end
	if Min<10
		MinStr=['0',int2str(Min)];
	else
		MinStr=int2str(Min);
	end
	if Hour<10
		HourStr=['0',int2str(Hour)];
	else
		HourStr=int2str(Hour);
	end
	fprintf(HistFid,['000000/',HourStr,':',MinStr,':',SecStr,':',MSecStr,'\n\n']);
	HourStart=Hour;
	MinStart=Min;
	SecStart=Sec;
	MSecStart=MSec;
	MSecStrStart=MSecStr;
	Message=char('Trigger in file:');
	Message=char(Message,FileStr);
	Message=char(Message,'');
	NTrig=zeros(NEvents,1);
	
 	for EventInd=1:NEvents
		NExTrig=0;
		Hour=HourStart;
		Min=MinStart;
		Sec=SecStart;
		MSec=MSecStart;
		MSecStr=MSecStrStart;
		OldTrigPoint=0;
		if TrigMat(EventInd,1)==1
			NTrig(EventInd)=NTrig(EventInd)+1;
			OldTrigPoint=1;
			if isempty(TrigStatusMat) | TrigStatusMat(EventInd,NTrig(EventInd))
				fprintf(HistFid,['000000/',int2str(Hour),':',int2str(Min),':',int2str(Sec),':',MSecStr,' : Stimulus : ',EventCodesStr(EventInd,:),'\n\n']);
			end
		end
		for PointInd=2:NPoints
			if TrigMat(EventInd,PointInd)==1 & TrigMat(EventInd,PointInd-1)==0
				NTrig(EventInd)=NTrig(EventInd)+1;
				AddMSec=(PointInd-OldTrigPoint).*1000./SampRate;
				[Hour,HourStr,Min,MinStr,Sec,SecStr,MSec,MSecStr]=AddMSec2Time(Hour,Min,Sec,MSec,AddMSec);
				TrigStr=['000000/',HourStr,':',MinStr,':',SecStr,':',MSecStr,' : Stimulus : ',EventCodesStr(EventInd,:)];
				if isempty(TrigStatusMat) | TrigStatusMat(EventInd,NTrig(EventInd))
					fprintf(HistFid,[TrigStr,'\n\n']);
				else	
					fprintf(1,['Exclude trigger # ',int2str(NTrig(EventInd)),': ',TrigStr])
					NExTrig=NExTrig+1;
				end
				OldTrigPoint=PointInd;
			end
		end
		NTrig(EventInd)=NTrig(EventInd)-NExTrig;
		Message=char(Message,[EventCodesStr(EventInd,:),' :   ',num2str(NTrig(EventInd))]);
	end
	fclose(HistFid);
	Message=char(Message,'');
	Message=char(Message,'Write history to file:');
	Message=char(Message,HistFilePath);
	Message=char(Message,'');
	hmsgbox=msgbox(Message,HistFile,'help');
	pause(.01)
end
return;

%================================================================== 

function[Hour,HourStr,Min,MinStr,Sec,SecStr,MSec,MSecStr]=AddMSec2Time(Hour,Min,Sec,MSec,AddMSec);


AddSec=floor(AddMSec./1000);
AddMSec=AddMSec-AddSec.*1000;
AddMin=floor(AddSec./60);
AddSec=AddSec-AddMin.*60;
AddHour=floor(AddMin./60);
AddMin=AddMin-AddHour.*60;

MSec=MSec+AddMSec;
if MSec>999; AddAddSec=1; MSec=MSec-1000; else; AddAddSec=0; end
Sec=Sec+AddSec+AddAddSec;
if Sec>59; AddAddMin=1; Sec=Sec-60; else; AddAddMin=0; end
Min=Min+AddMin+AddAddMin;
if Min>59; AddAddHour=1; Min=Min-60; else; AddAddHour=0; end
Hour=Hour+AddHour+AddAddHour;

if MSec<10
	MSecStr=['00',int2str(MSec)];
elseif MSec<100
	MSecStr=['0',int2str(MSec)];
else
	MSecStr=int2str(MSec);
end
if Sec<10
	SecStr=['0',int2str(Sec)];
else
	SecStr=int2str(Sec);
end
if Min<10
	MinStr=['0',int2str(Min)];
else
	MinStr=int2str(Min);
end
if Hour<10
	HourStr=['0',int2str(Hour)];
else
	HourStr=int2str(Hour);
end
