function handles = autocont(u, v, varargin)
% handles = autocont(u, v, varargin)
%  u, v  % zonal and meridional velocity, cm/s
%  v is required, but it is empty, u is not assumed to be velocity
% 'handles' is a structure  with handles to 
%    handles.uax          the u contour axes object, 
%    handles.vax          the v contour axes object, 
%    handles.hcb_u        the u colorbar object (if it exists)
%    handles.hcb_v        the v colorbar object (if it exists)
%
%  name               default                  what
% ------             --------               ---------
%  ord_name            ''           % y label string
%  ord                 []           % default will use vertical index
%  new_ord             []           % default: grid ordinate to 40 points
%                                        if length > 1, use the values
%                                        if scalar, use this grid size
%  ord_num             []           % scalar: use this many gridpoints
%                                        (new_ord overrides ord_num)
%  ordmin              0            % for ylims only: make y axis go to 0
%                                   %   (setting 0 uses new_ord for ylims)
%
%  abc_name            ''           % x label string
%  abc                 []           % default will use horizontal index
%  new_abc             []           % default: grid abcissa to 60 points
%                                        if length > 1, use the values
%                                        if scalar, use this grid size
%  abc_num             []           % scalar: make this many grid points
%                                        (new_abc overrides abc_num)
%  vrange              []           % colormap range (default is guess)
%  vstep               []           % colormap step (default is to guess)
%  vlabels             []           % velocity colorbar labels
%                                   %     (default is to guess)
%  vlines              []           % contour these lines in black
%                                   %     (default is same as vlabels)
%                                   % disable with 'none'
%  vfill               1            % fill color contours (0 use lines)
%  axesfontsize      14             % axes font size
%  axesfontweight   'bold'          % default is 'bold'; could say 'normal'
%  ustr   'Zonal Velocity (cm/s)'      % u title string
%  vstr   'Meridional Velocity (cm/s)' % v title string
%  cstr   'cm/s'                    %  colorbar label string
%  del                 1            %  parameter for zgrid. (regrid)
%  nrng               10            %  parameter for zgrid. (regrid)
%  newfig            1              % start a new figure
%
% eg. autocont(u,v,'vange',[-30 30],'new_ord',[0:10:200])
% eg. autocont(sal, [], 'vrange',[34 36], 'vstep', .1, ...
%               'ustr','salinity', 'cstr','psu');

% JH 2003/07/31


%defaults
cfg.ord_name         =   '';    
cfg.ord              =   [];    
cfg.ordmin           =    0;
cfg.new_ord          =   [];    
cfg.ord_num          =   [];
cfg.abc_name         =   '';    
cfg.abc              =   [];    
cfg.new_abc          =   [];    
cfg.abc_num          =   [];
cfg.vrange           =   [];    
cfg.vstep            =   [];    
cfg.vlabels          =   [];    
cfg.vlines           =   [];    
cfg.vfill            =    1;
cfg.axesfontsize     =   14;    
cfg.axesfontweight   ='bold';   
cfg.ustr =   'Zonal Velocity'     ; % u title string
cfg.vstr =   'Meridional Velocity'; % v title string
cfg.cstr =          'cm/s';
cfg.del              =    1;
cfg.nrng             =   10;
cfg.newfig           = 1;

cfg = fillstruct(cfg, varargin, 0);
handles = [];


%% error checking
if isempty(v)
   isvel = 0;
else
   isvel = 1;
end


if length(find(~isnan(u))) == 0
   handles = 0;
   return
end


if ~isempty(cfg.ord) & length(cfg.ord) ~= length(u(:,1))
   fprintf('check inputs: ordinate does not match data\n')
   return
end
if ~isempty(cfg.abc) & length(cfg.abc) ~= length(u(1,:))
   fprintf('check inputs: abcissa does not match data\n')
   return
end


if isempty(cfg.ord)
   cfg.ord = 1:length(u(:,1));
   if isempty(cfg.ord_name)
      cfg.ord_name = 'bins';
   end
end
if isempty(cfg.abc)
   cfg.abc = 1:length(u(1,:));
   if isempty(cfg.abc_name)
      cfg.abc_name = 'index';
   end
end



%% get the gridded data :
% ordinate
zrange = [min(cfg.ord), max(cfg.ord)];
xrange = [min(cfg.abc), max(cfg.abc)];


if length(cfg.new_ord) == 0
   if (~isempty(cfg.ord_num))
      zdiv = cfg.ord_num;
   else
      zdiv = min(39,length(cfg.ord));
   end
   dz =  diff(zrange)/(zdiv+1);
   
   cfg.new_ord =  zrange(1) : dz : zrange(2);
elseif length(cfg.new_ord) == 1
   dz =   cfg.new_ord;
   cfg.new_ord =  zrange(1) : dz : zrange(2);
   % else cfg.new_ord IS the new ordinate
end

%abcissa
if length(cfg.new_abc) == 0
   if ~isempty(cfg.abc_num)
      xdiv = cfg.abc_num;
   else
      xdiv = min(59,length(cfg.abc));
   end
   dx =  diff(xrange)/(xdiv+1);
   cfg.new_abc =  xrange(1) : dx : xrange(2);
elseif length(cfg.new_abc) == 1
   dx = cfg.new_abc;
   cfg.new_abc =  xrange(1) : dx : xrange(2);
   % else cfg.new_abc IS the new abcissa
end

fprintf('new ordinate: %d points\n',length(cfg.new_ord))
fprintf('new abcissa: %d points\n',length(cfg.new_abc))

%% get the color ranges
if (isvel == 1)
   if (isempty(cfg.vrange))
      uvabs = abs(medfilt2d(u,3,3,20) + i*medfilt2d(v,3,3,20));
      uvabs = uvabs(:);
      goodi = find(~isnan(uvabs));
      maxuv = ceil(max(uvabs(goodi)));
      cfg.vrange = [-1 1]*maxuv;
   end
else % velocities are bad
   if (isempty(cfg.vrange))
      val = abs(medfilt2d(u,3,3,20));
      val = val(:);
      goodi = find(~isnan(val));
      cfg.vrange = [min(val(goodi)) max(val(goodi))];
   end
end   


% do labels/colorbar
if (isempty(cfg.vlines))
   cfg.vlines = best_ticks(cfg.vrange);
end

if (isempty(cfg.vlabels))
   cfg.vlabels = cfg.vlines;
end

if (isempty(cfg.vstep))
   steps = best_ticks(cfg.vrange);
   dv = mean(diff(steps));
   if length(steps) < 8
      cfg.clev = min(steps):dv/4:max(steps);
   else
      cfg.clev = min(steps):dv/2:max(steps);
   end
else
   cfg.clev = min(cfg.vrange) : cfg.vstep : max(cfg.vrange);
end

% set up the colormap:
cfg.clev = [cfg.vrange(1)-100*diff(cfg.vrange),...
            cfg.clev(:)' ,...
            cfg.vrange(end)+100*diff(cfg.vrange)];
nclev = length(cfg.clev);
cfg.cmap = mk_cmap(nclev - 1, 'jet');
cfg.cmapindex = 1:length(cfg.cmap(:,1));

if (cfg.newfig)
   figure
else
   hold off
end

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


new_u    = regrid(u, cfg.abc(:)', cfg.ord(:), cfg.new_abc(:)',...
                  cfg.new_ord(:), 1, 3);

if (isvel==1)
   new_v = regrid(v, cfg.abc(:)', cfg.ord(:), cfg.new_abc(:)' , ...
                  cfg.new_ord(:), 1, 3);
end
   

if (isvel == 1)
   subplot(211);
   hh =  contour_panel(cfg, new_u);
   title(cfg.ustr)
   handles.uax = hh.ax;
   handles.ucb = hh.cbar;
   
   subplot(212)
   hh = contour_panel(cfg, new_v);
   title(cfg.vstr)
   handles.vax = hh.ax;
   handles.vcb = hh.cbar;
else
   hh =  contour_panel(cfg, new_u);
   title(cfg.ustr)
   handles.uax = hh.ax;
   handles.ucb = hh.cbar;
end   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function hreturn = contour_panel(cfg, vel)


if (cfg.vfill == 1)
   [c,h1] = contourf(cfg.new_abc, cfg.new_ord,  vel, cfg.clev);
   set(h1, 'EdgeColor', 'none');
   hold on
else
   [c,h1] = contour6(cfg.new_abc, cfg.new_ord,  vel, cfg.clev);
   hold on
end   
set(gca,'ydir','reverse')
if (~isempty(cfg.ordmin))
   yl(cfg.ordmin, max(cfg.new_ord));
end


[c,h2] = contour6(cfg.new_abc, cfg.new_ord,  vel, cfg.vlines,'k');
   
cdata_direct(h1, cfg.clev, cfg.cmapindex(1));

if strcmp(cfg.abc_name,'lon')
   xlabel('longitude')
   lltick(gca,'x','lon')
elseif strcmp(cfg.abc_name, 'lat')
   xlabel('latitude')
   lltick(gca,'x','lat')
else % (d==3)
   xlabel('decimal day')
end

%set up the color bar
hcb1=cbar_direct(cfg.clev, cfg.cmap(cfg.cmapindex(1)), 'vert', cfg.cstr);
set(findobj(hcb1, 'Type', 'patch'), 'EdgeColor', 'none');
if (~isempty(cfg.vlabels'))
   set(hcb1,'ytick',cfg.vlabels,'fontsize',10);
end

hreturn.ax = h1;
hreturn.cbar = hcb1;