function sfcLayerDepth = getSfcLayerDepth(bin)
% getSfcLayerDepth = returns the depth of the surface layer from a spmr file
%
% The surface layer depth is defined as the depth where Ed = Ed(0-)/e. SeaWiFS
% estimates the average chlorophyll from the surface to this depth.
%
% Use as: sfcLayerDepth = getSfcLayerDepth(binFile)
%
% Inputs: binFile = the binned data file produced by prosoft or
%                   a data structure produced by readSpmr

% Brian Schlining
% 22 Feb 2001

if isempty(bin)
   sfcLayerDepth = NaN;
   return;
end

if ~isstruct(bin)
   [filepath filename ext] = fileparts(bin);
   
   
   bin = readSpmr(bin);
   
   if isempty(bin)
      sfcLayerDepth = NaN;
      return
   end
else
   [filepath filename ext] = fileparts(bin.filename);
end

e       = 1/exp(1);


switch lower(ext)
case '.bin'
   zColumn = min(find(strcmp(lower(bin.fields), 'pres'))); % There may be more than one pressure field
   z       = bin.data(:, zColumn);
   
   EsWaves = str2num(bin.ESWAVES);
   EdWaves = str2num(bin.EDWAVES);
   
   lambda = [443 490 510 555];
   
   depth = lambda * NaN;
   
   for i = 1:length(lambda)
      
      goodE    = near(EsWaves, lambda(i));               % Get the wavelength nearest to lambda
      
      EsName   = ['es' num2str(EsWaves(goodE))];
      EdName   = ['ed' num2str(EdWaves(goodE))]; 
      EsColumn = find(strcmp(lower(bin.fields), EsName));
      EdColumn = find(strcmp(lower(bin.fields), EdName));
      
      % This is supposed to be the ratio of Ed/Ed(0-) but here we are testing it with 
      % Ed/Es (Ed(0-) = Es*.98)
      eRatio   = bin.data(:, EdColumn) ./ (bin.data(:, EsColumn)*.98);
      good     = near(eRatio, e);
      depth(i) = z(good);
      
   end
   sfcLayerDepth = max(depth);
case '.par'
   zColumn   = find(strcmp(lower(bin.fields), 'depth'));
   PctColumn = find(strcmp(lower(bin.fields), '%light'));
   good = near(bin.data(:, PctColumn), e*100);
   sfcLayerDepth = bin.data(good, zColumn);
otherwise
   sfcLayerDepth = NaN;
end


