function[MsiFilePath,SetFilePath,SesFilePath,AvgFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec]=
TransMsiContSessIAPS(MsiFilePath,PreTrig,PostTrig,ReTrig,MinNTrigPoints,NStep,NDefTrig)
%	TransMsiContSessIAPS.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.  

global AvgDataMat
if nargin<7; NDefTrig=[]; end;
if nargin<6; NStep=[]; end;
if nargin<5; MinNTrigPoints=1; end;
if nargin<4; ReTrig=1; end;
if nargin<3; PostTrig=100; end;
if nargin<2; PreTrig=0; 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,'*.msi');
[MsiFile,MsiPath,MsiFilePath]=ReadFilePath(MsiFilePath,DefPath,String);
SetDefPath(2,MsiPath);
if MsiFile==0; MsiFilePath=[]; return; end

SetFilePath=PutFileExt2Mat(MsiFilePath,'.set');
SesFilePath=PutFileExt2Mat(MsiFilePath,'.ses.msi',4);
AvgFilePath=PutFileExt2Mat(MsiFilePath,'.avg.msi',4);

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;
else
	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 average MSI to file:');
	Message=char(Message,[AvgFilePath]);
	Message=char(Message,'');
	hmsgbox=msgbox(Message,'Info','help'); 
	pause(.01);
end

[SetFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec,MsiFormat]=ReadMsiSet(SetFilePath);

NTotChan=ParaVec(1);
NMsiPoints=ParaVec(2);
NTrials=ParaVec(3);
NMegChan=ParaVec(4);
NEegChan=ParaVec(8);
SampRate=ParaVec(5);
SampPeriod=ParaVec(6);
BaseMs=ParaVec(7);
NMEegChan=NMegChan+NEegChan;
MEegSensorIndexVec=zeros(NMEegChan,1);
MEegSensorIndexVec(1:NMegChan)=MEGSensorIndexVec;
MEegSensorIndexVec(NMegChan+1:NMEegChan)=EEGSensorIndexVec;

TrigChan=1;
NSeek=NTotChan.*4;
MsiFid=fopen(MsiFilePath,'r','b');

TrigVec=zeros(NMsiPoints+1,1);
TrigVec(1)=-1;
TrigInd=1;
TrigStatus=0;
PointInd=0;
while PointInd<NMsiPoints
	PointInd=PointInd+1;
	[DataVec,Count]=fread(MsiFid,NTotChan,MsiFormat);
	if Count==NTotChan;
		if DataVec(TrigChan)>4
			TrigInd=TrigInd+1;
			TrigVec(TrigInd)=PointInd;
			if (NMsiPoints-PointInd)>MinNTrigPoints
				status=fseek(MsiFid,NTotChan.*MinNTrigPoints.*4,0);
				PointInd=PointInd+MinNTrigPoints;
			else
				PointInd=NMsiPoints;
			end
		end
	else
		NMsiPoints=PointInd-1;
		break;
	end
end
TrigVecA=TrigVec(2:TrigInd);
NTrig=length(TrigVecA)
TrigVecB=TrigVecA-DistTrig./2;
TrigVec=zeros(NTrig.*2,1);
TrigVec(1:NTrig)=TrigVecA;
TrigVec(NTrig+1:2.*NTrig)=TrigVecB;
CondVec=ones(NTrig.*2,1);
CondVec(NTrig+1:2.*NTrig)=2.*ones(NTrig,1);
NTrig=2.*NTrig;
TrigStatusVec=ones(NTrig,1);
%=====Alle trigger, die kleiner sind als pretrigger fallen raus===================
BadIndexVec=[];
BadIndexVec=find(TrigVec<PreTrig);
if ~isempty(BadIndexVec); 
	TrigStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
end
if ~ReTrig
	for TrigInd=2:NTrig
		if TrigVec(TrigInd)-TrigVec(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-TrigVec<=PostTrig);
if ~isempty(BadIndexVec); 
	TrigStatusVec(BadIndexVec)=zeros(size(BadIndexVec)); 
end
TrigStatusVec(BadIndexVec)=zeros(size(BadIndexVec));
		
OkTrigIndVec=find(TrigStatusVec==1);
NTrig=length(OkTrigIndVec);

TrigVec=TrigVec(OkTrigIndVec);
CondVec=CondVec(OkTrigIndVec);
TimeMsVec=(TrigVec-1).*1000./SampRate;

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(TrigVec)
	Diff=TrigVec(i)-TrigVec(i-1);
	DiffVec(i-1)=Diff;
end
fprintf(1,'Trigger Vector:\n\n')
disp(TrigVec')
fprintf(1,'\n\n')
fprintf(1,'Distance Vector:\n\n')
disp(DiffVec)

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

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

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);
AvgDataMat=zeros(NSessChan,DistTrig);
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=TrigVec(TrigInd);
	status=fseek(MsiFid,(ActTrigPoint-PreTrig-1).*NTotChan.*NBit,-1);
	DataMat=fread(MsiFid,[NTotChan,DistTrig],MsiFormat);
	DataMat=DataMat(MEegSensorIndexVec,:);
	fwrite(SesFid,DataMat,'float');
	AvgDataMat=AvgDataMat+DataMat;
end	
fclose(MsiFid);
fclose(SesFid);
AvgDataMat=AvgDataMat./NTrig;
AvgFid=fopen(AvgFilePath,'w','b');
fwrite(AvgFid,AvgDataMat,'float');
fclose(AvgFid);
return;
