function[EGISFileMat,CondFileMat,FileMat]=TransNetGeoFaces(FileMat,TRStatus,
PreTrig,PostTrig,GainFilePath,ZeroFilePath,GivenNTrials)

%   TransNetGeoFaces

%   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<7; GivenNTrials=[]; end;
if nargin<6; ZeroFilePath=[]; end;
if nargin<5; GainFilePath=[]; end;
if nargin<4; PostTrig=[]; end;
if nargin<3; PreTrig=[]; end;
if nargin<2; TRStatus=[]; end;
if nargin<1; FileMat=[]; end;

%==================================================================
fprintf('\n');clc;
[TRStatus]=IfEmptyInputSpecVal(TRStatus,[-1 1],1,...
'Please insert the file status:\n',...
'RAW                   [ 1]',...
'TAW                   [-1]');

if TRStatus==1; Mask='*.RAW'; elseif TRStatus==-1; Mask='*.TAW' ; end

[NFiles,FileMat]=ReadFileNames(FileMat,Mask,'Choose NetStation file:');
if NFiles==0; return; end

[EGISFileMat]=FileNameExt2Mat(FileMat,'E1',3);
[CondFileMat]=FileNameExt2Mat(EGISFileMat,'.CON');
[RCFileMat]=FileNameExt2Mat(FileMat,'RC',3);
[RTFileMat]=FileNameExt2Mat(FileMat,'RT',3);


%=========EGIS Header======================
global BytOrd; 					BytOrd=[0 0 0 0];
global HdrVer; 				
global LData;					
global LHeader;					LHeader=[];
global ExptNam;				ExptNam=zeros(80,1);
global RunDate;		
global RunTime; 		
global SubjID;					SubjID=0;
global Handed;					Handed=0;
global Sex;					Sex=0;
global Age;					Age=0;
global ExperID;					ExperID=0;
global EdVer;				
global CalFlag;					CalFlag=0;
global NChan;				
global LComment;				LComment=0;
global LText;					
global LPad;						
global BrdGain;			
global ChanGain;		
global ChanZero;		
global CellName;				CellName=zeros(80,1);
global LHeader;					LHeader=[];
global NCells;					NCells=1;
global CellID;					CellID=0;
global NTrials;			
global NPoints;		    
global SampRate;		
global LSpec	;		
global LSpecCell1;		
global LCellHdr;		
%===============================



for FileIndex=1:NFiles
	
	[NetFile,NetPath,NetFilePath]=GetFileNameOfMat(FileMat,FileIndex);

	fprintf('\n')
	fprintf('TransNetGeoTrig\n')
	fprintf(NetFilePath)
	fprintf('\n')
	clc;
	fprintf('Start reading data file...\n\n');
	fprintf(NetFilePath);
	fprintf('\n\n');

	NetFid=fopen(NetFilePath,'r');

	%=========NetStation Header===============

	Version=fread(NetFid,1,'long');
	Year=fread(NetFid,1,'short');
	Month=fread(NetFid,1,'short');
	Day=fread(NetFid,1,'short');
	Hour=fread(NetFid,1,'short');
	Minute=fread(NetFid,1,'short');
	Sec=fread(NetFid,1,'short');
	MSec=fread(NetFid,1,'long');
	SampRate=fread(NetFid,1,'short');
	NChan=fread(NetFid,1,'short');
	BrdGain=fread(NetFid,1,'short');
	Bits=fread(NetFid,1,'short');
	Range=fread(NetFid,1,'short');
	NNetPoints=fread(NetFid,1,'long');
	NNetEvents=fread(NetFid,1,'short');
	EventCodes=fread(NetFid,[NNetEvents,4],'char');
	LNetHeader=ftell(NetFid);
	
	TimeMsStart=MSec+Sec.*1000+Minute.*60000+Hour.*3600000;

	[NetFile,NetPath]=SepFilePath(NetFilePath);
	LNetFile=length(NetFile);
	if isempty(GainFilePath) 
		if LNetFile>4
			if strcmp(NetFile(LNetFile-5:LNetFile-4),'.f')	%filtered data
				GainFilePath=[NetPath,NetFile(1:LNetFile-5) 'Gain'];
			else
				GainFilePath=[NetPath,NetFile(1:LNetFile-3) 'Gain'];
			end
		else
			GainFilePath=[NetPath,NetFile(1:LNetFile-3) 'Gain'];
		end
	end
	if isempty(ZeroFilePath) 
		if LNetFile>4
			if strcmp(NetFile(LNetFile-5:LNetFile-4),'.f')	%filtered data
				ZeroFilePath=[NetPath,NetFile(1:LNetFile-5) 'Zero'];
			else
				ZeroFilePath=[NetPath,NetFile(1:LNetFile-3) 'Zero'];
			end
		else
			ZeroFilePath=[NetPath,NetFile(1:LNetFile-3) 'Zero'];
		end	
	end
	[ChanGain,ChanZero,...
	GainYear,GainMonth,GainDay,GainHour,GainMinute,GainSec,GainMSec,...
	ZeroYear,ZeroMonth,ZeroDay,ZeroHour,ZeroMinute,ZeroSec,ZeroMSec,OldVersion]=...
	ReadNetGainZero(NChan,GainFilePath,ZeroFilePath);	
	fprintf('Time dist between data file and gain file:\n\n')
	TimeDiffInfo([Year Month Day Hour Minute Sec MSec; GainYear GainMonth GainDay GainHour GainMinute GainSec GainMSec],1,.5);
	fprintf('Time dist between data file and zero file:\n\n')
	TimeDiffInfo([Year Month Day Hour Minute Sec MSec; ZeroYear ZeroMonth ZeroDay ZeroHour ZeroMinute ZeroSec ZeroMSec],1,.5);

	if isempty(NNetEvents) | NNetEvents==0
		fprintf('Sorry, no trigger channel in this file !\n')
		pause(4)
	else
                fprintf('\n');
		fprintf('Number of trigger channels in this file : %g\n\n',NNetEvents); again=0;
		fprintf('End reading data header...\n');
		pause(.5)
		%===============================================================================
		if LNetFile>4
			StringIndex=1;
			while NetFile(StringIndex:StringIndex+1)~='.f' & StringIndex<LNetFile
				StringIndex=StringIndex+1;
			end
			if StringIndex~=LNetFile	%filtered data
				HistFilePath=[NetPath,NetFile(1:StringIndex) 'HIST'];
			else
				HistFilePath=[NetPath,NetFile(1:LNetFile-3) 'HIST'];
			end
		end
		[HistFile,HistPath,HistFilePath]=ReadFilePath(HistFilePath,'*.HIST',['Choose the HIST file:']);
		fprintf('\n\n'); clc;
		fprintf('Read Hist file:\n\n')
		fprintf(HistFilePath)
		
		HistFid=fopen(HistFilePath,'r');
				
		Tmp=fscanf(HistFid,'%s',1);	%Event
		Tmp=fscanf(HistFid,'%s',1);	%History
		StartTimeTest=fscanf(HistFid,'%s',1);
		StartMsTest=StartTimeTest(19)-48;
		StartMsTest=StartMsTest+(StartTimeTest(18)-48).*10;
		StartMsTest=StartMsTest+(StartTimeTest(17)-48).*100;
		StartMsTest=StartMsTest+(StartTimeTest(15)-48).*1000;
		StartMsTest=StartMsTest+(StartTimeTest(14)-48).*10000;
		StartMsTest=StartMsTest+(StartTimeTest(12)-48).*60000;
		StartMsTest=StartMsTest+(StartTimeTest(11)-48).*600000;
		StartMsTest=StartMsTest+(StartTimeTest(9)-48).*3600000;
		StartMsTest=StartMsTest+(StartTimeTest(8)-48).*36000000;

		if TimeMsStart~=StartMsTest;
			fprintf('\n\n')
			fprintf('WARNING:\n\n')
			fprintf('Start time in file:\n')
			fprintf(NetFilePath)
			fprintf('\n')
			fprintf('differs from start time in file:\n')
			fprintf(HistFilePath)
			fprintf('\n\n')
			fprintf('Take start time from HIST file for further calculations:')
			pause(2)
			TimeMsStart=StartMsTest;
		end
		
		Index=0;
		Tmp='Blodsinn';
		fseek(HistFid,0,'bof');
		while ~strcmp(Tmp,'Stimulus')
			Tmp=fscanf(HistFid,'%s',1);
			Index=Index+1;
		end
		Index=Index-3;
		fseek(HistFid,0,'bof');
		Tmp=fscanf(HistFid,'%s',Index);

		Index=0;
		Count=1;
		Tell1=ftell(HistFid);
		while Count==1
			Index=Index+1;
			[Tmp1,Count]=fscanf(HistFid,'%s',1);
			[Tmp2,Count]=fscanf(HistFid,'%s',1);
			[Tmp3,Count]=fscanf(HistFid,'%s',1);
			[Tmp4,Count]=fscanf(HistFid,'%s',1);
			[Tmp5,Count]=fscanf(HistFid,'%s',1);
		end
		NTrigEvents=Index-1;
		NRowTrigDateTimeMat=19;
		TrigDateTimeMat=zeros(NTrigEvents,NRowTrigDateTimeMat);
		TrigCodeMat=zeros(NTrigEvents,6);
		TrigBitMat=zeros(NTrigEvents,4);

		fseek(HistFid,Tell1,'bof');
                
		for Index=1:NTrigEvents
			[Tmp1,Count]=fscanf(HistFid,'%s',1);
			[Tmp2,Count]=fscanf(HistFid,'%s',1);
			[Tmp3,Count]=fscanf(HistFid,'%s',1);
			[Tmp4,Count]=fscanf(HistFid,'%s',1);
			[Tmp5,Count]=fscanf(HistFid,'%s',1);
			TrigDateTimeMat(Index,:)=Tmp1;
			TrigCodeMat(Index,:)=Tmp5;
		end
		TmpOld=0;
		Index2=0;

		for Index1=1:NTrigEvents
			TmpNew=TrigDateTimeMat(Index1,19)-48;									
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,18)-48).*10;			
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,17)-48).*100;		
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,15)-48).*1000;	
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,14)-48).*10000;
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,12)-48).*60000;
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,11)-48).*600000;
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,9)-48).*3600000;
			TmpNew=TmpNew+(TrigDateTimeMat(Index1,8)-48).*36000000;
			TrigTimeVec(Index1)=TmpNew;
                end 
                TrigTimeVecTmp=TrigTimeVec;
                TrigCodeMatTmp=TrigCodeMat;
                NRestTrigEvents=NTrigEvents;
                Index2=0;
                ValVec2=0;
                while ~isempty(ValVec2)
                        Index2=Index2+1;
                        
                        [ValVec1,IndVec1]=find(abs(TrigTimeVecTmp-TrigTimeVecTmp(1))<3);
                        [ValVec2,IndVec2]=find(abs(TrigTimeVecTmp-TrigTimeVecTmp(1))>2);    
                        for i=1:length(IndVec1)
			     Tmp=TrigCodeMatTmp(IndVec1(i),5);
			     if (Tmp-48)==1
				TrigBitMat(Index2,1)=1;
			     elseif (Tmp-48)==2
				TrigBitMat(Index2,2)=1;
			     elseif (Tmp-48)==3
				TrigBitMat(Index2,3)=1;
			     elseif (Tmp-48)==4
				TrigBitMat(Index2,4)=1;
                             end
                         end
                         TrigTimeVec(Index2)=TrigTimeVecTmp(1);
                         TrigTimeVecTmp=TrigTimeVecTmp(IndVec2);
                         TrigCodeMatTmp=TrigCodeMatTmp(IndVec2,:);              
		end
	        Index2=Index2-1;
		TrigBitMat=TrigBitMat(1:Index2,:);
		TrigTimeVec=TrigTimeVec(1:Index2);
		for Index=1:Index2
			if TrigBitMat(Index,:)==[0 0 0 0];
				CondVec(Index)=0;
			elseif TrigBitMat(Index,:)==[1 0 0 0];
				CondVec(Index)=1;
			elseif TrigBitMat(Index,:)==[0 1 0 0];
				CondVec(Index)=2;
			elseif TrigBitMat(Index,:)==[1 1 0 0];
				CondVec(Index)=3;
			elseif TrigBitMat(Index,:)==[0 0 1 0];
				CondVec(Index)=4;
			elseif TrigBitMat(Index,:)==[1 0 1 0];
				CondVec(Index)=5;
			elseif TrigBitMat(Index,:)==[0 1 1 0];
					CondVec(Index)=6;
			elseif TrigBitMat(Index,:)==[1 1 1 0];
					CondVec(Index)=7;
			elseif TrigBitMat(Index,:)==[0 0 0 1];
					CondVec(Index)=8;
			elseif TrigBitMat(Index,:)==[1 0 0 1];
					CondVec(Index)=9;
			elseif TrigBitMat(Index,:)==[0 1 0 1];
					CondVec(Index)=10;
			elseif TrigBitMat(Index,:)==[1 1 0 1];
					CondVec(Index)=11;
			elseif TrigBitMat(Index,:)==[0 0 1 1];
					CondVec(Index)=12;
			elseif TrigBitMat(Index,:)==[1 0 1 1];
					CondVec(Index)=13;
			elseif TrigBitMat(Index,:)==[0 1 1 1];
					CondVec(Index)=14;
			elseif TrigBitMat(Index,:)==[1 1 1 1];
					CondVec(Index)=15;
                        end
		end
                ReacIndVec=find(CondVec==13 | CondVec==14);
                NoReacIndVec=find(CondVec~=13 & CondVec~=14);
		NTrials=length(NoReacIndVec);
                fprintf('\n'); clc;
		fprintf('Number of trials: %g ',NTrials);
		pause(.5)
		if ~isempty(GivenNTrials)
			if NTrials~=GivenNTrials; 
                            Message=char('Warning:');
		            Message=char(Message,'');
                            Message=char(Message,'bad number of trials:');
                            Message=char(Message,['Expected:  ',int2str(GivenNTrials)]);
                            Message=char(Message,['Given:       ',int2str(NTrials)]);
		            hmsgbox=msgbox(Message,'Info','warn'); 
                        end
		end
		
		NoReacTrigDateTimeMat=TrigDateTimeMat(NoReacIndVec,:);
		
                ReacTrigTimeVec=TrigTimeVec(ReacIndVec);
		ReacCondVec=CondVec(ReacIndVec);
                NoReacTrigTimeVec=TrigTimeVec(NoReacIndVec);
		NoReacCondVec=CondVec(NoReacIndVec);
        
		
		%==================================================
		ReacTrigTimeVec=ReacTrigTimeVec-TimeMsStart.*ones(size(ReacTrigTimeVec));
	        NoReacTrigTimeVec=NoReacTrigTimeVec-TimeMsStart.*ones(size(NoReacTrigTimeVec));
	
                %==================================================
		ReacTrigPointVec=ceil(ReacTrigTimeVec./(1000./SampRate))+ones(size(ReacTrigTimeVec));
	        NoReacTrigPointVec=ceil(NoReacTrigTimeVec./(1000./SampRate))+ones(size(NoReacTrigTimeVec));
	
                 [YSort,IndexSort]=sort(NoReacTrigPointVec);
		NoReacTrigPointVec=NoReacTrigPointVec(IndexSort);
		NoReacTrigTimeVec=NoReacTrigTimeVec(IndexSort);
		NoReacCondVec=NoReacCondVec(IndexSort);
                
                [YSort,IndexSort]=sort(ReacTrigPointVec);
                ReacTrigPointVec=ReacTrigPointVec(IndexSort);
		ReacTrigTimeVec=ReacTrigTimeVec(IndexSort);
		ReacCondVec=ReacCondVec(IndexSort);
		
		[PreTrig]  =IfEmptyInputValInt(['Please insert the'],['pre trigger intervall:'],PreTrig,100,-(NNetPoints-1),NNetPoints-1,1);
		[PostTrig]=IfEmptyInputValInt(['Please insert the'],['post trigger intervall:'],PostTrig,200,-(NNetPoints-PreTrig),NNetPoints-PreTrig);
			
		DistTrig=PreTrig+PostTrig+1;

                %==================Conditions=============================================================
		TrialStatusVec=ones(NTrials,1);
		%=====Alle trigger, die kleiner sind als pretrigger fallen raus===================
        	BadIndexVec=[];
		BadIndexVec=find(NoReacTrigPointVec<PreTrig);
		if ~isempty(BadIndexVec); 
			TrialStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
		end
		for TrialInd=2:NTrials
			if NoReacTrigPointVec(TrialInd)-NoReacTrigPointVec(TrialInd-1)<DistTrig
                            TrialStatusVec(TrialInd)=0; 
                            TrialStatusVec(TrialInd-1)=0;
                        end
		end
		%=====Alle trigger, die groesser sind als posttrigger fallen raus===================
        	BadIndexVec=[];
		BadIndexVec=find(NNetPoints-NoReacTrigPointVec<PostTrig);
		if ~isempty(BadIndexVec); 
			TrialStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
		end
		
		OkTrialsIndVec=find(TrialStatusVec==1);
		NTrials=length(OkTrialsIndVec);
		fprintf('Number of trials to save: %g ',NTrials);
		
		NoReacCondVec=NoReacCondVec(OkTrialsIndVec);
		NoReacTrigTimeVec=NoReacTrigTimeVec(OkTrialsIndVec);
		NoReacTrigPointVec=NoReacTrigPointVec(OkTrialsIndVec);
    
                ReacCondVec=ReacCondVec(OkTrialsIndVec);
		ReacTrigTimeVec=ReacTrigTimeVec(OkTrialsIndVec);
		ReacTrigPointVec=ReacTrigPointVec(OkTrialsIndVec);

		%============Save condition vector to file==========================
        	[CondFile,CondPath,CondFilePath]=GetFileNameOfMat(CondFileMat,FileIndex);
	 	[CondFilePath,CondEndPos] = SaveData(NoReacCondVec',CondFilePath,1,[],'ascii','ascii',[],[],[],1,1,0);
		[CondFilePath,CondEndPos] = SaveData(NoReacTrigPointVec',CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);
		[CondFilePath,CondEndPos] = SaveData(NoReacTrigTimeVec',CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);

                %============Save reaction vector to file==========================
        	[RCFile,RCPath,RCFilePath]=GetFileNameOfMat(RCFileMat,FileIndex);
	 	[RCFilePath,RCEndPos] = SaveData(ReacCondVec',RCFilePath,1,[],'ascii','ascii',[],[],[],1,1,0);
		[RCFilePath,RCEndPos] = SaveData(ReacTrigPointVec',RCFilePath,1,[],'ascii','ascii',1,RCEndPos,[],1,1,0);
		[RCFilePath,RCEndPos] = SaveData(ReacTrigTimeVec',RCFilePath,1,[],'ascii','ascii',1,RCEndPos,[],1,1,0);

                 %============Save reaction time to file==========================
        	[RTFile,RTPath,RTFilePath]=GetFileNameOfMat(RTFileMat,FileIndex);
	 	SaveData(ReacTrigTimeVec'-NoReacTrigTimeVec',RTFilePath,1,[],'ascii','ascii');

        
		%=========EGIS Header======================
	
		HdrVer=Version;
		LData=NNetPoints.*NChan;
		LHeader=[];
		RunDate=[Day,Month,Year];
		RunTime=[Hour,Minute,Sec];			
		EdVer=Version;
		LText=Bits;				%Muss noch geaendert werden
		LPad=Range;				%Muss noch geaendert werden
		NTrials=length(NoReacTrigPointVec);
		NPoints=DistTrig;
		LSpec=4;
		LSpecCell1=zeros(NTrials,LSpec./2);
		LCellHdr=NCells.*90+NTrials.*LSpec;   %2.*(LSpec./2)
		
		%==========================================
		
		LengthNetFilePath=length(NetFilePath);

		LSpecCell1(:,1)=-1.*ones(NTrials,1);
		LSpecCell1(:,2)=zeros(NTrials,1);
		EGISFileInd=FileIndex;
		EgisEventInd=1;
		
		[EGISFile,EGISPath,EGISFilePath]=GetFileNameOfMat(EGISFileMat,FileIndex);
		WriteEGISHeader(EGISFilePath);
		EGISFid=fopen(EGISFilePath,'r+');
		fseek(EGISFid,LHeader,-1);
		fprintf(1,'Write %g trials to file:\n\n',NTrials)
	
		for TrialInd=1:NTrials
			fprintf(1,'%g\n',TrialInd)
			if TRStatus==1										%RAW
				status=fseek(NetFid,LNetHeader+(NChan+NNetEvents).*(NoReacTrigPointVec(TrialInd)-PreTrig-1).*2,-1);
				if status==-1; error('fseek error'); end
				Tmp=fread(NetFid,[NChan+NNetEvents,DistTrig(EgisEventInd)],'int16');
				Tmp=Tmp(1:NChan,:);
				fwrite(EGISFid,Tmp,'int16'); 
			elseif TRStatus==-1									%TAW
				Tmp=zeros(DistTrig(EgisEventInd),NChan);
				status=fseek(NetFid,LNetHeader+(NoReacTrigPointVec(TrialInd)-PreTrig-1).*2,-1);
				if status==-1; error('fseek error'); end
				for ChanInd=1:NChan	
					Tmp(:,ChanInd)=fread(NetFid,DistTrig(EgisEventInd),'int16');
					if ChanInd~=NChan
						SeekStatus=fseek(NetFid,(NNetPoints-DistTrig(EgisEventInd)).*2,0);
						if SeekStatus==-1; error('fseek error'); end
					end
				end
				fwrite(EGISFid,Tmp','int16'); 	
			end
		end
		fclose(EGISFid);
	end	%if AllTrigVec(EgisEventInd)~=0
	fclose(NetFid);
end	%FileIndex
return;
