function bad_ashuw(ashfile, yearbase, varargin)
% bad_ashuw(ashfile, yearbase, varargin)
%  
% run this to create a file with bad profiles for profiles in which ship
% speed excedes threshold and ashtech gap is longer than cutoff
%
% apply output file with:
% use with 'dbupdate ../adcpdb/[dbname] bad_ahsuw.asc'
%
% 'ashfile' is the output of ubprint  (defaults to [dbname].mat)
%
% varargin: name, value pairs:
% (name)                        (what)                default
% --------              -----------------           ----------------
% 'ashfiledir'          path to ashfile               '../nav'
% 'outfile'             file with bad profiles        'bad_ashuw.asc'
% 'uw_cutoff'           cutoff for underway            2    (m/s)
% 'shortest_okgap'      ashtech bad if longer
%                            gap than this (mins)      25
% 'append'              append to current file         1
%                           (otherwise overwrite)
%
%

%JH 2004/02/11
% 
% 
% combination of mk_badtimes.m and ashrot.m


cfg.ashfiledir = '../nav';
cfg.outfile = 'bad_ashuw.asc';
cfg.uw_cutoff = 2;
cfg.append = 1;
cfg.shortest_okgap = 25;

cfg = fillstruct(cfg, varargin, 0);

if nargin < 2
   fprintf('ERROR: must specify yearbase\n')
   return
end


% Editing criteria:
min_n_used     = 20;
max_dh_span    =  5;
max_dh         = 10;
max_mean_roll  =  7;
max_mean_pitch =  5;
dh_offset = 0;


% clip from ashrot here
[ppjunk,nnjunk,ext]=fileparts(ashfile);
if isempty(ext)
   ashfile = [ashfile, '.mat'];
end

ashfile = fullfile(cfg.ashfiledir, ashfile);

if ~exist(ashfile, 'file')
   fprintf('\nAshtech attitude file (%s) from ubprint not found.\n',...
           ashfile)
   return
end

load(ashfile, '-mat');


% (1) get a mask for good ashtech data
igood = find(~isnan(att(i_r_mean,:)));
if isempty(igood)
   disp('Warning: No valid attitude measurements were found.')
   return
   good_att_mask = zeros(1, size(att, 2));
else
   dhm = mean(att(i_dh_mean, igood));
   rm = mean(att(i_r_mean, igood));
   pm = mean(att(i_p_mean, igood));

   % Editing mask:
   good_att_mask = att(i_n_used,:) > min_n_used                      ...
                 & att(i_dh_max,:)-att(i_dh_min,:) < max_dh_span     ...
                 & abs(att(i_dh_mean,:) - dhm)     < max_dh          ...
                 & abs(att(i_r_mean,:)  - rm )     < max_mean_roll   ...
                 & abs(att(i_p_mean,:)  - pm )     < max_mean_pitch;
end

i_good_att = find(good_att_mask);

dh = att(i_dh_mean,:).';
tt = att(i_day,:).';
n_att = length(dh);

if isempty(i_good_att)
   disp('Warning: No attitude measurements have passed the editing checks.')
   disp('         A value of 0 will be substituted.')
   dh = zeros(size(tt));
else

   % Fill missing values at start of array with first good value.
   i_0 = i_good_att(1);
   if i_0 ~= 1,
      dh(1:(i_0-1)) = dh(i_0) * ones(i_0-1,1);
   end

   % Fill missing values at end of array with last good value.
   i_n = i_good_att(length(i_good_att));
   if i_n ~= n_att,
      dh((i_n+1):n_att) = dh(i_n) * ones(n_att-i_n, 1);
   end

   % Next: linearly interpolate any gaps in the middle.
   i_bad_att = i_0 - 1 + find(~good_att_mask(i_0:i_n));
   if ~isempty(i_bad_att),
     dh(i_bad_att) = table1([tt(i_good_att) dh(i_good_att)], tt(i_bad_att));
   end
end



%% (2) get a mask for profiles in side long gaps
in_long_range_mask = zeros(size(good_att_mask));

% Find significant interpolation ranges:
range_mask = [1 good_att_mask];
edge_mask = diff(range_mask);
i_start = find(edge_mask == -1);

range_mask = [good_att_mask 1];
edge_mask = diff(range_mask);
i_end   = find(edge_mask == 1);

n_ranges = length(i_end);
if (n_ranges == length(i_start))
   time_ranges =  [tt(i_start) tt(i_end)];  % two columns
   range_lengths = diff(time_ranges.').';  % one column
   i_long_range = find(range_lengths > (cfg.shortest_okgap*60/86400));
else
   fprintf(' ERROR: Number of starts and ends of interp ranges not equal')
   return
end



%% (3) get mask with ship speeds over cutoff
mps = ll2mps(att(i_day,:), att(i_lon,:), att(i_lat,:));
toofast_mask = mps > cfg.uw_cutoff;


%% (4) find the bad values and write a note:
if (cfg.append == 1)
   fid_log = fopen('bad_ashuw.log','a');
else
   fid_log = fopen('bad_ashuw.log','w');
end
fprintf(fid_log, '%s\n', nowstr);
fprintf(fid_log, 'ensembles found with bad ashtech while underway:\n');
for longsegi = 1:length(i_long_range)
   index = i_long_range(longsegi);
   ii = i_start(index) : i_end(index);
   in_long_range_mask(ii) = 1;
   fprintf(fid_log,...
           '%d ensembles between %f and %f\n',...
           length(find(in_long_range_mask(ii) & toofast_mask(ii))), ...
           time_ranges(index,1), time_ranges(index,2));
   fprintf('%d ensembles between %f and %f\n',...
           length(find(in_long_range_mask(ii) & toofast_mask(ii))), ...
           time_ranges(index,1), time_ranges(index,2));
end
fprintf('\n\nlist of bad ashtech while underway is in %s\n', cfg.outfile)
fprintf('summary of bad time ranges in "bad_ashuw.log"\n')
fclose(fid_log);

%% (4) %now write to file:  (clip from mk_badtimes)
iblkprf = zeros(length(good_att_mask),2);  %should be irrelevant
time = to_date(yearbase, att(i_day,:), 'n');

badprofs = in_long_range_mask & toofast_mask;
if cfg.append
   fid = fopen(cfg.outfile, 'a');
else
   fid = fopen(cfg.outfile, 'w');
end   
for ii = find(badprofs)
   fprintf(fid, ...
           ' -1 %3d %3d %4d/%02d/%02d  %02d:%02d:%02d\n', ...
           iblkprf(ii,:), time(ii,1:6));
end
fclose(fid);
fprintf('wrote %d lines to %s\n', length(find(badprofs)), cfg.outfile)

