function handles = autovect(x, y, u, v, varargin)
% handles = autovect(x, y, u, v, varargin)
%    u       % u  cm/s, vector Nx1 (or 1xN) vector  (disable by using NaN)
%    v       % v  cm/s, vectorNx1 (or 1xN) vector   
%    x       % assumed to be longitude
%    y       % assumed to be latitude
% 'handles' is a structure  with handles
%    handles.axes         the vectorplot axes object, 
%    handles.hcb_topo     the topography colorbar object (if it exists)
%    handles.hcb_temp     the temperature colorbar object (if it exists)
%
%   name          default             what
%  -----         ----------         % --------
%    T              []              % temperature (one per point)
%  stations         []              % x,y pairs for special treatment
%  latrange         []              % [minlat maxlat] default is autorange
%  lonrange         []              % [minlon maxlon] default is autorange
%  Trange           []              % [minT maxT] default is autorange
%  Tstep            .5              % colorbar step for colors 
%  Tlabels          []              % labels for colorbar.  empty means
%                                   %        [minT:Tstep:maxT]
%  toponame         []              % default '' is best_topo; names can be
%                                   %     'smithsandwell'     smith-sandwell
%                                   %      'tbase'             terrain base
%                                   %      'm_elev'            default m_map
%                                   %      'none'       don't do topography
%  toporange    [-6000 0]           % [mintopo maxtopo]
%  topostep         500             % steps for color contour
%  topolabels        []             % labels for colorbar.  empty means
%                                   %   [mintopo:topostep:maxtopo]
%  topofill          1              % color fill topo (else colored lines)
%  clinewidth        1              % contour line width (if using lines)
%  topounits        'km'            % topographic databases are in meters.
%                                   %     default is to change these to km for
%                                   %     full-ocean depths. else use 'm'
%  titlestr         []              % (default is no title)
%  titlesfontsize   14              %     title font size
%  key_vec          [1 0]           % key: u,v for length scale
%  key_str         '1 m/s'          %      string for key 
%  unwrap_lon        1              % try to make all of the vectors land 
%                                   %     together no matter what the 
%                                   %     cruisetrack did
%  mvec_scale        []             %  [data units per inch]  default is to
%                                   %      autoscale based on vel max
%  shaftwidth        2              % good for temperature or few vectors
%                                   % probably want 1 if crowded
%  headlength        10             % pixels?  (matches shaftwidth 2)
%  axesfontsize      14             %  axes font size
%  axesfontweight   'bold'          % default is 'bold'; could say 'normal'
%  newfig            1              % start a new figure
%
%
%  outfile           ''             % string: prefix of eps filename for disk
%                                   %   (if empty, do not save file)
% 

% projection is lambert; adding more may be tough
% JH 2003/07/30 

cfg.T             =   [];            
cfg.stations      =   [];          
cfg.latrange      =   [];          
cfg.lonrange      =   [];          
cfg.Trange        =   [];          
cfg.Tstep         =   .5;          
cfg.Tlabels       =   [];          
cfg.toponame      =   '';          
cfg.toporange     =  [-6000 0];       
cfg.topostep      =   500;         
cfg.topolabels    =    [];         
cfg.topofill      =    1;
cfg.clinewidth    =    1;
cfg.topounits     =   'km';
cfg.titlestr      =    [];         
cfg.titlefontsize =    12;
cfg.unwrap_lon    =    1;          
cfg.mvec_scale    =    [];         
cfg.key_vec      = [1 0];
cfg.key_str      = '1 m/s';
cfg.shaftwidth   = 2;
cfg.headlength   = 10;
cfg.axesfontsize = 14;     % or 10 or 12
cfg.axesfontweight = 'bold';  % or normal
cfg.newfig       = 1;
cfg.outfile      = '';
%--------------------------------------------

cfg = fillstruct(cfg, varargin, 0);

if length(find(~isnan(u))) == 0
   novectors = 1;
else
   novectors = 0;
end


% set up vector plotting length
if (isempty(cfg.mvec_scale))
   oki = find(~isnan(u+i*v));
   if (max(abs(u(oki) + i*v(oki))) > 1)
      cfg.mvec_scale = 2;
   elseif (max(abs(u(oki) + i*v(oki))) > .5)
      cfg.mvec_scale = 1;
   else
      cfg.mvec_scale = .5;   
   end
end

% set things up for map ------------------------------
[lonrange, latrange] = map_range(x, y);
if isempty(cfg.lonrange),  cfg.lonrange = lonrange;  end
if isempty(cfg.latrange),  cfg.latrange = latrange;  end

if (cfg.unwrap_lon)
   x = unwrap_lon(x);
end

if cfg.lonrange(2) < 0
   cfg.lonrange = cfg.lonrange + 360;
end
dshift = round(360*(round(  (mean(cfg.lonrange) - mstdgap(x))/360)));
x = x + dshift;

handles.axes = gca;


plot_topog = logical(1);
if ~isempty(cfg.toponame)
   if strcmp(cfg.toponame, 'none')
      plot_topog = logical(0);
   end
end
if plot_topog
   [longrid, latgrid, topog] = ...
       best_topo(cfg.lonrange, cfg.latrange, ...
                 'toponame', cfg.toponame);
   if (isempty(topog))
      [longrid, latgrid, topog] = ...
          best_topo(cfg.lonrange, cfg.latrange,...
                    'toponame','m_elev');
   end
end

if (plot_topog)
   [topog, longrid] = m_fixlon(longrid(:)', latgrid', topog, cfg.lonrange);  
   
   
   %topography colors, do it in meters
   topo_clev = [-100000 cfg.toporange(1):cfg.topostep:cfg.toporange(2) 10000];
   if isempty(cfg.topolabels)
      cfg.topolabels = best_ticks([topo_clev(2), topo_clev(end-1)]);
   end
   if strcmp(cfg.topounits, 'km')
      topo_clev       = unique(round(topo_clev/1000));
      cfg.topolabels  = unique(round(cfg.topolabels/1000));
      topog            = topog/1000;
   end
   ntopo = length(topo_clev);
   topo_cmap = mk_cmap(ntopo - 1, 'topo');
   topo_indices = 1:size(topo_cmap,1);
else
   topo_cmap = [];
   topo_indices = 0;
end


%temperature colors %% fix this
use_T = logical(0);
if (~isempty(cfg.T)) 
   Ti = find(~isnan(cfg.T));
   if length(Ti) > 0
      use_T = logical(1);
      if isempty(cfg.Trange)
         cfg.Trange = [min(cfg.T(Ti)) max(cfg.T(Ti))];
         if (diff(cfg.Trange) < 1)
            cfg.Trange = cfg.Trange + [-1 1];
         end
      end
      if isempty(cfg.Tlabels)
         cfg.Tlabels = best_ticks(cfg.Trange);
      end
      if (isempty(cfg.Tstep))
         cfg.Tstep = mean(diff(best_ticks(cfg.Trange)));
      end
      Tclev = [-100 cfg.Trange(1) : cfg.Tstep/4 : cfg.Trange(2) 100];
   else
      use_T = logical(0);
   end
end



if (use_T )
   ntemps = length(Tclev);
   temp_cmap = mk_cmap(ntemps-1, 'jet');
   cmap = [topo_cmap ; temp_cmap];
   temp_indices = topo_indices(end) + (1:size(temp_cmap,1));
else
   cmap = [topo_cmap];
end


if (cfg.newfig == 1)
   figure
else
   hold off
end

if (~isempty(cmap))
   colormap(cmap)
end

set(gcf, 'defaultaxesfontsize', cfg.axesfontsize')
set(gcf, 'defaultaxesfontweight', cfg.axesfontweight')

% do the plot --------------------------------------------------

m_proj('lambert', 'long' , cfg.lonrange, 'lat', cfg.latrange);

if (plot_topog)
   if cfg.topofill == 1
      [cmat, haxtopo] = m_contourf(longrid, latgrid ,topog, topo_clev);
      set(haxtopo, 'EdgeColor', 'none');
   else
      [cmat, haxtopo] = m_contour(longrid, latgrid ,topog, topo_clev);
      set(haxtopo, 'linewidth',cfg.clinewidth);
   end

   cdata_direct(haxtopo, topo_clev, topo_indices(1));
   hcb_topo = cbar_direct(topo_clev, topo_indices(1), 'vert',...
                          sprintf('depth, %s', cfg.topounits));
   set(findobj(hcb_topo, 'Type', 'patch'), 'EdgeColor', 'none')
   set(hcb_topo, 'ytick', cfg.topolabels, 'fontsize',10);
end
m_grid('tickdir','out');

   
hold on



if (use_T)
   if novectors == 1
      m_plot(x,y,'k')
   else
      [hvp_temp] = m_vec(cfg.mvec_scale, x ,  y, u, v, cfg.T,...
                         'headlength',cfg.headlength, 'shaftwidth', cfg.shaftwidth,...
                         'CDataMapping','direct', 'EdgeColor','k');
      cdata_direct(hvp_temp, Tclev, temp_indices(1));
   end
else
   if novectors == 1
      m_plot(x,y,'k')
   else
      [hvp] = m_vec(cfg.mvec_scale, x , y, u, v,'k',...
                    'headlength',cfg.headlength, 'shaftwidth', cfg.shaftwidth,...
                    'CDataMapping','direct', 'EdgeColor','k');
   end
end


if ~novectors
   [hp,ht]=m_vec(cfg.mvec_scale, min(cfg.lonrange) + .05*diff(cfg.lonrange),...
                 min(cfg.latrange) + .1*diff(cfg.latrange),...
                 cfg.key_vec(1), cfg.key_vec(2),...
                 'key', cfg.key_str, ...
                 'shaftwidth', cfg.shaftwidth,...
                 'headlength',cfg.headlength);
   set(hp,'facecolor','k');
   set(hp,'edgecolor','k');

   
   if (use_T)
      % Temperature color indexing.
      hcb_temp = cbar_direct(Tclev, temp_indices(1), 'horiz', ...
                             'Temperature, deg C');
      set(findobj(hcb_temp, 'Type', 'patch'), 'EdgeColor', 'none');
      set(hcb_temp, 'xtick', cfg.Tlabels,'fontsize',10)
   end
end


if ~isempty(cfg.titlestr)
   hh=title(cfg.titlestr);
   set(hh,'fontsize', cfg.titlefontsize);
end

if (plot_topog)
   handles.haxtopo = haxtopo;
   handles.hcb_topo = hcb_topo;
end

if (use_T)
   if ~novectors
      handles.hcb_temp = hcb_temp;
   end
end
      
   

if (~isempty(cmap))
   set(gcf, 'renderer', 'painters')
end


if ~isempty(cfg.outfile)
   printit(outfile)
end



