%==================================================================
%
%	CalcGrandMean.m
%
%	Markus Junghoefer	[1998]
%   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.                                                                      
%
%
%	Function definition
%
	
	function[GrandMeanData,FileMatIn]=CalcGrandMean(FileMatIn,FileFormat,filterSpec,dialogTitle,x,y,PrintStatus);

%
%
%=================================================================
if nargin<7; PrintStatus=1; end
if nargin<6; y=0; end
if nargin<5; x=0; end
if nargin<4; dialogTitle=[]; end
if nargin<3; filterSpec='*'; end
if nargin<2; FileFormat='SCADS'; end
if nargin<1; FileMatIn=[]; end

if ~strcmp(FileFormat,'SCADS') & ...
	~strcmp(FileFormat,'AsciiHeaderVec') & ...
	~strcmp(FileFormat,'AsciiBesaVec') 
		GrandMeanData=[];
		FileMatOut=[];
		return; 
end
if ~isempty(FileMatIn)
	[NFilesIn,NoUse]=size(FileMatIn);
else 
	[NFilesIn,FileMatIn]=ReadFileNames([],filterSpec,dialogTitle,x,y,PrintStatus);
end

for FileIndex=1:NFilesIn
	[File,Path,FilePath]=GetFileNameOfMat(FileMatIn,FileIndex);
	if strcmp(FileFormat,'SCADS')
		[DataMat] = ReadAvgFile(FilePath);
	elseif strcmp(FileFormat,'AsciiHeaderVec')
 		[DataMat] = ReadBem(FilePath,1,'Matrix')
	elseif strcmp(FileFormat,'AsciiBesaVec')
		[DataMat,TSB,DI,SB,SC,NPoints,NChan,SampRate,TrigPoint]=ReadAsciiBesa(FilePath);	
	end	
	if FileIndex==1; 
		GrandMeanData=DataMat; 
	else
		GrandMeanData=GrandMeanData+DataMat;
	end
end
GrandMeanData=GrandMeanData./NFilesIn;

return;
