function apuv(data, config, varargin)
% apuv(data, config, varargin)
% a tool to plot lon and lat vs time; and cruise track with
%       reference layer velocities as arrows
%
% use agetmat to get data
% varargin  has the following name, value pairs (defaults shown)
% name                    default                              what
% topo_clev             [-9000:500:0]                  topography levels   
% mvec_scale              100                           cm/s per inch on paper
% topo_only               0                         plot topo only; do not
%                                                     plot  lon and lat panels
% index                                                % how to subsample 
%                                           - empty (default, use it all)
%                                           - scalar (subsample by this many)
%                                           - length 2 vector (range in dday)
%                                           - length > 2 vector (indices to use)
% pfc                      (from aflagit)         profile flag cutoffs
%                          only pfc.cfg.pgrefl_nbins is used
%
%
% NOTE: to apply flagging, do this first:
% config.flagged = data.pflag; apuv(data,config)
%
% eg. 
% [data,config]=agetmat('a_')  %in gautoedit
% apuv(data,config,'index',[1:10:length(data.dday)],'topo_only',1)
%

% Jules 2000/11/27
% JH 2003/03/14 add varargin

%varargin structure elements are
astruct.topo_clev = [-9000:500:0];
astruct.mvec_scale = 100;
astruct.index = [];
astruct.topo_only = 0;
%% from aflagit: this should be pfc.cfg
astruct.pfc.cfg.underway =  100;
astruct.pfc.cfg.bigtarget_amp =  25;
astruct.pfc.cfg.bigtarget_offset =  5;
astruct.pfc.cfg.bigtarget_avg =  2;
astruct.pfc.cfg.pgcutoff =  50;
astruct.pfc.cfg.maxpgbin_fudge =  7;
astruct.pfc.cfg.badpgrefl =  50;
astruct.pfc.cfg.badpgrefl_nbins =  1;
astruct.pfc.cfg.trimtopbins =  0;
astruct.pfc.cfg.amp_cutoff_atbin1 =  0;
astruct.pfc.cfg.ampdecrperbin =  10;
astruct.pfc.cfg.ecutoff =  120;
astruct.pfc.cfg.wire_ecutoff =  90;
astruct.pfc.cfg.wire_onstation =  2;
astruct.pfc.cfg.wire_binrange =  [1 20];
astruct.pfc.cfg.jitter_cutoff =  5;
astruct.pfc.cfg.orphan_numbins =  1;
astruct.pfc.cfg.orphan_slide =  0;
astruct.pfc.cfg.agility =  3;
astruct.pfc.cfg.degperminute =  20;
astruct.pfc.cfg.glitchfactor =  3;
astruct.pfc.cfg.topglitchbin =  1;


%update  topo_clev, mvec_scale, and pfc
astruct = fillstruct(astruct, varargin, 0);

if (~isfield(config, 'rl_range'))
   config.rl_range = [1 20];
end


% get  indices
if (isemptys(astruct.index))
   abci = 1:length(data.dday);     % use all indices
elseif (length(astruct.index) == 1)     % subsample by this number
   abci = [1:astruct.index:length(data.dday)];
elseif (length(astruct.index) == 2)     %it's a range
   abci = find (...
      (astruct.index(1) <= data.dday) & ...
      (astruct.index(2) >= data.dday) );
else                                      %it's already set of indices
   abci = astruct.index;
   abci(abci < 1) = [];
   abci(abci > length(data.dday)) = [];
end
astruct.index = abci;


%if no flags defined, use no flags
if (~isfield(config, 'flagged'))
   config.flagged = zeros(size(data.umeas));
end

set(0, 'defaulttextinterpreter', 'tex')


rlbins = config.rl_range(1):config.rl_range(2);

if (diff(config.rl_range) == 0)
   rlbins = [rlbins rlbins];  %so mstdgap will work
end

mask0 = dotmmask(config.flagged(rlbins,abci));
uabs_refl_sm = mstdgap(data.uabs_sm(rlbins,abci).*mask0);
vabs_refl_sm = mstdgap(data.vabs_sm(rlbins,abci).*mask0);

toofast = 15;  %15m/s too fast ship speed



%try to filter positions a bit
if (isemptys(data.smmps))
   fprintf('no navigation, evidently\n')
   goodi= 1:length(abci);
else
   badi = find(data.smmps(abci) > toofast);  %
   if (isemptys(badi))
      goodi= 1:length(abci);
   else   
      warning('found potential bad navigation at:')
      fprintf('    dday                   lat                   lon\n')
      fprintf('%11.7f       %14.7fN     %14.7fE\n',...
              [data.dday(abci(badi))', ...
               data.lat(abci(badi))', data.lon(abci(badi))']')
      goodi = find(data.smmps(abci) <= toofast);  %
   end
end



%rename; now abci should no longer be necessary
dday = data.dday(abci(goodi));
lon =  data.lon(abci(goodi));
lat =  data.lat(abci(goodi));
uabs_refl_sm = uabs_refl_sm(goodi);
vabs_refl_sm = vabs_refl_sm(goodi);
config.flagged = config.flagged(:,abci(goodi));



%% replace old code with this:
%get the map ranges
[lonlims, latlims] = map_range(lon, lat);
if (isnan(sum(lonlims+latlims)))
   fprintf('navigation problems. aborting %s\n', mfilename)
   return
end

   
clf
if (~astruct.topo_only)
   %add a positions
   subplot(411)
   plot(dday, lon,'b')
   lltick(gca, 'y', 'lon');
   set(gca, 'xtick', [])
   set(gca, 'ylim', lonlims);
   text(mstdgap(dday), mstdgap(lon), 'LONGITUDE')
   
   
   subplot(412)
   plot(dday, lat,'b')
   lltick(gca, 'y', 'lat');
   text(mstdgap(dday), mstdgap(lat), 'LATITUDE')
   xlabel('dday')
   set(gca, 'ylim', latlims);
   pos = get(gca,'pos');
   set(gca, 'pos', pos + [0 .03 0 0]); 
end


if (~exist('m_elev','file'))
   fprintf('cannot show topography\n')
   fprintf('please download m_map from Rich Pawlowicz page at\n')
   fprintf('http://www.ocgy.ubc.ca/~rich')
   subplot(212)
   squiver(lon(goodi), lat(goodi), uabs_refl_sm(goodi),...
           vabs_refl_sm(goodi), 'scale', .02);
   axis('equal')
else
   if (~astruct.topo_only)
      subplot(212)
   end

   %use sstopo if we're north of 70deg
   if ( (latlims(1) < -70) | (latlims(2) > 70) | ~exist('ss_block','file'))
      %see whether there's any topography
      [topog, top_lon, top_lat]=m_elev([ lonlims latlims]  + [-1 1 -1 1]);
      top_lon = top_lon(1,:);
      top_lat = top_lat(:,1)';
      % lon-clipping bug in m_map:
      [topog top_lon] = m_fixlon(top_lon, top_lat, topog, lonlims);  
   else %use ss_block if it exists and if we're inside +/- 70
      num_tpts = 32*diff(latlims)*32*diff(lonlims);
      if (num_tpts < 10000)
         nsub = 1;
      elseif (num_tpts < 30000)
         nsub = 3;
      else
         nsub = 9;
      end
      
      eval('[top_lon, top_lat, topog] = ss_block(lonlims + [-1 1] , latlims + [-1 1], nsub);')
      
   end
      
   %set up the colors
   topo_cmap = mk_cmap(length(astruct.topo_clev), 'topo');
   topo_irange =  [1 length(topo_cmap(:,1))]; % indices into topo_cmap
   colormap([topo_cmap])
   
   
   m_proj('lambert', 'long' ,lonlims, 'lat', latlims);
   m_contourf(top_lon, top_lat, topog,  astruct.topo_clev);
   m_grid('box','fancy','tickdir','in');
   %m_coast;
   
   notflagged = (config.flagged == 0);
   rlbins = config.rl_range(1) : config.rl_range(2);
   numgoodbins = sum(notflagged(rlbins,:));
   goodi = find(numgoodbins >= astruct.pfc.cfg.badpgrefl_nbins);
   
   
   if (~isemptys(goodi))
      [hp,ht]=m_vec(astruct.mvec_scale,...
                    lon(goodi), lat(goodi),...
                    uabs_refl_sm(goodi),...
                    vabs_refl_sm(goodi),...
                    'shaftwidth',.1);
      set(hp,'facecolor','r')
      set(hp,'edgecolor','r')
   end
   
   %navtimes = NaN*data.lon;
   %m_track(data.lon, data.lat, navtimes, 'color', 'g', 'linewidth', 2);
   m_line(lon, lat, 'color', 'g', 'linewidth', 2);
   
   h_dcb = dcolbar( astruct.topo_clev/1000, 'vert', 'Depth (km)');
   h_dcbp = findobj(h_dcb,'Type','patch');
   cf_index(h_dcbp, astruct.topo_clev/1000, topo_irange);
end

set(gcf, 'renderer', 'painters')

date_it
subtitle(config.comment)
