function[OutFilePath,NormVec]=MergeAvgFileGroups(InFileMat,OutFilePath,chWeight,chNorm,DefFileMask,chGroups,NrConditions)

%   MergeAvgFileGroups - averages several SCADS average files, offering options
%   for weighting and normalization.
%
%   See also CALCAVGDIFF.

%   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<7; NrConditions = [];end
if nargin<6; chGroups = [];end
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;

%==================================================================
clc;
[DefFilePath]=SetDefPath('r',DefFileMask,[],0);
[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,[],0);




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);

fprintf('\n\n');
while isempty(NrConditions)
    NrConditions = input('How many files are in a group ? ');
    if round(NFiles/NrConditions)~=NFiles/NrConditions
        disp('Batch file length is not dividable by the group size!');
        NrConditions  = [];
    end
end
NLoops = NFiles/NrConditions;
fprintf('\n\n');

if chNorm>1
	NormVec=zeros(NFiles,1);
else
	NormVec=[];
end

TmpFileMat = [];

for FileInd = 1:NLoops
    
    OutFilePath = [];
    
    TmpFileMat =GetFileNameOfMat(InFileMat,1+(FileInd-1)*NrConditions);
    for i=2:NrConditions
        TmpFileMat = char(TmpFileMat,GetFileNameOfMat(InFileMat,(FileInd-1)*NrConditions+i));
    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
    
    fprintf('\nThe actual file is an average ot the files:\n\n');
    disp(TmpFileMat);
    fprintf('\n');
	if isempty(OutFilePath)
		[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);
        [NChan,NPoints]=size(AvgMat);
		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);
	fprintf('\n\n');
	fprintf(1,'Average of %g files done. %g\n\n',NrConditions);
	fprintf('\n\n');
    
	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
    
end


return;
