function oms_makeSeabassFile(infile)
% oms_makeSeabassFile   - Convert Oasis Mooring Spectroradiometer data to SeaBASS format
%
% This program creates one file for each instrument depth. This was in response to 
% a request from SeaBASS. The text files will be written to
% the same directory as the input file
%
% Use as: oms_makeSeabassFile(infile)
%
% inputs: infile = an OMS netcdf object

% Brian Schlining
% 31 Jan 2000
% 14 Jun 2000; Converted oms2seabass to oms_makeSeabassFormat

inFile = char(ncnames(infile));					   % Get the filename
[filepath filename ext] = fileparts(inFile);	% Parse it

S = oms_getinfo(infile);
depths = unique(S.instrumentDepth);
depths = depths(find(~isnan(depths)));


%===============
% Missing value
%===============
%mv = infile.missing_value(:);								% Get the missing value
mv = -999;
if isempty(mv)
   mv = -999;
end
if isstr(mv)
   mv = str2num(mv);
end


%=============
% Lat and Lon
%=============
lat = infile{'latitude'}(:);										% Add the lat and lon
lon = infile{'longitude'}(:);

%==========
% Get Time
%==========
t = nctime(infile);
rows = length(t);

%==========================================================
% Locate Night time data and get rid of it.
% Currently this is very simple. It gets rid of data thats
% not between 7am and 5pm local. This could be upgraded later 
% to remove data where the solar zenith angle is below the 
% horizon.
%==========================================================
[localYear localMonth localDay localHour localMinute localSecond] = datevec(t + gmtoffset(lon));
localHour = localHour + (localMinute + localSecond/60)/60;
dayTime = find(localHour >= 7 & localHour <= 17);	% Get data between 7am and 5pm
t       = t(dayTime);
[Year Month Day Hour Minute Second] = datevec(t);
Second  = round(Second);
tFields = {'year','month','day','hour','minute','second'};
tUnits  = {'yyyy','mo','dd','hh','mn','ss'};

%======
% Time
%======
tMin      = min(t);											% Get the starting time
[yearMin monthMin dayMin hourMin minuteMin secondMin] = datevec(tMin);
secondMin = round(secondMin);								% Round this for clean looking output
tMax      = max(t);											% Get the ending time
[yearMax monthMax dayMax hourMax minuteMax secondMax] = datevec(tMax);
secondMax = round(secondMax);								% Round this for clean looking output

%============
% Other Info
%============
mooring  = lower(infile.mooring(:));
if strcmp(mooring, 'ep1') | strcmp(mooring, 'ep2')
   f = ['\\tsunami.shore.mbari.org\oasis\eqpac\cfg\' mooring '.cfg'];
elseif strcmp(mooring, 'm1') | strcmp(mooring, 'm2')
   f = ['\\tsunami.shore.mbari.org\oasis\cfg\' mooring '.cfg'];
end
calFiles = oms_getcfgfiles(f);

%=========
% QC Flag
%=========
%Qc = infile{'flag'};
%if ~isempty(Qc);
%i

for i = 1:length(depths);
   
   depth = depths(i);
   
   outFile = [filepath filesep filename '_' num2str(i) '.ftp'];  % Create an output filename
   fid     = fopen(outFile, 'wt');				                    % Open the output file for writing
   
   OK      = find(S.instrumentDepth == depth);               % Get instuments at a single depth
   good    = find(~strcmp(S.symbol(OK), 'null') & ~strcmp(S.symbol(OK), 'v') ...
      & ~strcmp(S.symbol(OK), 'f') & ~strcmp(S.symbol(OK), 'z'));
   OK      = OK(good);                                           % Ignore voltage and nulls
   
   %==========================
   % Begin writing the header
   %==========================
   fprintf(fid, '/begin_header\n');
   fprintf(fid, '/affiliations=Monterey_Bay_Aquarium_Research_Institute\n');
   fprintf(fid, '/experiment=TAO_Moorings\n');
   fprintf(fid, '/investigators=Francisco_Chavez,Pete_Strutton,Brian_Schlining\n');
   fprintf(fid, '/contact=chfr@mbari.org,stpe@mbari.org,brian@mbari.org\n');
   
   parameters = getSeabassParameterNames(unique(S.symbol(OK)), depth);
   fprintf(fid, '/parameters=');
   for j = 1:length(parameters)
      fprintf(fid, '%s', parameters{j});
      if j < length(parameters)
         fprintf(fid, ',');
      else
         fprintf(fid, '\n');
      end
   end
   
   fprintf(fid, '/data_type=mooring\n');
   fprintf(fid, '/measurement_depth=%4.1f\n', depth);
   fprintf(fid, '/original_file_name=%s%s\n', filename, ext);
   fprintf(fid, '/delimiter=space\n');
   fprintf(fid, '/missing=%f\n', mv);
   
   %==========================
   % Get variable information
   %==========================
   V    = var(infile);										% Variables
   V    = V(OK);                                   % Only get the variables at the current depth
   
   [fields, units] = oms_getSeabassFieldname(chopstruct(S,OK));	% Get the seabass names of each variable
   
   %==============
   % Get the data
   %==============
   DATA = ones(rows, length(OK))*NaN;
   for i = 1:length(V)						            % Loop through the pertinent variables 
      DATA(:,i) = V{i}(:);  				         	% Extract the data from each variable     
   end
   DATA(find(isnan(DATA))) = -999;

   %========================
   % Remove night time data
   %========================
   DATA = DATA(dayTime,:);
   
   %=============
   % Lat and Lon
   %=============
   fprintf(fid, '/north_latitude=%0.3f[DEG]\n', lat);
   fprintf(fid, '/south_latitude=%0.3f[DEG]\n', lat);
   fprintf(fid, '/east_longitude=%0.3f[DEG]\n', lon);
   fprintf(fid, '/west_longitude=%0.3f[DEG]\n', lon);
   
   %======
   % Time
   %======
   fprintf(fid, '/start_date=%04i%02i%02i\n', yearMin, monthMin, dayMin);
   fprintf(fid, '/end_date=%04i%02i%02i\n', yearMax, monthMax, dayMax);
   fprintf(fid, '/start_time=%02i:%02i:%02i[GMT]\n', hourMin, minuteMin, secondMin);
   fprintf(fid, '/end_time=%02i:%02i:%02i[GMT]\n', hourMax, minuteMax, secondMax);
   
   %============
   % Other info
   %============
   fprintf(fid, '/documents=MbariSeabassMooring.readme\n');
   fprintf(fid, '/calibration_files=%s.cfg,', mooring);
   for i = 1:length(calFiles)-1
      
      fprintf(fid, '%s,', calFiles{i});
   end
   fprintf(fid, '%s\n', calFiles{end});
   
   %========================
   % Add comments into here
   %========================
   %fprintf(fid, '! Comments: Last column is quality flag; -1=bad, 0=unchecked, 1=good\n');
   %fprintf(fid, '! Comments: MorelChl[0m]490 is mean chl over the upper 20m calculated according to Morel (1988), OC2V2Chl is calculated from the NLw. See documentation.\n');
   %fprintf(fid, '! Comments: KLw is Lw calculated using the attenuation coefficient of downwelling irradiance at the relevant wavelength to back-propagate the 20m Lu data.\n');
   %fprintf(fid, '! Comments: NLw is KLw normalized using surface Ed.\n');
   
   %==================
   % Write the fields
   %==================
   FIELDS = [tFields fields];
   fprintf(fid,'/fields=');
   for k = 1:length(FIELDS)
      fprintf(fid,'%s',FIELDS{k});
      if k < length(FIELDS)
         fprintf(fid, ',');
      else
         fprintf(fid, '\n');
      end
      
   end
   
   %=================
   % Write the units
   %=================
   UNITS = [tUnits units];
   fprintf(fid,'/units=');
   for k = 1:length(UNITS)
      fprintf(fid,'%s',UNITS{k});
      if k < length(UNITS)
         fprintf(fid, ',');
      else
         fprintf(fid, '\n');
      end
   end
   
   %================
   % Write the data
   %================
   [r c]  = size(DATA);
   
   
   for n = 1:r
      fprintf(fid,'%4i %02i %02i ',Year(n), Month(n), Day(n));
      fprintf(fid,'%02i %02i %02i ',Hour(n), Minute(n), Second(n));         % Time in GMT
      for m = 1:c
         fprintf(fid,'%12.6f ', DATA(n,m));               % The data
      end
      fprintf(fid,'\n');
   end
   
   fclose(fid);
   
end

%pc2unix(outfilename);


%%%%%%%%%%%%%%%%%%%%%%%%
function [seabassParm, units] = getSeabassParameterNames(OMSParm, depth)

seabassParm = cell(size(OMSParm));
units = cell(size(OMSParm));

for i = 1:length(OMSParm)
   switch OMSParm{i}
   case 'ed'
      tmp = 'Ed';
      ut  = 'uW/cm^2/nm';
   case 'lu'
      tmp = 'Lu';
      ut  = 'uW/cm^2/nm/sr';
   case 'es'
      tmp = 'Es';
      ut  = 'uW/cm^2/nm';
   case 'par'
      ut  = 'uE/sm^2/s';
      if depth >= 0
         tmp = 'EPar';
      else
         tmp = 'PAR';
      end
   case 't'
      ut = 'degreesC';
      if depth >= 2
         tmp = 'Wt';
      elseif depth <= 0
         tmp = 'At';
      else
         tmp = 'SST';
      end
      
   case 'z'
      
      if depth >= 0
         tmp = 'pressure';
         ut = 'dbar';
      else
         tmp = 'altitude';
         ut = 'm';
      end
      
   end
   seabassParm{i} = tmp;
   units{i} = ut;
end

%%%%%%%%%%%%%%%%%%%%%%%%









