function[MsiFilePath,SetFilePath,SesFilePath,AvgFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec]=
TransMsiContSess(MsiFilePath,PreTrig,PostTrig,ReTrig,SpecCondVec,NStep,NDefTrig)
%   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.                                                                      
%==================================================================
%
%	TransMsiContSess.m
%
%	Markus Junghoefer	[2000]
%
%
%	
%	Function definition	
%=================================================================
if nargin<7; NDefTrig=[]; end;
if nargin<6; NStep=[]; end;
if nargin<5; SpecCondVec=[]; end;
if nargin<4; ReTrig=1; end;
if nargin<3; PostTrig=271; end;
if nargin<2; PreTrig=136; 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);
if MsiFile==0; return; end
SetDefPath(2,MsiPath);
if MsiFile==0; MsiFilePath=[]; return; end

%=================Rename MSI files
SetFilePath=PutFileExt2Mat(MsiFilePath,'.set');
SesFilePath=PutFileExt2Mat(MsiFilePath,'.ses.msi',4);
SesSetFilePath=PutFileExt2Mat(SesFilePath,'.set');
AvgFilePath=PutFileExt2Mat(MsiFilePath,'.avg.msi',4);
AvgSetFilePath=PutFileExt2Mat(AvgFilePath,'.set');
PmgSetFilePath=PutFileExt2Mat(MsiFilePath,'.pmg');

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 session MSI set to file:');
	Message=char(Message,[SesSetFilePath]);
	Message=char(Message,'');
	Message=char(Message,'Write average MSI to file:');
	Message=char(Message,[AvgFilePath]);
	Message=char(Message,'');
	Message=char(Message,'Write average MSI set to file:');
	Message=char(Message,[AvgSetFilePath]);
	Message=char(Message,'');
    Message=char(Message,'Write sensor configuration to pmg file:');
	Message=char(Message,[PmgSetFilePath]);
	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;
global TrigVec
TrigChan=NTotChan-1;
TrigVec=zeros(NMsiPoints,1);
TrigCodeOld=0;
TrigCodeNew=0;
MsiFid=fopen(MsiFilePath,'r','b');

fprintf(1,'\n\n');
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
	TrigCodeOld=TrigCodeNew;
	TrigCodeNew=DataVec(TrigChan);
	if TrigCodeNew~=TrigCodeOld & TrigCodeNew>0
		TrigVec(PointInd)=TrigCodeNew;
	end
end

TrigVecInd=find(TrigVec);
CondVec=TrigVec(TrigVecInd);
NTrig=length(CondVec)
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<=PostTrig);
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;
	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)

TrigFig=figure('Units','normal','Position',[.6 0 .4 .5],'Name',['Trigger (n=',int2str(NTrials),') Info of File: ',MsiFile],'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([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(TrigVecInd,CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);
[CondFilePath,CondEndPos] = SaveData(TimeMsVec,CondFilePath,1,[],'ascii','ascii',1,CondEndPos,[],1,1,0);
%============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:');
KeyWordFormat=['d','d','d','d','d','d'];
SesParaVec=[NMEegChan,NMEegChan,NTrig,DistTrig,DistTrig,0];
[ParaVecOld,NewSetFilePath]=ChangeMsiSet(SetFilePath,SesSetFilePath,KeyWordMat,KeyWordFormat,SesParaVec);
AvgParaVec=[NMEegChan,NMEegChan,1,DistTrig,DistTrig,0];
[ParaVecOld,NewSetFilePath]=ChangeMsiSet(SetFilePath,AvgSetFilePath,KeyWordMat,KeyWordFormat,AvgParaVec);
%============Save pmg set to file=======================
WritePmgSet(SetFilePath);
%============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);
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=TrigVecInd(TrigInd);
	status=fseek(MsiFid,(ActTrigPoint-PreTrig-1).*NTotChan.*NBit,-1);
	DataMat=fread(MsiFid,[NTotChan,DistTrig],'float');
	DataMat=DataMat(MEegSensorIndexVec,:);
	fwrite(SesFid,DataMat,'float');
	AvgDataMat=AvgDataMat+DataMat;
end	
fclose(MsiFid);
fclose(SesFid);
%============Save averaged file==========================
AvgDataMat=AvgDataMat./NTrig;
AvgFid=fopen(AvgFilePath,'w','b');
fwrite(AvgFid,AvgDataMat,'float');
fclose(AvgFid);
return;
