function[EGISFileMat,NetFileMat,CondFileMat]=TransNetGeoHistNew(NetFileMat,TRStatus,
PreTrig,PostTrig,ReTrig,GainFilePath,ZeroFilePath,OldZeroVersion,
NGainZeroString,SpecCondVec,NStep,NDefTrials,SimpleTrig,DSample,DMeanSampleStatus,IntTrig)
%   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.                                                                      
%==================================================================
%
%	TransNetGeoHistAudite.m
%
%	Markus Junghoefer	[2003]
%
%
%	Function definition
%
%	function[EGISFileMat,NetFileMat]=TransNetGeoHistTmp(NetFileMat,TRStatus,...
% 	PreTrig,PostTrig,ReTrig,GainFilePath,ZeroFilePath,OldZeroVersion,...
%   NGainZeroString,SpecCondVec,NStep,NDefTrials,SimpleTrig,DSample,DMeanSampleStatus)
%
%	DSample gives the number of points to downsample
%	DSample =[] or DSample=0 or DSample=1 result in no downsampling
%	Using DSample=2 every other value (1,3,5,7...) will be taken (if DMeanSampleStatus=0)
%	if DMeanSampleStatus=1 the program takes the mean of the 1st and 2nd, 3rd and 5th etc.
%	SampRate is therefore the od SampRate divided by the DSampleValue
%	Take DSample=2 to sample down from 500 to 250 Hz or 250 to 125 Hz
%	Take DSample=4 to sample down from 500 to 125 Hz
%==================================================================
if nargin<16; IntTrig=[]; end;
if nargin<15; DMeanSampleStatus=0; end;
if nargin<14; DSample=[]; end;
if nargin<13; SimpleTrig=[]; end;
if nargin<12; NDefTrials=[]; end;
if nargin<11; NStep=[]; end;
if nargin<10; SpecCondVec=[]; end;
if nargin<9; NGainZeroString=[]; end;
if nargin<8; OldZeroVersion=0; end;
if nargin<7; ZeroFilePath=[]; end;
if nargin<6; GainFilePath=[]; end;
if nargin<5; ReTrig=[]; end;
if nargin<4; PostTrig=[]; end;
if nargin<3; PreTrig=[]; end;
if nargin<2; TRStatus=[]; end;
if nargin<1; NetFileMat=[]; end;
%==================================================================
if ~isempty(TRStatus)
	if abs(TRStatus)-1~=0; error('Bad TRStatus'); end
end	
if ~isempty(DSample); 
	DSample=round(DSample);
	if DSample<2
		fprintf(1,'DSample<2 does not result in any down sampling !');
		hmsgbox=msgbox('DSample<2 does not result in any down sampling !','Warning:','help')
		pause(3)
		DSample=0;
		DSampleStatus=0;
	else	
		DSampleStatus=1; 
	end
else
	DSampleStatus=0;
end

if isempty(NetFileMat)
	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,NetFileMat]=ReadFileNames(NetFileMat,Mask,'Choose NetStation file:');
	if NFiles==0; return; end
else
	NFiles=size(NetFileMat,1);
end
[EGISFileMat]=FileNameExt2Mat(NetFileMat,'E1',3);
[CondFileMat]=FileNameExt2Mat(EGISFileMat,'.CON');

%=========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 NetFileIndex=1:NFiles
	
    [NetFile,NetPath,NetFilePath]=GetFileNameOfMat(NetFileMat,NetFileIndex);
	LNetFile=length(NetFile);
	if LNetFile<5; error('Unknown Net format'); end
	if strcmp(NetFile(LNetFile-2:LNetFile),'RAW')
		TRStatus=1;
	elseif strcmp(NetFile(LNetFile-2:LNetFile),'TAW')
		TRStatus=-1;
	else
		error('Unknown Net format');
	end
	fprintf('\n')
	fprintf('TransNetGeoTrig\n')
	disp(NetFilePath)
	fprintf('\n')
	clc;
	fprintf('Start reading data file...\n\n');
	disp(NetFilePath);
	fprintf('\n\n');

	NetFid=fopen(NetFilePath,'r','b');
	%=========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;

	if isempty(GainFilePath) 
		if isempty(NGainZeroString)
			a=findstr(NetFile,'.fl');	%filtered data
			b=findstr(NetFile,'.fh');	%filtered data
			c=inf; d=inf;
			if ~isempty(a)
				c=a(1);
			end
			if ~isempty(b)
				d=b(1);
				if d<c; 
					c=d;
				end
			end
			if c<inf
				GainFilePath=[NetPath,NetFile(1:c) 'Gain'];
			else
				GainFilePath=[NetPath,NetFile(1:LNetFile-3) 'Gain'];
			end
		else
			GainFilePath=[NetPath,NetFile(1:NGainZeroString) '.Gain'];
		end
	end
	if isempty(ZeroFilePath) 
		if isempty(NGainZeroString)
			a=findstr(NetFile,'.fl');	%filtered data
			b=findstr(NetFile,'.fh');	%filtered data
			c=inf; d=inf;
			if ~isempty(a)
				c=a(1);
			end
			if ~isempty(b)
				d=b(1);
				if d<c; 
					c=d;
				end
			end
			if c<inf
				ZeroFilePath=[NetPath,NetFile(1:c) 'Zero'];
			else
				ZeroFilePath=[NetPath,NetFile(1:LNetFile-3) 'Zero'];
			end
		else
			ZeroFilePath=[NetPath,NetFile(1:NGainZeroString) '.Zero'];
		end
	end
	[ChanGain,ChanZero,...
	GainYear,GainMonth,GainDay,GainHour,GainMinute,GainSec,GainMSec,...
	ZeroYear,ZeroMonth,ZeroDay,ZeroHour,ZeroMinute,ZeroSec,ZeroMSec]=...
	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('Number of trigger channels in this file : %g\n\n',NNetEvents); again=0;
		fprintf('End reading data header...\n');
		pause(.5)
		%===============================================================================
		if LNetFile>4
			Index=1;
			while ~strcmp(NetFile(Index:Index+1),'.f') & Index<LNetFile-1 %filtered data	
				Index=Index+1;
			end
			if Index<LNetFile-1
				HistFilePath=[NetPath,NetFile(1:Index) 'HIST'];
			else
				HistFilePath=[NetPath,NetFile(1:LNetFile-3) 'HIST'];
			end
		else
			HistFilePath=[NetPath,NetFile(1:LNetFile-3) 'HIST'];
		end
        
		[HistFile,HistPath,HistFilePath]=ReadFilePath(HistFilePath,'*.HIST',['Choose the HIST file:']);
		fprintf('\n\n')
        fprintf('Open file:\n')
        disp(HistFilePath)
        HistFid=fopen(HistFilePath,'r','b');
		
		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 %g in file:\n',TimeMsStart)
			disp(NetFilePath)
			fprintf('\n')
			fprintf('differs from start time %g in file:\n',StartMsTest)
			disp(HistFilePath)
			fprintf('\n\n')
			fprintf('Take start time from RAW file for further calculations:')
			pause(5)
		end
		
		Index=0;
		Tmp='Bloedsinn';
		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;
		TrigBitMat=zeros(NTrigEvents,4);
		fseek(HistFid,Tell1,'bof');
        NNetEventNames=0;
		
		for TrigIndex=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);
	        NewEventName=1;
   		    for NetEventNameIndex=1:NNetEventNames 
   	           	NetEventNameTmp=deblank(NetEventNameMat(NetEventNameIndex,:));
              	if strcmp(Tmp5,NetEventNameTmp)
                	 NewEventName=0;
              	end
            end
          	if NewEventName
  	           NNetEventNames=NNetEventNames+1;
 	        end          
            if TrigIndex==1
               	TrigDateTimeMat=char(Tmp1);
               	TrigCodeMat=char(Tmp5);
            else
               	TrigDateTimeMat=char(TrigDateTimeMat,Tmp1);
               	TrigCodeMat=char(TrigCodeMat,Tmp5);
            end
            if NewEventName
            	if NNetEventNames==1
                 	NetEventNameMat=char(Tmp5);
                else
                    NetEventNameMat=char(NetEventNameMat,Tmp5);
                end
           	end
        end
        fclose(HistFid);
		%==================
		DinNameStatus=1;
		for NetEventNameIndex=1:NNetEventNames
			NetEventNameTmp=deblank(NetEventNameMat(NetEventNameIndex,:));
			a=findstr(NetEventNameTmp,'DIN1');
			b=findstr(NetEventNameTmp,'DIN2');
			c=findstr(NetEventNameTmp,'DIN3');
			d=findstr(NetEventNameTmp,'DIN4');
			if isempty(a) & isempty(b) & isempty(c) & isempty(d)
				DinNameStatus=0;
			end
		end
		if DinNameStatus
			for NetEventNameIndex=1:NNetEventNames
				NetEventNameTmp=deblank(NetEventNameMat(NetEventNameIndex,:));
				a=findstr(NetEventNameTmp,'DIN1');
				if ~isempty(a)
					NetEventNameMat(NetEventNameIndex,1:4)='DIN1';
					for TrigIndex=1:NTrigEvents
						TrigCodeTmp=deblank(TrigCodeMat(TrigIndex,:));
						aa=findstr(TrigCodeTmp,'DIN1');
						if ~isempty(aa)
							TrigCodeMat(TrigIndex,1:4)='DIN1';
						end
					end
				end
				b=findstr(NetEventNameTmp,'DIN2');
				if ~isempty(b)
					NetEventNameMat(NetEventNameIndex,1:4)='DIN2';
					for TrigIndex=1:NTrigEvents
						TrigCodeTmp=deblank(TrigCodeMat(TrigIndex,:));
						bb=findstr(TrigCodeTmp,'DIN2');
						if ~isempty(bb)
							TrigCodeMat(TrigIndex,1:4)='DIN2';
						end
					end
				end
				c=findstr(NetEventNameTmp,'DIN3');
				if ~isempty(c)
					NetEventNameMat(NetEventNameIndex,1:4)='DIN3';
					for TrigIndex=1:NTrigEvents
						TrigCodeTmp=deblank(TrigCodeMat(TrigIndex,:));
						cc=findstr(TrigCodeTmp,'DIN3');
						if ~isempty(cc)
							TrigCodeMat(TrigIndex,1:4)='DIN3';
						end
					end
				end
				d=findstr(NetEventNameTmp,'DIN4');
				if ~isempty(d)
					NetEventNameMat(NetEventNameIndex,1:4)='DIN4';
					for TrigIndex=1:NTrigEvents
						TrigCodeTmp=deblank(TrigCodeMat(TrigIndex,:));
						dd=findstr(TrigCodeTmp,'DIN4');
						if ~isempty(dd)
							TrigCodeMat(TrigIndex,1:4)='DIN4';
						end
					end
				end
			end		
			TrigCodeMat=TrigCodeMat(:,1:4);
		else
			Message=char('Attention !!!');
			Message=char(Message,'');
			Message=char(Message,'You are using event name(s) not containing substrings of');
			Message=char(Message,'DIN1, DIN2, DIN3 or DIN4');
			Message=char(Message,'');
			Message=char(Message,'The program has no information about the digital input number');
			Message=char(Message,'of the events. Conditions are numbered corresponding to the order');
			Message=char(Message,'of event name occurring in the history file. This order might');
			Message=char(Message,'change across sessions leading to confusing condition numbers.');
			Message=char(Message,'')
			hmsgbox=msgbox(Message,'Info','help'); 
		end
		%==================
		TrigMSVec=zeros(NTrigEvents,1);
		for Index1=1:NTrigEvents
			Tmp=TrigDateTimeMat(Index1,19)-48;									
			Tmp=Tmp+(TrigDateTimeMat(Index1,18)-48).*10;			
			Tmp=Tmp+(TrigDateTimeMat(Index1,17)-48).*100;		
			Tmp=Tmp+(TrigDateTimeMat(Index1,15)-48).*1000;	
			Tmp=Tmp+(TrigDateTimeMat(Index1,14)-48).*10000;
			Tmp=Tmp+(TrigDateTimeMat(Index1,12)-48).*60000;
			Tmp=Tmp+(TrigDateTimeMat(Index1,11)-48).*600000;
			Tmp=Tmp+(TrigDateTimeMat(Index1,9)-48).*3600000;
			Tmp=Tmp+(TrigDateTimeMat(Index1,8)-48).*36000000;
			TrigMSVec(Index1)=Tmp;
		end	
		if ~isempty(SimpleTrig)
			Index2=0;
			for Index1=1:NTrigEvents	
				Tmp=deblank(TrigCodeMat(Index1,:));
           	 	if strcmp(Tmp,SimpleTrig)
           	 		Index2=Index2+1;
					TimeMsVec(Index2)=TrigMSVec(Index1);
				end
			end
			NTrig=Index2;
			TimeMsVec=TimeMsVec-TimeMsStart.*ones(size(TimeMsVec)); 
			TrialVec=ceil(TimeMsVec./(1000./SampRate))';
			if strcmp(SimpleTrig(length(SimpleTrig)),'1')
				CondVec=16.*ones(NTrig,1);
			elseif strcmp(SimpleTrig(length(SimpleTrig)),'2')
				CondVec=17.*ones(NTrig,1);
			elseif strcmp(SimpleTrig(length(SimpleTrig)),'3')
				CondVec=18.*ones(NTrig,1);
			elseif strcmp(SimpleTrig(length(SimpleTrig)),'4')
				CondVec=19.*ones(NTrig,1);
			else 
				CondVec=99.*ones(NTrig,1);
			end
			fprintf('\n'); clc;
			fprintf('Total number of trigger: %g ',NTrig);
		else	%if isempty(SimpleTrig)
			[TrigMSVec,TrigMSInd]=sort(TrigMSVec);
			TrigCodeMat=TrigCodeMat(TrigMSInd,:);
			TmpOld=0;
			Index2=0;
			MaxDist=ceil(1000/SampRate);
			for Index1=1:NTrigEvents
				TmpNew=TrigMSVec(Index1);
				if 	Index1==1 | ((TmpNew-TmpOld)>MaxDist);
					Index2=Index2+1;
					TimeMsVec(Index2)=TmpNew;
					TmpOld=TmpNew;
				end
           	 	TrigCodeTmp=deblank(TrigCodeMat(Index1,:));
           	 	for NetEventNameIndex=1:NNetEventNames
					if ~DinNameStatus
               			NetEventNameTmp=deblank(NetEventNameMat(NetEventNameIndex,:));
		        		if strcmp(TrigCodeTmp,NetEventNameTmp)
			       			TrigBitMat(Index2,NetEventNameIndex)=1;
               			end
					else
						NetEventNameTmp=deblank(NetEventNameMat(NetEventNameIndex,:));
		        		if strcmp(TrigCodeTmp(length(TrigCodeTmp)),'1')
			       			TrigBitMat(Index2,1)=1;
						elseif strcmp(TrigCodeTmp(length(TrigCodeTmp)),'2')
							TrigBitMat(Index2,2)=1;
						elseif strcmp(TrigCodeTmp(length(TrigCodeTmp)),'3')
							TrigBitMat(Index2,3)=1;
						elseif strcmp(TrigCodeTmp(length(TrigCodeTmp)),'4')
							TrigBitMat(Index2,4)=1;
               			end
					end
            	end
			end
			NTrig=Index2;
			TimeMsVec=TimeMsVec-TimeMsStart.*ones(size(TimeMsVec)); 
			TrialVec=ceil(TimeMsVec./(1000./SampRate))';
			TrigBitMat=TrigBitMat(1:NTrig,:);
			fprintf('\n'); clc;
			fprintf(1,'Total number of trigger: %g ',NTrig);
			CondVec=zeros(NTrig,1);
			for Index=1:NTrig
				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
% 				[0 0 0 0]	=>	0
% 				[1 0 0 0]	=>	1
% 				[0 1 0 0]	=>	2
% 				[1 1 0 0]	=>	3
% 				[0 0 1 0]	=>	4
% 				[1 0 1 0]	=>	5
% 				[0 1 1 0]	=>	6
% 				[1 1 1 0]	=>	7
% 				[0 0 0 1]	=>	8
% 				[1 0 0 1]	=>	9
% 				[0 1 0 1]	=>	10
% 				[1 1 0 1]	=>	11
% 				[0 0 1 1]	=>	12
% 				[1 0 1 1]	=>	13
% 				[0 1 1 1]	=>	14
% 				[1 1 1 1]	=>	15
			end
		end
		[PreTrig]  =IfEmptyInputValInt(['Please insert the'],['pre trigger intervall:'],PreTrig,25,-(NNetPoints-1),NNetPoints-1,1);
		[PostTrig]=IfEmptyInputValInt(['Please insert the'],['post trigger intervall:'],PostTrig,100,-(NNetPoints-PreTrig),NNetPoints-PreTrig);
        [ReTrig]=IfEmptyInputBo(['Do you want to use retrigger ?'],...
		['(if retrigger = "Yes" the distance between two trigger can be smaller than Pre+Posttrigger)'],ReTrig,0);
		
		DistTrig=PreTrig+PostTrig+1
		TrialStatusVec=ones(length(TrialVec),1);
		%=====Extract trigger < pretrigger===============================================
        BadIndexVec=[];
		BadIndexVec=find(TrialVec<PreTrig);
        TrialVec=TrialVec
		if ~isempty(BadIndexVec); 
			TrialStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
		end
		%=====If ~Retrig extract trigger(i+1)-trigger(i) < disttrigger===================
		if ~ReTrig
			for TrialInd=2:length(TrialVec)
				if TrialVec(TrialInd)-TrialVec(TrialInd-1)<DistTrig
                    TrialStatusVec(TrialInd)=0; 
                    TrialStatusVec(TrialInd-1)=0;
               end
			end
        end
		%=====Extract trigger > posttrigger==============================================
        BadIndexVec=[];
		BadIndexVec=find(NNetPoints-TrialVec<=PostTrig);
		if ~isempty(BadIndexVec); 
			TrialStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
		end
		TrialStatusVec(BadIndexVec)=zeros(size(BadIndexVec));
		
		OkTrialsIndVec=find(TrialStatusVec==1);
		NTrials=length(OkTrialsIndVec);
		CondVec=CondVec(OkTrialsIndVec);
		TrialVec=TrialVec(OkTrialsIndVec);
		TimeMsVec=TimeMsVec(OkTrialsIndVec);
		if ~isempty(SpecCondVec)
			SpecCondIndex=0;
			for TrialInd=1:NTrials
				if ~isempty(find(SpecCondVec==CondVec(TrialInd)))
					SpecCondIndex=SpecCondIndex+1;
					SpecCondTrialsIndVec(SpecCondIndex)=TrialInd;
				end
			end
			CondVec=CondVec(SpecCondTrialsIndVec);
			TrialVec=TrialVec(SpecCondTrialsIndVec);
			TimeMsVec=TimeMsVec(SpecCondTrialsIndVec);
			NTrials=length(SpecCondTrialsIndVec);
		end
		if ~isempty(NStep)
			TakeVec=[1:NStep:NTrials];
			CondVec=CondVec(TakeVec);
			TrialVec=TrialVec(TakeVec);
			TimeMsVec=TimeMsVec(TakeVec);
			NTrials=length(TakeVec);
		end	
		if ~isempty(NDefTrials)
			if NDefTrials~=NTrials
				Message=char('Warning: ');
				Message=char(Message,'');
				Message=char(Message,'File:');
				Message=char(Message,NetFilePath);
				Message=char(Message,'');
				Message=char(Message,['The number of trials to save (' int2str(NTrials) ') does not']);
				Message=char(Message,['agree with the default number of trials (' int2str(NDefTrials) ') !']);
				hmsgbox=msgbox(Message,'Warning','warn'); 
			end
		end
		TrialFig=figure('Units','normal','Position',[.6 0 .4 .5],'Name',['Trigger (n=',int2str(NTrials),') Info of File: ',NetFile],'NumberTitle','off');
		subplot(2,1,1)
		plot(TrialVec)
		axis([1 NTrials .9.*min(TrialVec) 1.1.*max(TrialVec)])		
        title('Trigger Vector')
		xlabel('Trigger #')
		ylabel('Time Point []')
		Index1=0;
		Index2=0;
		for i=2:length(TrialVec)
			Diff=TrialVec(i)-TrialVec(i-1);
			if Diff>10
				Index1=Index1+1;
				TestVec1(Index1)=Diff;
			end
		end
		subplot(2,1,2)
		plot(TestVec1)
 		axis([1 length(TestVec1) .9.*min(TestVec1) 1.1.*max(TestVec1)])
		title('Distance between Trigger')
		xlabel('Trigger #')
		ylabel('Distance Points []')
		fprintf('Number of trials to save: %g ',NTrials);	
        %======================================
        if ~isempty(IntTrig)
            CondVecTmp=zeros(NTrials.*IntTrig,1);
            TrialVecTmp=zeros(NTrials.*IntTrig,1);
            TimeMsVecTmp=zeros(NTrials.*IntTrig,1);
            NPoints=floor(DistTrig./IntTrig);
            for TrialInd=1:NTrials
                for IntInd=1:IntTrig
                    CondVecTmp((TrialInd-1).*IntTrig+IntInd)=CondVec(TrialInd);
                    TrialVecTmp((TrialInd-1).*IntTrig+IntInd)=TrialVec(TrialInd)+IntInd.*NPoints;
                    TimeMsVecTmp((TrialInd-1).*IntTrig+IntInd)=TimeMsVec(TrialInd)+IntInd.*NPoints.*1000./SampRate;
                end
            end
            CondVec=CondVecTmp;
            TrialVec=TrialVecTmp;
            TimeMsVec=TimeMsVecTmp;
            NTrials=NTrials.*IntTrig;
        end
		%============Save condition vector to file==========================		
        [CondFile,CondPath,CondFilePath]=GetFileNameOfMat(CondFileMat,NetFileIndex);
	 	[CondFilePath,CondEndPos] = SaveData(CondVec,CondFilePath,1,[],'ascii','ascii',[],[],[],1,1,0);
		[CondFilePath,CondEndPos] = SaveData(TrialVec,CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);
		[CondFilePath,CondEndPos] = SaveData(TimeMsVec',CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);

		%=========EGIS Header======================
		HdrVer=Version;
		LData=DistTrig.*NChan.*2;
		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(TrialVec)
		NPoints=DistTrig;
		LSpec=4;
		LSpecCell1=zeros(NTrials,LSpec./2);
		LCellHdr=NCells.*90+NTrials.*LSpec;   %2.*(LSpec./2)
		if DSampleStatus	
			NPoints=floor(DistTrig./DSample);
			LData=NPoints.*NChan.*2;
			SampRate=SampRate./DSample;
			if DMeanSampleStatus
				DSampleMat=zeros(DSample,NPoints);
				for SampleInd=1:DSample
					DSampleMat(SampleInd,:)=[1+SampleInd-1:DSample:NPoints.*DSample+SampleInd-1];
				end
			else
				DSampleVec=[1:DSample:NPoints.*DSample];
			end
		end
		%==========================================
		LengthNetFilePath=length(NetFilePath);
		LSpecCell1(:,1)=-1.*ones(NTrials,1);
		LSpecCell1(:,2)=zeros(NTrials,1);
		
        [EGISFile,EGISPath,EGISFilePath]=GetFileNameOfMat(EGISFileMat,NetFileIndex);
		[EGISFile,EGISPath,EGISFilePath]=WriteEGISHeader(EGISFilePath);
		EGISFid=fopen(EGISFilePath,'r+','b');
		fseek(EGISFid,LHeader,-1);
		fprintf(1,'Write %g trials of %g channels and %g points to file:\n\n',NTrials,NChan,NPoints);
		if TRStatus==-1									%TAW
			TmpRead=zeros(DistTrig,NChan);
		end
		for TrialInd=1:NTrials
			fprintf(1,'%g\n',TrialInd)
			if TRStatus==1										%RAW
				status=fseek(NetFid,LNetHeader+(NChan+NNetEvents).*(TrialVec(TrialInd)-PreTrig-1).*2,-1);
				if status==-1; error('fseek error'); end
				TmpRead=fread(NetFid,[NChan+NNetEvents,DistTrig],'int16');
				TmpWrite=TmpRead(1:NChan,:);
			elseif TRStatus==-1									%TAW
				status=fseek(NetFid,LNetHeader+(TrialVec(TrialInd)-PreTrig-1).*2,-1);
				if status==-1; error('fseek error'); end
				for ChanInd=1:NChan
					TmpRead(:,ChanInd)=fread(NetFid,DistTrig,'int16');
					if ChanInd<NChan
						SeekStatus=fseek(NetFid,(NNetPoints-DistTrig).*2,0);
						if SeekStatus==-1; error('fseek error'); end
					end
				end
				TmpWrite=TmpRead';
			end
			if DSampleStatus
				if DMeanSampleStatus
					Tmp=TmpWrite(:,DSampleMat(1,:));
					for SampleInd=2:DSample
						Tmp=Tmp+TmpWrite(:,DSampleMat(SampleInd,:));
					end	
					TmpWrite=Tmp./DSample;
				else
					TmpWrite=TmpWrite(:,DSampleVec);
				end
			end
			fwrite(EGISFid,TmpWrite,'int16'); 
		end
		fclose(EGISFid);
	end	%if AllTrigVec~=0
	fclose(NetFid);
end	%NetFileIndex
return;
