function[MsiFilePath,SetFilePath,SesFilePath,AvgFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec]=
TransMsiContSessFastWordTrig(MsiFilePath,MsiFilePathTmp,PreTrig,PostTrig,ReTrig,SpecCondVec,NStep,NDefTrig,Session)

%	TransMsiContSessFastWordTrig.m

%   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<9; Session=[]; end;
if nargin<8; NDefTrig=[]; end;
if nargin<7; NStep=[]; end;
if nargin<6; SpecCondVec=[]; end;
if nargin<5; ReTrig=1; end;
if nargin<4; PostTrig=500; end;
if nargin<3; PreTrig=99; end;
if nargin<2; MsiFilePathTmp=[]; end
if nargin<1; MsiFilePath=[];end

DistTrig=PreTrig+PostTrig+1;

MsiMat=[];
MEGSensorPosMat=[];
ParaVec=[];
MEGSensorNameVec=[];
MEGSensorIndexVec=[];
SetFilePath=[];
SesFilePath=[];
AvgFilePath=[];

String='Choose MSI file:';
[DefPath]=SetDefPath(1,'*');
[MsiFile,MsiPath,MsiFilePath]=ReadFilePath(MsiFilePath,DefPath,String);
if MsiFile==0; return; end
if ~isempty(findstr(MsiFile,',f'))
    FilterFlag=1;
else
    FilterFlag=0;
end
SetDefPath(2,MsiPath);
if MsiFile==0; MsiFilePath=[]; return; end
SetFilePath=PutFileExt2Mat(MsiFilePathTmp,'.set');
if exist(SetFilePath,'file')~=2
	Message=char('Sorry,');
	Message=char(Message,'unable to find MSI set file:');
	Message=char(Message,'');
	Message=char(Message,[SetFilePath]);
	Message=char(Message,'');
	hmsgbox=msgbox(Message,'Info','help'); 
	return;
end
[SetFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,...
 EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec,MsiFormat,MSIChannelOrderVec,...
 MsiPatient,MsiScan,MsiSession,MsiRun,...
 ExternSensorNameVec,ExternSensorIndexVec]=ReadMsiSet(SetFilePath);
SesFilePath=PutFileExt2Mat(MsiFilePathTmp,'.ses');
[SesFile,SesPath]=SepFilePath(SesFilePath);
SesSetFilePath=PutFileExt2Mat(SesFilePath,'.set');
[SesSetFile,SesSetPath]=SepFilePath(SesSetFilePath);

Message=char('Read MSI data from file:');
Message=char(Message,[MsiFilePath]);
Message=char(Message,'');
Message=char(Message,'Read MSI set from file:');
Message=char(Message,[SetFilePath]);
Message=char(Message,'');
Message=char(Message,'Write session MSI to file:');
Message=char(Message,[SesFilePath]);
Message=char(Message,'');
Message=char(Message,'Write session MSI set to file:');
Message=char(Message,[SesSetFilePath]);
Message=char(Message,'');
hmsgbox=msgbox(Message,'Info','help'); 
pause(.01);

NTotChan=ParaVec(1);
NMsiPoints=ParaVec(2);
NTrials=ParaVec(3);
NMegChan=ParaVec(4);
NEegChan=ParaVec(5);
SampRate=ParaVec(6);
SampPeriod=ParaVec(7);
BaseMs=ParaVec(8);
Duration=ParaVec(9);
NBit=ParaVec(10)
NExternChan=ParaVec(11);
NMEegChan=NMegChan+NEegChan
MEegSensorIndexVec=zeros(NMEegChan,1);
MEegSensorIndexVec(1:NMegChan)=MEGSensorIndexVec;
MEegSensorIndexVec(NMegChan+1:NMEegChan)=EEGSensorIndexVec
NChanTmp=size(MSIChannelOrderVec,1);
TrigChan=0;
a=[];
while isempty(a) & TrigChan<NChanTmp
    TrigChan=TrigChan+1;
    a=findstr(MSIChannelOrderVec(TrigChan,:),'TRIGGER');
end
if isempty(a); 
    error('No TRIGGER channel in file');
end
global TmpVec TrigVec DiffVec MsiFilePath
TrigVec=zeros(NMsiPoints,1);
MsiFid=fopen(MsiFilePath,'r','b');
if MsiFid==-1
    error(['Can not open file: ',MsiFilePath])
end
fprintf('\n\n');
PointInd=0;
TmpVec=zeros(NMsiPoints,1);
DataOld=0;
Lim=1;
MsiFormat
NTotChan
NMsiPoints
for PointInd=1:NMsiPoints
	if round(PointInd./1000)==PointInd./1000
		fprintf(1,'%g of %g done ...\n',PointInd,NMsiPoints)
	end
	[DataVec,Count]=fread(MsiFid,NTotChan,MsiFormat);
	if Count~=NTotChan
		error('Count~=NTotChan')
    end
    DataNew=DataVec(TrigChan);
    TmpVec(PointInd)=DataNew;
	if DataNew>Lim & DataOld<Lim
		TrigVec(PointInd)=DataNew;
    end
    DataOld=DataNew;
end
TrigVecInd=find(TrigVec);
%TrigVecInd=TrigVecInd([2:301,303:602]);
for i=2:length(TrigVecInd)
	Diff=TrigVecInd(i)-TrigVecInd(i-1);
	DiffVec(i-1)=Diff;
end
TrigConVec=TrigVec(TrigVecInd);
TrigConVec=TrigConVec-min(TrigConVec);
TrigConVecTmp=TrigConVec;
i=0;
while ~isempty(TrigConVecTmp)
    i=i+1;
    ConVec(i)=TrigConVecTmp(1);
    NConVec(i)=length(find(TrigConVecTmp==ConVec(i)))
    TrigConVecTmp=TrigConVecTmp-ConVec(i);
    TrigConVecIndTmp=find(TrigConVecTmp);
    TrigConVecTmp=TrigConVecTmp(TrigConVecIndTmp);
end
ConVec=ConVec-min(ConVec)
NConVec=NConVec

fprintf(1,'Trigger Vector:\n\n')
disp(TrigVecInd')
fprintf(1,'\n\n')
fprintf(1,'Distance Vector:\n\n')
disp(DiffVec)
NTrig=length(TrigVecInd)
CondVec=TrigConVec;
TrigStatusVec=ones(NTrig,1);

%=====Alle trigger, die kleiner sind als pretrigger fallen raus===================
BadIndexVec=[];
BadIndexVec=find(TrigVecInd<PreTrig);
if ~isempty(BadIndexVec); 
	TrigStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
end
if ~ReTrig
	for TrigInd=2:NTrig
		if TrigVecInd(TrigInd)-TrigVecInd(TrigInd-1)<DistTrig
			TrigStatusVec(TrigInd)=0; 
			TrigStatusVec(TrigInd-1)=0;
		end
	end
end
%=====Alle trigger, die groesser sind als posttrigger fallen raus===================
BadIndexVec=[];
BadIndexVec=find(NMsiPoints-TrigVecInd<=3/2*PostTrig+1);
if ~isempty(BadIndexVec); 
	TrigStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
end
TrigStatusVec(BadIndexVec)=zeros(size(BadIndexVec));
		
OkTrigIndVec=find(TrigStatusVec==1);
NTrig=length(OkTrigIndVec);

TrigVecInd=TrigVecInd(OkTrigIndVec);
CondVec=CondVec(OkTrigIndVec);
TimeMsVec=(TrigVecInd-1).*1000./SampRate;
if ~isempty(SpecCondVec)
	SpecCondIndex=0;
    NTrig=NTrig
	for TrigInd=1:NTrig
		if ~isempty(find(SpecCondVec==CondVec(TrigInd)))
			SpecCondIndex=SpecCondIndex+1;
			SpecCondTrialsIndVec(SpecCondIndex)=TrigInd;
		end
	end
	CondVec=CondVec(SpecCondTrialsIndVec);
	TrigVecInd=TrigVecInd(SpecCondTrialsIndVec);
	TimeMsVec=TimeMsVec(SpecCondTrialsIndVec);
	NTrig=length(SpecCondTrialsIndVec);
end
if ~isempty(NStep)
	TakeVec=[1:NStep:NTrig];
	CondVec=CondVec(TakeVec);
	TrigVec=TrigVec(TakeVec);
	TimeMsVec=TimeMsVec(TakeVec);
	NTrig=length(TakeVec);
end			
if ~isempty(NDefTrig)
	if NDefTrig~=NTrig
		Message=char('');
		Message=char(Message,'File:');
		Message=char(Message,MsiFilePath);
		Message=char(Message,'');
		Message=char(Message,['The number of trials to save (' int2str(NTrig) ') does not']);
		Message=char(Message,['agree with the default number of trials (' int2str(NDefTrig) ') !']);
		Message=char(Message,'');
		hmsgbox=msgbox(Message,'Warning','warn'); 
	end
end
for i=2:length(TrigVecInd)
	Diff=TrigVecInd(i)-TrigVecInd(i-1);
	DiffVec(i-1)=Diff;
end
fprintf(1,'Trigger Vector:\n\n')
disp(TrigVecInd')
fprintf(1,'\n\n')
fprintf(1,'Distance Vector:\n\n')
disp(DiffVec)


%============Save condition vector to file==========================
[CondFilePath]=FileNameExt2Mat(SesFilePath,'.con');
		
[CondFilePath,CondEndPos] = SaveData(CondVec,CondFilePath,1,[],'ascii','ascii',[],[],[],1,1,0);
[CondFilePath,CondEndPos] = SaveData(TrigVecInd,CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);
[CondFilePath,CondEndPos] = SaveData(TimeMsVec,CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);

NTrig=length(TrigVecInd);

TrigFig=figure('Units','normal','Position',[.6 0 .4 .5],'Name',['Trigger (n=',int2str(NTrig),') Info of File: ',SesFile],'NumberTitle','off');
subplot(2,1,1)
plot(TrigVecInd)
axis([0 length(TrigVecInd) min(TrigVecInd) max(TrigVecInd)])
title('Trigger Vector')
xlabel('Trigger #')
ylabel('Time Point []')
subplot(2,1,2)
plot(DiffVec)
axis([1 length(DiffVec) 0 300])
title('Distance between Trigger')
xlabel('Trigger #')
ylabel('Distance Points []')
pause(.01)


%============Save ses and average set to file==========================
KeyWordMat=char('MSI.ChannelsPerSlice:');
KeyWordMat=char(KeyWordMat,'MSI.TotalChannels:');
KeyWordMat=char(KeyWordMat,'MSI.TotalEpochs:');
KeyWordMat=char(KeyWordMat,'MSI.SlicesPerEpoch:');
KeyWordMat=char(KeyWordMat,'MSI.TotalSlices:');
KeyWordMat=char(KeyWordMat,'MSI.RefChanCount:');
KeyWordMat=char(KeyWordMat,'MSI.ExternChanCount:');
KeyWordMat=char(KeyWordMat,'MSI.ChannelOrder:');
KeyWordMat=char(KeyWordMat,'MSI.ChannelLabels:');
KeyWordMat=char(KeyWordMat,'MSI.SigAChanIndex:');
KeyWordMat=char(KeyWordMat,'MSI.EEGChanIndex:');
KeyWordMat=char(KeyWordMat,'MSI.RefChanNames:');
KeyWordMat=char(KeyWordMat,'MSI.RefChanNumbers:');
KeyWordMat=char(KeyWordMat,'MSI.RefChanIndex:');
KeyWordMat=char(KeyWordMat,'MSI.ExternChanNames:');
KeyWordMat=char(KeyWordMat,'MSI.ExternChanNumbers:');
KeyWordMat=char(KeyWordMat,'MSI.ExternChanIndex:');

KeyWordFormat=['d','d','d','d','d','d','d','s','s','s','s','s','s','s','s','s','s'];

ChannelOrderStr='A1';
for ChanInd=2:NMegChan
    ChannelOrderStr=[ChannelOrderStr,',A',int2str(ChanInd)];
end
for ChanInd=29:28+NEegChan  
    ChannelOrderStr=[ChannelOrderStr,',E',int2str(ChanInd)];
end 
MegIndStr='0';
for ChanInd=1:NMegChan-1
    MegIndStr=[MegIndStr,',',int2str(ChanInd)];
end
EegIndStr=int2str(NMegChan+1-1);
for ChanInd=NMegChan+1:NMEegChan-1    
    EegIndStr=[EegIndStr,',',int2str(ChanInd)];
end 
StrMat=char(ChannelOrderStr);           %ChannelOrder
StrMat=char(StrMat,ChannelOrderStr);    %ChannelLabels
StrMat=char(StrMat,MegIndStr);          %SigAChanIndex
StrMat=char(StrMat,EegIndStr);          %EEGChanIndex
StrMat=char(StrMat,'');                 %RefChanNames
StrMat=char(StrMat,'');                 %RefChanNumbers
StrMat=char(StrMat,'');                 %RefChanIndex
StrMat=char(StrMat,'');                 %ExternChanNames
StrMat=char(StrMat,'');                 %ExternChanNumbers
StrMat=char(StrMat,'');                 %ExternChanIndex

fprintf(1,'\n\n')
fprintf(1,'Change set file:\n')
fprintf(1,SetFilePath)
fprintf(1,'\n')
fprintf(1,'and write set file:\n')
fprintf(1,SesSetFilePath)
SesParaVec=[NMEegChan,NMEegChan,NTrig,DistTrig,DistTrig,0,0];
[ParaVecOld,NewSetFilePath]=ChangeMsiSet(SetFilePath,SesSetFilePath,KeyWordMat,KeyWordFormat,SesParaVec,StrMat);

%============Save session file==========================
fprintf('Number of Trials to save: %g\n\n',NTrig);	
if strcmp(MsiFormat,'float');
	NBit=4;
elseif strcmp(MsiFormat,'short');
	NBit=2;
end
SesFid=fopen(SesFilePath,'w','b');
NSessChan=length(MEegSensorIndexVec);
fseek(MsiFid,0,-1);
fprintf(1,'Write %g trials of %g sensors and %g points to file:\n\n',NTrig,NSessChan,DistTrig)
for TrigInd=1:NTrig
	if round(TrigInd./10)==TrigInd./10	
		fprintf(1,'%g\n',TrigInd)
	else
		fprintf(1,'.')
	end
	ActTrigPoint=TrigVecInd(TrigInd);
	status=fseek(MsiFid,(ActTrigPoint-PreTrig-1).*NTotChan.*NBit,-1);
	DataMat=fread(MsiFid,[NTotChan,DistTrig],MsiFormat);
	DataMat=DataMat(MEegSensorIndexVec,:);
	fwrite(SesFid,DataMat,'float');
end	
fclose(MsiFid);
fclose(SesFid);
return;
