function oms_avg(infile, outfile)
% OMS_AVG - Oasis Mooring Spectroradiometer averaging
%
% Create an nc file containing daily averages (between 10 and 2 mooring local time)
%
% Use as: oms_avg(infile, outfile);
%
% Inputs: infile = String name of the netcdf file to average
%         outfile = String name of the averaged data file to create
%
% Warning: OMS_AVG will clobber the outfile. So be careful about choosing file names 
% that already exist. If outfile already exists it will be erased and overwritten.

% Brian Schlining
% 02 Dec 1999
% 14 Mar 2000; Brought up to MBARI conventions

epoch = datenum('01 Jan 1970 00:00:00');

TimeLim = 2;													     % Look for data +/- 2 hours from Noon

in   = netcdf(infile, 'nowrite');
nccopyschema(in, outfile);										  % Create a new nc file
out  = netcdf(outfile, 'write');								  % Open the empty nc file for writing
try 
	out.dataComment3 = 'Data in this file are daily averages of data within +/-2 hours of local noon';
catch
   warning('Unable to add dataComment3');
end


t    = nctime(in); 		 							  		     % Get the GMT time of the data
[Year, Month, Day, Hour, Minute, Second] = datevec(t);  % Get the year 
Hour = Hour + (Minute + Second./60)./60;			  		  % Get the decimal hour of the day 
lon  = in{'longitude'}(:);	   		 						  % Get the longitude (degrees)
Day  = date2jul(t); 										        % Get the day of the year
v    = var(in);													  % Get the variable list from the netcdf file
index = 0;

for y = min(Year):max(Year)		 	 % Loop thorugh each year
   id = find(Year == y);
   
   for d = min(Day(id)):max(Day(id)) % Loop from the earliest to the lastest day found in each year
      
      LAN = noon(jul2date(d,y),lon,1);								  % Local Area Noon in GMT
		StartTime = (LAN - abs(TimeLim));       				  	  % in hours
		EndTime   = (LAN + abs(TimeLim));       				  	  % in hours
      i = find(Year == y & Day == d & Hour >= StartTime & Hour <= EndTime ); % Find all points on the desired day
      if ~isempty(i)
         index = index + 1;
         out{'time'}(index) = (mean(t(i))- epoch)*24*60*60;
         fprintf(1,'Processing %s GMT at index %06i\n',datestr(mean(t(i))), index);
         for n = 1:length(v)
            if ~iscoord(v{n})
               dat = in{name(v{n})}(i);
               bad = find(dat == v{n}.FillValue_(:));
               dat(bad) = NaN;
               dat = nanmean(dat);
               if (isnan(dat) | isempty(dat))
                  out{name(v{n})}(index) = v{n}.FillValue_(:);
               else
                  out{name(v{n})}(index) = dat;
               end
               
            end
         end
      end
      %if index == 10
      %   close(in);close(out);return
      %end
      
   end      
end
[f p e] = fileparts(infile);
out.sourceFile = ncchar([p e]);
out.description = 'Daily-averaged spectroradiometer data from the Equatorial Pacific'

ncquit(in);
ncquit(out);