function Z = oms_getdepth(infile, V, flag)
% OMS_GETDEPTH - Get the depth of the sensor supplying a variable 
%
% Use as: Z = oms_getdepth(infile, V)
%
% Inputs: infile = a netcdf object
%         V      = a netcdf variable object from an Oasis Mooring 
%                  Spectroradiometer netcdf file
%         flag   = type of depth qualtiy control to implement
%                  <0 = Return default instrument depth (default)
%                  0  = No QC
%                  >0 = outliers > +/- xm from defualt depth are set to default depth
%                  
%
% Output: Z = Depth of each sample taken by the sensor
%         Note: due to errors

OK = oms_checkfile(infile);

if ~OK
   Z = [];
   return;
end

if nargin < 3
   flag = -1;
end

%===============================
% find the depth of the  sensor
%===============================
Z           = V.instrumentDepth(:);		% get the depth
if ~isempty(Z)
   if flag >= 0
      oasis_bank  = V.bank(:);			   % get the bank# of the Ed sensor
      v = var(infile);									% Get all the variables
      S = oms_getinfo(infile);
      bank_depths = infile{'bankDepth'}(:);		% get the default (i.e. low precision) bank depths
      banksAtZ    = find(bank_depths == Z) - 1;	% Find other bank#'s at the same depth
      iZ          = strmatch('z', S.symbol);		% Index of all variables containing depth info
      OK          = zeros(size(S.bank));
      for i = 1:length(banksAtZ)
         j = find(S.bank == banksAtZ(i));
         OK(j) = 1;
      end
      
      good = intersect(find(OK),iZ);
      if ~isempty(good)
         Zorg = Z;
         Z = v{good}(:);
         i = find(Z == v{good}.FillValue_(:));
         Z(i) = Zorg*-1;
         Z = Z*-1;
         if flag > 0
            i = find(Z > Zorg + flag | Z < Zorg - flag);
            Z(i) = Zorg;
         end
      else
         Z = ones(size(V))*Z;
      end
   else
      Z = ones(size(V))*Z;
   end
end
