function[OutFilePath,NormVec]=MergeAvgFiles(InFileMat,OutFilePath,chWeight,chNorm,DefFileMask)
%   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.                                                                      
%==================================================================
%
%	MergeAvgFiles.m
%
%	Markus Junghoefer	[1997]
%
%
%	Function definition
%
%
%
%==================================================================
if nargin<5; DefFileMask='*at*'; end;
if nargin<4; chNorm=[]; end;
if nargin<3; chWeight=[]; end;
if nargin<2; OutFilePath=[]; end;
if nargin<1; InFileMat=[]; end;

%==================================================================

[DefFilePath]=SetDefPath('r',DefFileMask);
[DefFile,DefPath]=SepFilePath(DefFilePath)
[DefPath]=SwitchGrandBatch(DefPath,'Grand2Batch',1);
DefFilePath=[DefPath,DefFile]
[NFiles,InFileMat,NonUse,BatchFilePath]=ReadFileNames(InFileMat,DefFilePath,'Choose avg files or batch file:');
if NFiles==0; OutFilePath=[]; return; end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath(2,BatchPath);

fprintf('\n\n');
[chWeight]=IfEmptyInputSpecVal(chWeight,[1 2 3],2,...
'Do you want to use',...
'no weighting                [1]',...
'trial number weighting      [2]',...
'Std matrix weighting        [3]');
fprintf('\n\n');

[chNorm]=IfEmptyInputSpecVal(chNorm,[1 2 3],1,...
'Do you want to use',...
'no normalization                     [1]',...
'mean Root Mean Square normalization  [2]',...
'mean Global Power normalization      [3]');

[PrintGPStatus]=IfEmptyInputBo('Print Global Power','for each file ?',[],0,1);

if chNorm>1
	NormVec=zeros(NFiles,1);
else
	NormVec=[];
end
OutFile=BatchFile;
Tmp=findstr(lower(OutFile),'batch.');
if ~isempty(Tmp)
	if Tmp==1 & length(OutFile)>5
		OutFile=OutFile(7:length(OutFile));
	elseif Tmp==length(OutFile)-4
		OutFile=OutFile(1:Tmp-1);
	else
		OutFile=OutFile(1:Tmp-1,Tmp+5:length(OutFile));
	end
end
Tmp=findstr(lower(OutFile),'batch');
if ~isempty(Tmp)
	if Tmp==1 & length(OutFile)>5
		OutFile=OutFile(7:length(OutFile));
	elseif Tmp==length(OutFile)-4
		OutFile=OutFile(1:Tmp-1);
	else
		OutFile=OutFile(1:Tmp-1,Tmp+5:length(OutFile));
	end
end
if length(OutFile)>4
	if strcmp(OutFile(1:4),'Bat.')
		OutFile=OutFile(5:length(OutFile));
	end
end
if length(OutFile)>3
	if strcmp(OutFile(1:3),'GM.')
		OutFile=OutFile(4:length(OutFile));
	end
end
if isempty(OutFilePath)
    [BatchPath]=SwitchGrandBatch(BatchPath,'Batch2Grand',1);
	[OutFile,OutPath,OutFilePath]=WriteFilePath([BatchPath,filesep,'GM.w',int2str(chWeight),'.n',int2str(chNorm),'.',OutFile],'Choose the new file name:');
else
    [OutFile,OutPath]=SepFilePath(OutFilePath);
end

if OutFile==0; fprintf(1,'Bad OutFilePath in MergeAvgFiles !'); return; end
if NFiles<2; return; end

for FileIndex=1:NFiles
	[File,Path,FilePath]=GetFileNameOfMat(InFileMat,FileIndex);
	[AvgMat,File,Path,FilePath,NTrialAvgVec,StdMat,...
	SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(FilePath);
	if PrintGPStatus
		MaxVec(FileIndex)=max(mean(sqrt(AvgMat.^2)));
	end
	if chNorm>1
		if chNorm==2
			Norm=mean(mean(sqrt(AvgMat.^2)));
		elseif chNorm==3
			Norm=mean(mean(AvgMat.^2));
		end
		AvgMat=AvgMat./Norm;
		NormVec(FileIndex)=Norm;
	end
	if FileIndex==1; 
		[NChan,NPoints]=size(AvgMat);
		if chWeight==1
			MergeAvgMat=AvgMat;
		elseif chWeight==2
			TotMaxNumberOfTrials=max(NTrialAvgVec);
			MergeAvgMat=TotMaxNumberOfTrials.*AvgMat;
		elseif chWeight==3
			InvMergeStdMat=1./StdMat;
			MergeAvgMat=AvgMat.*InvMergeStdMat; 
		end
		MergeStdMat=StdMat; 
		MergeNTrialAvgVec=NTrialAvgVec;
		MergeMedMedRawVec=MedMedRawVec;
		MergeMedMedAvgVec=MedMedAvgVec;
	else
		if chWeight==1
			MergeAvgMat=MergeAvgMat+AvgMat;
		elseif chWeight==2
			MaxNumberOfTrials=max(NTrialAvgVec);
			fprintf(1,'Maximum number of trials in this file: %g\n\n',MaxNumberOfTrials);
			TotMaxNumberOfTrials=TotMaxNumberOfTrials+MaxNumberOfTrials;
			MergeAvgMat=MergeAvgMat+MaxNumberOfTrials.*AvgMat;
		elseif chWeight==3
			MergeAvgMat=MergeAvgMat+AvgMat./StdMat;
			InvMergeStdMat=InvMergeStdMat+1./StdMat;
		end
		MergeStdMat=MergeStdMat+StdMat;
		%============If MergeNTrialAvgVec=NTrialAvgVec'=============
		SizeMergeNTrialAvgVec=size(MergeNTrialAvgVec);
		SizeNTrialAvgVec=size(NTrialAvgVec);
		if SizeMergeNTrialAvgVec(2)==SizeNTrialAvgVec(1); NTrialAvgVec=NTrialAvgVec'; end
		MergeNTrialAvgVec=MergeNTrialAvgVec+NTrialAvgVec;
		%============If MergeMedMedRawVec=MedMedRawVec'=============
		SizeMergeMedMedRawVec=size(MergeMedMedRawVec);
		SizeMedMedRawVec=size(MedMedRawVec);
		if SizeMergeMedMedRawVec(2)==SizeMedMedRawVec(1); MedMedRawVec=MedMedRawVec'; end
		MergeMedMedRawVec=[MergeMedMedRawVec;MedMedRawVec];
		%============If MergeMedMedAvgVec=MedMedAvgVec'=============
		SizeMergeMedMedAvgVec=size(MergeMedMedAvgVec);
		SizeMedMedAvgVec=size(MedMedAvgVec);
		if SizeMergeMedMedAvgVec(2)==SizeMedMedAvgVec(1); MedMedAvgVec=MedMedAvgVec'; end
		MergeMedMedAvgVec=[MergeMedMedAvgVec;MedMedAvgVec];
		%==============================================================
	end
end

if chWeight==1
	MergeAvgMat=MergeAvgMat./NFiles;
elseif chWeight==2
	MergeAvgMat=MergeAvgMat./TotMaxNumberOfTrials;
elseif chWeight==3
	MergeAvgMat=MergeAvgMat./InvMergeStdMat;
end
if chNorm>1
    MergeAvgMat=MergeAvgMat.*mean(NormVec);
end
MergeStdMat=MergeStdMat./NFiles;

SaveAvgFile(OutFilePath,MergeAvgMat,MergeNTrialAvgVec,MergeStdMat,SampRate,MergeMedMedRawVec,MergeMedMedAvgVec,EegMegStatus,NChanExtra);
SetDefPath('w',OutPath);

if PrintGPStatus
	NCol=ceil(sqrt(NFiles));
	NRow=ceil(NFiles./NCol);
	figure;
	for FileIndex=1:NFiles
		[File,Path,FilePath]=GetFileNameOfMat(InFileMat,FileIndex);
		[AvgMat,File,Path,FilePath,NTrialAvgVec,StdMat,...
		SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(FilePath);
		[NChan,NPoints]=size(AvgMat);
		subplot(NCol,NRow,FileIndex)
		plot(mean(sqrt(AvgMat.^2)))
		axis([1 NPoints 0 max(MaxVec)])
		title(File)
		pause(.001)
	end
end
return;
