%
%  Name: makeavgd.m
% 
%  Usage: makeavgd
% 
%  Description:
%    Creates a DIAMOND data file with averaged FRF data matrices
%     from multiple DIAMOND data files with single data ensembles
%

%  Version SWD970725
%
%  Author(s): Scott W. Doebling, doebling@lanl.gov
%
%  Institution: Los Alamos National Laboratory,
%		ESA-EA
%
%  Copyright (c) 1997, The Regents of the University
%     	of California. (See top level of code for
%        full copyright statement)
%

%
%  Determine how many files are available
%

navgf = input('How many files form the Averaged set?');

disp(['Preparing to load ',num2str(navgf),' files'])

%  Prompt for each one of the single ensemble files

pathname = 'C:\';

for ib = 1:navgf,
   
   fprintf(1,'Preparing to Load File #%d of %d\n',ib,navgf)
   
   [filename,pathname,error] = loadfile(0,pathname);

   if error == 0,
      
      fprintf(1,'Loading File #%d of %d\n',ib,navgf)

      eval(['load ',[pathname,filename]]);

      if exist('G')==1,
         
         if ib == 1,
            Gnew = zeros(size(G,1),size(G,2),navgf);
         end
         
         Gnew(:,:,ib) = G;
         
      end
      
      if exist('Gxy'),
         
         if ib == 1,
            Gxynew = zeros(size(Gxy,1),size(Gxy,2),navgf);
         end

         Gxynew(:,:,ib) = Gxy;
         
      end

      if exist('Gxx') == 1,
         
         if ib == 1,
            Gxxnew = zeros(size(Gxx,1),size(Gxx,2),navgf);
         end

         Gxxnew(:,:,ib) = Gxx;
         
      end

      if exist('Gyy') == 1,
         
         if ib == 1,
            Gyynew = zeros(size(Gyy,1),size(Gyy,2),navgf);
         end

         Gyynew(:,:,ib) = Gyy;
         
      end
   end
end

%  Create averaged data sets

if exist('Gnew')==1,
   G = squeeze(mean(Gnew,3));
end


if exist('Gxynew')==1,
  Gxy = squeeze(mean(Gxynew,3));
end

if exist('Gxxnew')==1,
  Gxx = squeeze(mean(Gxxnew,3));
end

if exist('Gyynew')==1,
   Gyy = squeeze(mean(Gyynew,3));
end

%  Compute Coherence Function

fprintf(1,'Forming Coherence Function...')

nresp = size(Gxy,1) / size(Gxx,1);

Gxxbig = [];

for i = 1:nresp,
   Gxxbig = [Gxxbig ; Gxx];
end

Coh = abs(Gxy).^2 ./ Gxxbig ./ Gyy;

fprintf(1,'done\n')

%
%   Save the new DIAMOND data file with the averaged variables
%

fprintf(1,'Saving Averaged Datafile...\n')

[filename,pathname,error] = savefile(0,pathname);

if error == 0,
   
   savedata
   
else
   
   disp('ERROR Saving Averaged Datafile!')
   
end

disp('Done Creating Averaged Data file')