function[EGISFileMat,NetFileMat]=TransNetGeoHistIAPS(NetFileMat,TRStatus,...
PreTrig,PostTrig,ReTrig,GainFilePath,ZeroFilePath,OldZeroVersion,...
NGainZeroString,SpecCondVec,NStep,NDefTrials,SimpleTrig,DSample,DMeanSampleStatus,TrialDist)

%	TransNetGeoHist256.m
%
%	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

%   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<16; TrialDist=83; 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=1; end;
if nargin<1; NetFileMat=[]; end;
%==================================================================
if abs(TRStatus)-1~=0; error('Bad TRStatus'); 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
MatlabVersionString=version;
MainMatlabVersion=str2num(MatlabVersionString(1));

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
[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)
    str2num(NetFile(1:2))
    if str2num(NetFile(4:5))<7
        PreTrig=-12;	%0
        PostTrig=179;	%167
        TrialDist=83
        NDefTrials=200;
        TakeVec=ones(1,NDefTrials);
        TakeVec(1:100)=[9:108];
        TakeVec(101:200)=[117:216];
    elseif str2num(NetFile(4:5))>6 & str2num(NetFile(4:5))<9
        PreTrig=-12;	%0
        PostTrig=111;	%99
        TrialDist=50
        NDefTrials=200;
        TakeVec=ones(1,NDefTrials);
        TakeVec(1:100)=[11:110];
        TakeVec(101:200)=[121:220];
    end
	fprintf('\n')
	fprintf('TransNetGeoHistPeter\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 isempty(NGainZeroString)
			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
		else
			GainFilePath=[NetPath,NetFile(1:NGainZeroString) '.Gain'];
		end
	end
	if isempty(ZeroFilePath) 
		if isempty(NGainZeroString)
			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	
		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')
        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 %g in file:\n',TimeMsStart)
			fprintf(NetFilePath)
			fprintf('\n')
			fprintf('differs from start time %g in file:\n',StartMsTest)
			fprintf(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;
        if MainMatlabVersion<5
		  TrigDateTimeMat=zeros(NTrigEvents,NRowTrigDateTimeMat);
		  TrigCodeMat=zeros(NTrigEvents,6);
          NetEventNameMat=zeros(NNetEvents,6);
        end
		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 MainMatlabVersion<5
			    TrigDateTimeMat(TrigIndex,:)=Tmp1;
			    TrigCodeMat(TrigIndex,1:length(Tmp5))=Tmp5; 
                if NewEventName
					if NNetEventNames==1
						NetEventNameMat=Tmp5;
                	else	
						[MoUse,NCol]=size(NetEventNameMat);
					    NetEventNameMatTmp=zeros(NNetEventNames,max(length(Tmp5),NCol));						
						NetEventNameMatTmp(1:NNetEventNames-1,1:NCol)=NetEventNameMat;
                   		NetEventNameMat(NNetEventNames,1:length(Tmp5))=Tmp5;
					end
				end
            else
               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
        end
        fclose(HistFid);
		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,:));
				Tmp=Tmp(2:length(Tmp)-1);
           	 	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);
			NNotMaxDistTrig=0;
			for Index1=1:NTrigEvents
				TmpNew=TrigMSVec(Index1);
				if 	Index1==1 | ((TmpNew-TmpOld)>MaxDist);
					Index2=Index2+1;
					TimeMsVec(Index2)=TmpNew;
					TmpOld=TmpNew;
				else
					NNotMaxDistTrig=NNotMaxDistTrig+1;
				end
           	 	TrigCodeTmp=deblank(TrigCodeMat(Index1,:));
           	 	for NetEventNameIndex=1:NNetEventNames
               		 NetEventNameTmp=deblank(NetEventNameMat(NetEventNameIndex,:));
		        	if strcmp(TrigCodeTmp,NetEventNameTmp)
			       		TrigBitMat(Index2,NetEventNameIndex)=1;
               		end
            	end
			end
			NTrig=Index2;
% 			NNotMaxDistTrig=NNotMaxDistTrig
			TimeMsVec=TimeMsVec-TimeMsStart.*ones(size(TimeMsVec)); 
			TrialVec=ceil(TimeMsVec./(1000./SampRate))';
			TrigBitMat=TrigBitMat(1:NTrig,:);
			fprintf('\n'); clc;
			fprintf('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
			end
		end
		if ~isempty(TakeVec)
            CondVec=CondVec(TakeVec);
			TrialVec=TrialVec(TakeVec);
			TimeMsVec=TimeMsVec(TakeVec);
			NTrials=length(TakeVec);
        end
        
		[PreTrig]  =IfEmptyInputValInt(['Please insert the'],['pre trigger intervall:'],PreTrig,299,-(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);
		%=====Alle trigger, die kleiner sind als pretrigger fallen raus===================
        BadIndexVec=[];
		BadIndexVec=find(TrialVec<PreTrig);
		if ~isempty(BadIndexVec); 
			TrialStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
		end
		if ~ReTrig
			for TrialInd=2:length(TrialVec)
				if TrialVec(TrialInd)-TrialVec(TrialInd-1)<DistTrig
                    TrialStatusVec(TrialInd)=0; 
                    TrialStatusVec(TrialInd-1)=0;
               end
			end
        end
		%=====Alle trigger, die groesser sind als posttrigger fallen raus===================
        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
       
		%============Save condition vector to file==========================		
		CondVecTmp=zeros(length(CondVec)*2,1);
		CondVecTmp([1:2:length(CondVec)*2-1])=CondVec;
		CondVecTmp([2:2:length(CondVec)*2])=0*CondVec;
		CondVec=CondVecTmp;
		
		TrialVecTmp=zeros(length(CondVec),1);
		TrialVecTmp([1:2:length(CondVec)-1])=TrialVec;
		TrialVecTmp([2:2:length(CondVec)])=TrialVec+TrialDist;
		TrialVec=TrialVecTmp;
		
		TimeMsVecTmp=zeros(length(CondVec),1);
		TimeMsVecTmp([1:2:length(CondVec)-1])=TimeMsVec;
		TimeMsVecTmp([2:2:length(CondVec)])=TimeMsVec+TrialDist*1000/SampRate;
		TimeMsVec=TimeMsVecTmp;
		
        [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);

        NTrials=length(TrialVec);
        %========================================================================================================
		TrialFig=figure('Units','normal','Position',[.6 0 .4 .5],'Name',['Info about ',int2str(NTrials),' Trigger in 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;
        global DiffVec
		for i=2:length(TrialVec)
			Diff=TrialVec(i)-TrialVec(i-1);
			if Diff>10
				Index1=Index1+1;
				DiffVec(Index1)=Diff;
			end
		end
		subplot(2,1,2)
		plot(DiffVec)
 		axis([1 length(DiffVec) DiffVec(1)-2 DiffVec(1)+2])
		title('Distance between Trigger')
		xlabel('Trigger #')
		ylabel('Distance Points []')
        pause(.01)
		fprintf('Number of trials to save: %g ',NTrials);	

		%=========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)
		EGISFilePath=EGISFilePath
		[EGISFile,EGISPath,EGISFilePath]=WriteEGISHeader(EGISFilePath);
		EGISFid=fopen(EGISFilePath,'r+');
		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;
