function jplotadcp(varargin)
% usage: jplotadcp
% NOTE: you must have just about everything on your path.  It's better to 
% call "jplotadcp" which will set your path and then call this tool.
%
% recommendation: run this from the base adcp directory of interest
% (i.e. the directory that has adcpdb/ and vector/ in it)
%
% starts up a window with a menu called ADCPmenu
% the menu has various options
% DOES NOT MAKE DATA: you must already have the appropriate files lying around

%strategy:
% all the data and the stuff are contained in userdata, accessible using tag
% set(adcpfighandle,'userdata') : HH is a structure with everything
%this is like Steve's driver: get the plot type, (use gxytzoom to grab a 
%segment, and plot it.

%another note on strategy: for historical reasons, vector and contoru came 
% first, so their info is contained in HH.[field]  
% plotpg and attplot came afterwards and have their own structure (well,
% plotpg does now anyway (99/09/16)).  Their structure is saved as a field
% of HH.


%Jules 99/08/23
% Jules 2000/2/13 - refurbishing gattplot and gplotpg
% Jules: 2001/05/30 - making it work without using zgrid or m_map

  %globals are for webvectt and webcont
  global MAX_INCHES 
  MAX_INCHES = 7;
  %should be a file in same dir as jplotadcp but NOT this file

  %these used to be globals.  They may be added to menus later
  HH.split_longitude=0;
  HH.comment='';
  HH.vector_this_level=[];

  if (isempty(varargin))
	%start things up  ----------
	call_init('first_init',HH);
  elseif strcmp(varargin{1},'loadadcp')
	loadadcp;
  elseif strcmp(varargin{1},'savefig')
	savefig;
  elseif strcmp(varargin{1},'mk_adcpvector')
	adcpfighandle = findobj('Tag','adcpfig');
	HH=get(adcpfighandle,'userdata');
	%%%% have to fix this:  need a better test of HH.x
	if (~isfield(HH,'x'))
	  disp('must load data before making a vector plot')
	else
          disp(sprintf('load a datafile of the form *_uv.mat\n'))
	  mk_adcpvector;
	end
  elseif strcmp(varargin{1},'mk_adcpcontour')
        adcpfighandle = findobj('Tag','adcpfig');
	HH=get(adcpfighandle,'userdata');
	if (~isfield(HH,'x'))
	  disp('must load data before making a contour plot')
	elseif (length(HH.x)<=2)
	  disp('dataset too small: load data before making a contour plot')
	else
          sprintf('load a datafile of the form *_uv.mat')
	  mk_adcpcontour(varargin{2});
	end
  elseif strcmp(varargin{1},'mk_pgoodplot')
        disp(sprintf('load the block directory file from (adcpdb/*dir.blk)\n'))
	mk_pgoodplot;
  elseif strcmp(varargin{1},'mk_attplot')
        disp(sprintf('load a ubprint file from (nav/ub*.mat)'))        
	mk_attplot;
  elseif strcmp(varargin{1},'print_help')
	  print_help(varargin{2});
  end
disp(' ')

  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                              functions                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function   call_init(load_or_noload,HH)

  global MAX_INCHES

    
% this should  have two duties:
% it should make a clear new figure with the right menus, ready to plot
% and it should load the data if necessary on the first round
%
% if load_or_noload is 'first_init' then try to load the default,
% otherwise ask: this is just for the first pass through


%deal with the figure first
%if there's not a figure, make one  
  if (strcmp(load_or_noload,'first_init'))
    adcpfighandle = figure;
	%these are replicated here to match what is in webcont.m
	set(adcpfighandle,'menubar','none')
	set(adcpfighandle,'color',[1 1 1])
	set(adcpfighandle,'posit',round(MAX_INCHES*[0 13 727 827]/11));
    set(adcpfighandle,'Tag','adcpfig');
	set(0,'defaulttextfontsize',14)
	set(0,'defaultaxesfontsize',14)
	set(0,'defaulttextfontweight','bold')
	set(0,'defaultaxesfontweight','bold')
	HH.fig=adcpfighandle;
	HH=mk_menus(HH);
  end  
  
  %now deal with the data
  if (strcmp(load_or_noload,'first_init'))
	%set the path (where to look first) ----------
	
	
	HH.default_path=pwd;
	defaultname='cont';
	set(adcpfighandle,'userdata',HH); 
	
	%try to load data from  the default location
	file = sprintf('%s/%s_uv.mat',HH.default_path,defaultname);
	if (exist(file))
	  [fpath,fname,fext,fver] = fileparts(file) ;
	  rootname=fname(1:end-3);
	  
	  eval(sprintf('load %s/%s_uv.mat',HH.default_path,rootname))
	  eval(sprintf('load %s/%s_xy.mat',HH.default_path,rootname))
	  
	  disp(sprintf('\n%s/%s_uv.mat\n%s/%s_xy.mat\n',...
		  HH.default_path,rootname,HH.default_path,rootname))
	  D=dir(sprintf('%s/%s_uv.mat',HH.default_path,rootname));
	  disp(sprintf('these files were made %s',D.date))
	  [SS,current_date]=unix('date -u');
	  disp(sprintf('current date is %s',current_date))
	  disp('load new data or start plotting')
	  
	  
	  %data
	  HH.x=xyt(1,:)';                    %Nx1 vectors
	  HH.x=rem(HH.x+360-HH.split_longitude,360)+HH.split_longitude; %split
	  	  
	  HH.y=xyt(2,:)';                    %Nx1 vectors
	  HH.dday=xyt(3,:)';                 %Nx1 vectors
	  HH.zc=zc;
	  HH.z=z;
	  HH.u=uv(:,1:2:end);                %ndepths x Nvelocities
	  HH.v=uv(:,2:2:end);                %ndepths x Nvelocities
	  HH.levstr='[-100:20:100]';           %a string for color contour levels
	  HH.llevstr='[-50 0 50]';          %a string for lines on contour
	  
	  if exist('year_base')~=1
		HH.year_base=get_yb; %set year_base in HH.year_base
	  else
		HH.year_base=year_base;
	  end
	  
  
	  set(adcpfighandle,'userdata',HH); 
	else
	  loadadcp
	end
  end
  
%end of call_init

% -----------------------------
function HH=mk_menus(HH);
    
  HH.m_label = uimenu(HH.fig,'Label','&ADCPmenu');
  HH.m_a = uimenu(HH.m_label,...
	  'Label','&Load adcp data','Callback','jplotadcp(''loadadcp'')');
  HH.m_b = uimenu(HH.m_label,...
	  'Label','&Save figure','Callback','jplotadcp(''savefig'')');
  HH.m_c = uimenu(HH.m_label,...
	  'Label','&Vector plot','Callback','jplotadcp(''mk_adcpvector'')');
  HH.m_d = uimenu(HH.m_label,'Label','&Contour plot');
  HH.m_e = uimenu(HH.m_label,...
	  'Label','&PercentGood plot','Callback','jplotadcp(''mk_pgoodplot'')');
  HH.m_e = uimenu(HH.m_label,...
	  'Label','&AshtechStats plot','Callback','jplotadcp(''mk_attplot'')');
  HH.m_f = uimenu(HH.m_label,'Label','&Help');
  
  %what kind of contour plot?
  HH.m_da = uimenu(HH.m_d,...
	  'Label','against time',...
	  'Callback','jplotadcp(''mk_adcpcontour'',''time'')');
  HH.m_db = uimenu(HH.m_d,...
	  'Label','against lat',...
	  'Callback','jplotadcp(''mk_adcpcontour'',''lat'')');
  HH.m_dc = uimenu(HH.m_d,...
	  'Label','against lon',...
	  'Callback','jplotadcp(''mk_adcpcontour'',''lon'')');

  %help!!
  HH.m_fa = uimenu(HH.m_f,...
	  'Label','overview',...
	  'Callback','jplotadcp(''print_help'',''overview'')');
  HH.m_fb = uimenu(HH.m_f,...
	  'Label','vector',...
	  'Callback','jplotadcp(''print_help'',''vector'')');
  HH.m_fc = uimenu(HH.m_f,...
	  'Label','contour',...
	  'Callback','jplotadcp(''print_help'',''contour'')');
  HH.m_fd = uimenu(HH.m_f,...
	  'Label','PercentGood',...
	  'Callback','jplotadcp(''print_help'',''pgood'')');
  HH.m_fe = uimenu(HH.m_f,...
	  'Label','AshtechStats',...
	  'Callback','jplotadcp(''print_help'',''att'')');


%------------------------------  
function loadadcp
  
  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');
  
  [uifile, uipath] =uigetfile('*_uv.mat',...
	  'Select a velocity file of the form *_uv.mat');
  if (uifile~=0)
	[fpath,fname,fext,fver] = fileparts(uifile) ;
	rootname=fname(1:end-3);
	
	eval(sprintf('load %s%s_uv.mat',uipath,rootname))
	eval(sprintf('load %s%s_xy.mat',uipath,rootname))
	
	disp(sprintf('\n%s%s_uv.mat\n%s%s_xy.mat\ndata loaded.',...
		uipath,rootname,uipath,rootname))
	
	%data
	HH.default_path = uipath;
	HH.x=unwrap_lon(xyt(1,:)');                    %Nx1 vectors
	
	HH.y=xyt(2,:)';                    %Nx1 vectors
	HH.dday=xyt(3,:)';                 %Nx1 vectors
	HH.zc=zc;
	HH.z=z;
	HH.u=uv(:,1:2:end);                %ndepths x Nvelocities
	HH.v=uv(:,2:2:end);                %ndepths x Nvelocities
	HH.levstr='[-100:20:100]';           %a string for color contour levels
	HH.llevstr='[-50 0 50]';          %a string for lines on contour

	if exist('year_base')~=1
	  HH.year_base=get_yb; %set year_base in HH.year_base
	else
	  HH.year_base=year_base;
	end

	set(adcpfighandle,'userdata',HH); 
  else
	disp(sprintf('file %s%s\ncannot be loaded',uipath,uifile))
  end

%------------------------------
function savefig
  
  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');
  
  [uifile, uipath] = uiputfile(sprintf('%s/*.ps',HH.default_path),...
	  'save figure to a file');
  file=sprintf('%s%s',uipath,uifile);     %JH 2000/2/13 I hope I did this 
  if (~strcmp(file(end-3:end),'.ps'))     %right - it won't default to
	file = [file,'.ps'];                  %file.ps if there's a directory     
  end					  %called 'file', it makes            
                                          %something called file/figure1.ps   
										  %  very aggravating                   
  if (uifile==0)
	disp('canceling save')
  else
	orient tall
	eval(sprintf('print -dpsc %s',file))

	[rootfilename,ext]=strtok(file,'.'); %this is probably risky
	sprintf('figure saved to %s.ps',rootfilename)
  end		
  
  
%------------------------------
function mk_adcpvector
  
  % x,y are positions (whole cruise), u,v are um,vm for the whole cruise
  % xyt = position time vector from adcpsect 
  % zc  = depths over which u,v were averaged   NOTE: this is "z" not "zc"
  % uv  = velocity data from adcpsect (Nx2 vector)
  % TT = temperatures from lst_temp
  % str is a string for the title
  % vec_scale is vector length (data units per inch)
  %% Script called by the websectt 

  if (~exist('m_vec'))
     warning('cannot make vector plot: must install m_map first')
  else
     adcpfighandle = findobj('Tag','adcpfig');
     HH=get(adcpfighandle,'userdata');
     
     disp('making a vector plot')
     %close all the graphics
     figure(adcpfighandle)
     while (length(find(strcmp(get(get(gcf,'children'),'type'),'axes')==1))>=1)
        hh=get(gcf,'children');
        hh_isaxes=strcmp(get(hh,'type'),'axes') ;
        hh_ii=find(hh_isaxes==1);
        delete(hh(hh_isaxes(1)))
     end  
     
     %first, pull it out from the data structure
     x=HH.x;
     y=HH.y;
     dday=HH.dday;
     u=HH.u;
     v=HH.v;
     zc=HH.zc;
     z=HH.z;
     
     if (length(zc)==length(z))
        zc=mid(z);
     end
     
     badi=find(isnan(x));
     x(badi)=[];y(badi)=[];dday(badi)=[];u(:,badi)=[];v(:,badi)=[];
     
     ii=gxytzoom(x,y,dday);
     length(ii)
     vector_this_level=get_vectorlevel(z,zc);
     comment=get_comment; %writes comment to HH.comment
     HH.comment = comment;
     
     %next use only the relevant indices
     x=x(ii);
     y=y(ii);
     dday=dday(ii);
     u=u(vector_this_level,ii)';
     v=v(vector_this_level,ii)';
     
     %let's fake it a bit - replot vectors twice (since we don't have colors)
     TT=-99+0*x;
     xyt=[x y dday]';
     uvm=[u(:) v(:)]; %let's try this
                      %these have to be the levels surrounding the average
                      % (zc"minmax"???)
     zcm=[z(vector_this_level) z(vector_this_level+1)];  
     %NOTE: if no regridding, z are all zero.  show this in the title
     if (z(vector_this_level)==0)
        zcm=[vector_this_level vector_this_level+1];
        level_or_depth='level';
     else
        level_or_depth='depth';
     end
     
     
     if (isfield(HH,'vec_scale'))
        vec_scale=get_vecscale(sprintf('%f',HH.vec_scale));
        HH.vec_scale=vec_scale;
     else
        vec_scale=get_vecscale(sprintf('%f',1));
        HH.vec_scale=vec_scale;
     end 
     
     titlestr=get_titlestr(HH.year_base,dday,ii,comment);
     figure

     gvectt(x,y,u,v, xyt, zcm, uvm, TT, titlestr,vec_scale,level_or_depth );
     date_it;
     set(adcpfighandle,'userdata',HH);
  end


%------------------------------
function gvectt(allx, ally, allu, allv, ...
   xyt, zcm, uvm, TT, str, vec_scale, level_or_depth)
% function gvectt(allx, ally, allu, allv, ...
%           xyt, zcm, uvm, TT, str, vec_scale, level_or_depth)
%
%%%% make a nice vector plot of shipboard ADCP data.  (This was webvectt)
% allx, ally are positions        -> black vectors
% allu, allv are velocities -> black vectors
% xyt = position time vector from adcpsect       -> colored vectors
% zc  = depths over which u,v were averaged
% uv  = velocity data from adcpsect (Nx2 vector) -> colored vectors
% TT = temperatures from lst_temp
% str is a string for the title
%   optional:
% vec_scale is vector length in vector data units per inch (input to m_vec)
% level_or_depth is 'level' or 'depth'
%
% If only one set of vectors is needed, put positions and velocities
% in the first four arguments.
% All arguments are required, though.
% ? How should unused arguments be supplied?  NaN? empty?



% JH 00/10/09
% moved function "topocolors" to ../utils
% moved function "decimate_topo" to ../utils
% m_fixlon and map_range(x,y) added 08/06/'01  CA


global MAXTT MINTT AUTOTRANGE

if nargin < 11,
   level_or_depth = 'depth'
end
if nargin < 10,
   maxuv = max(sqrt(uvm(:,1).^2+uvm(:,2).^2));
   if  maxuv > 1,
      vec_scale = 2.0;
   elseif maxuv > 0.4,
      vec_scale = 1.0;
   else
      vec_scale = 0.5;
   end
end

% page setup parameters--move outside the function?
set(gcf, 'DefaultAxesFontSize', 12, 'DefaultTextFontSize', 12)
orient tall

xyt = xyt';
xx = xyt(:,1);   %get ranges from these
yy = xyt(:,2);

uu = uvm(:,1);
vv = uvm(:,2);

badT =  ((mean(TT) < -98) | any(isnan(TT)));  % -99 is missing T from
                                              % ascii lst_temp output

%get horizontal ranges

% above %% material substitued with this single function (& see below)
[lonrange, latrange] = map_range(xx, yy);

%xtick = round(lonrange(1)):floor(diff(lonrange)/4):floor(lonrange(2));
%ytick = round(latrange(1)):floor(diff(latrange)/4):floor(latrange(2));

%where the legend goes
xykey = [lonrange(1)+.05*diff(lonrange)  latrange(1)+diff(latrange)*.1];

% use smith-sandwell if whole section is inside +/- 70deg
if (max(abs(latrange))<69)
   %use medium decimation for the sections
   if exist('ss_block'),
      max_llr = max(diff(lonrange), diff(latrange));
      if max_llr  > 15, nsub = 9;
         elseif max_llr  > 5, nsub = 3;
         else nsub = 1;
      end
   end
   fprintf('getting topography (subsample by %d) from Smith-Sandwell', nsub)
   % eval is used to hide ss_block from the compiler--otherwise an
   % error will result even if this block of code is never executed.
   %
   %extract topography  1 degree around the outside of the data region
   eval('[top_lon, top_lat, topog] = ss_block(lonrange + [-1 1] , latrange + [-1 1], nsub);')
   [top_lat, top_lon, topog] = decimate_topo(top_lat, top_lon, topog, 60);
   % lon-clipping bug in m_map:
   [topog top_lon] = m_fixlon(top_lon, top_lat, topog, lonrange);  
else
   fprintf('getting topog from m_elev\n')
   %extract topography  1 degree around the outside of the data region
   [topog, top_lon, top_lat]=m_elev([ lonrange  latrange]  + [-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, lonrange);  
end

topo_clev = [-6000:500:500];  % Topography contour levels.

topo_cmap = topocolors(topo_clev);
topo_irange =  [1 size(topo_cmap,1)]; % indices into topo_cmap

temperature_cmap = jet(64);
colormap([topo_cmap ; temperature_cmap]);

% Temperature color indexing.
irange = [1 64];
irange = irange + size(topo_cmap, 1);  % makes indices into temperature_cmap

if (AUTOTRANGE==1)
   trange = [min(TT) max(TT)];
   disp('automatically ranging temperature')
else
   trange=[MINTT MAXTT];  %set in webglobs
end
if (badT)
   iT = zeros(size(TT)) + irange(1);
   shaftwidth = 0.5; headlength = 4;
else
   iT = c_index(TT, trange, irange, NaN);
   shaftwidth = 2; headlength = 10;
end


m_proj('merc', 'lon', lonrange, 'lat', latrange);
%%   [cmat, htopo] = m_tbase('contourf', topo_clev);
%% EF: we add some extreme values to topo_clev for contouring
%   so that the clipping in cf_index can work; anything
%   outside the topo_clev range now gets mapped to the extreme
%   values of the range.
[cmat, htopo] = m_contourf(top_lon,top_lat,topog, ...
                  [-100000 topo_clev 100000]);
set(htopo, 'EdgeColor', 'none');
m_coast;
%m_coast('patch', [0.85 0.9 0.8]);
%m_grid('tickdir','out','xtick',xtick,'ytick',ytick);
m_grid('tickdir','out');

cf_index(htopo, topo_clev, topo_irange);
hold on


%put on all the vectors black

[hvp] = m_vec(vec_scale, allx,ally,allu,allv,'k',...
         'headlength',headlength/2, 'shaftwidth',shaftwidth/2,...
         'CDataMapping','direct', 'EdgeColor','k');

[hvp] = m_vec(vec_scale, xx,yy,uu,vv, iT,...
         'headlength',headlength, 'shaftwidth',shaftwidth,...
         'CDataMapping','direct', 'EdgeColor','k');

[hkp,hkt] = m_vec(vec_scale, xykey(1), xykey(2), 0.5, 0, 'm',...
       'key',' 50 cm/s', 'headlength',headlength,...
       'shaftwidth',shaftwidth,'EdgeColor','k');
set(hkt,'FontSize',10,'color','m');

h_dcb = dcolbar( topo_clev/1000, 'vert', 'Depth (km)');
h_dcbp = findobj(h_dcb,'Type','patch');
cf_index(h_dcbp, topo_clev/1000, topo_irange);

if (strcmp(level_or_depth,'depth'))
   title(sprintf('%s, %.0f-%.0f m',str, min(zcm), max(zcm)  ));
else
   title(sprintf('%s, depth levels %.0f-%.0f',str, min(zcm), max(zcm)  ));
end

if (~badT)
   ind_cbar( trange, irange, 'horiz', 'SST (^{o}C)')
   center_cbar(h_dcb);
end
%------------------------------
function mk_adcpcontour(dstr)
  % webplott(lat, xyt, d, zc, uv ,levs)
  %
  % make a nice contour plot of shipboard ADCP data.
  % lat = vector of latitudes or longitudes for regriding and plotting
  % xyt = position time vector from adcpsect 
  % d   = direction index (1=longitude, 2=latitude,3=dday)
  % zc  = depths for contouring
  % uv  = velocity data from adcpsect
  % ts  = title will be ['Zonal Velocity'|'Meridional Velocity' ts]
  %levs = contour levels
  
  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');
  disp('making a contour plot')

  %first, pull it out from the data structure

  x=HH.x;
  y=HH.y;
  dday=HH.dday;
  u=HH.u;
  v=HH.v;
  zc=HH.zc;
  z=HH.z;

  badi=find(isnan(x));
  x(badi)=[];y(badi)=[];dday(badi)=[];u(:,badi)=[];v(:,badi)=[];

  ii=gxytzoom(x,y,dday);
  length(ii)
  gridlength=100;

  %set things up for calling webcont
  %set up d
  if (strcmp(dstr,'lon'))
        arange=[min(x(ii)) max(x(ii))];
	abcissca_grid=[min(arange):diff(arange)/gridlength:max(arange)];
	d=1;
	disp('select data to contour against longitude')
  elseif (strcmp(dstr,'lat'))
        arange=[min(y(ii)) max(y(ii))];
	abcissca_grid=[min(arange):diff(arange)/gridlength:max(arange)];
	d=2; 
	disp('select data to contour against latitude')
  elseif (strcmp(dstr,'time'))
        arange=[min(dday(ii)) max(dday(ii))];
	abcissca_grid=[min(arange):diff(arange)/gridlength:max(arange)];
	d=3;
	disp('select data to contour against time')
  else
	error('incorrect call of mk_adcpcontour in jplotadcp')
  end

  %set up xyt
  xyt=[x(ii) y(ii) dday(ii)]';
  uv=0*[u(:,ii) v(:,ii)];
  uv(:,1:2:end)=u(:,ii);
  uv(:,2:2:end)=v(:,ii);

  comment=get_comment; %writes comment to HH.comment
  HH.comment=comment;

  HH.levstr=get_levs(HH.levstr); %this is string for color contours
  eval(['levs=',HH.levstr,';'])
  HH.llevstr=get_levs(HH.llevstr); %this is string for black contours
  eval(['llevs=',HH.levstr,';'])
  
  titlestr=get_titlestr(HH.year_base,dday,ii,comment);

  if (sum(zc)==0) %data were not regridded
	zc=[1:length(zc)]';
  end


  gcont(abcissca_grid, xyt, d, zc, uv, titlestr,levs(:)',llevs(:)' )

  fprintf('minimum u = %4.1f, maximum u = %4.1f\n',...
	  min(min(100*u)),max(max(100*u)))
  fprintf('minimum v = %4.1f, maximum v = %4.1f\n',...
	  min(min(100*v)),max(max(100*v)))
  
  date_it;
  set(adcpfighandle,'userdata',HH);

%------------------------------
function gcont(abc, xyt, d, zc, uv, ts ,levs,llevs)

  % gcont(lat, xyt, d, zc, uv,levs )
  %
  % make a nice contour plot of shipboard ADCP data.
  % lat = vector of lats, longs or times for regriding and plotting
  % xyt = position time vector from adcpsect 
  % d   = direction index (1=longitude, 2=latitude,3=dday )
  % zc  = depths for contouring
  % uv  = velocity data from adcpsect
  % ts  = title will be ['Zonal Velocity'|'Meridional Velocity' ts]
  % levs = contour levels
  
  global MAX_INCHES
  
  u = regrid(uv(:,1:2:end),xyt(d,:),zc,abc,zc,1,3)*100;
  v = regrid(uv(:,2:2:end),xyt(d,:),zc,abc,zc,1,3)*100;
  
  set(0,'defaulttextfontsize',14)
  set(0,'defaultaxesfontsize',14)
  set(0,'defaulttextfontweight','bold')
  set(0,'defaultaxesfontweight','bold')
  set(gcf,'menubar','none')
  set(gcf,'color',[1 1 1])
  
%  sppi=get(0,'screenpixelsperinch');
%  set(gcf,'posit',round(MAX_INCHES*[0 13 727 827]/11));
  
  
  if ( ~exist('levs') & ~exist('llevs')  )  %then it wasn't passed into the contour routine
    maxuv=100*max(max(abs(uv)));
    if (maxuv>300)
  	disp('YOU ARE IN KEYBOARD in webcont')
  	disp('the maximum velocity in this section exceeded 300cm/s.')
  	disp('is this correct?')
  	disp('typing the word "return" is ok but will leave a bad contour plot')
  	keyboard
    end
    if (maxuv>200)
  	levs = [-300:20:300];
  	llevs = [-200 -100 100 200];
    elseif ((maxuv>=100) & (maxuv<200))
  	levs = [-200:20:200];
  	llevs = [-100 100];
    elseif ((maxuv>=50) & (maxuv<100))
  	levs = [-100:10:100];
  	llevs = [-50 50];
    else
  	levs = [-50:5:50];
  	llevs = [-40 -30 -20 -10 10 20 30 40];
    end
  end

  hold off  

  ha1 = subplot(211);
  contour_panel(abc, zc, u, levs, llevs, d);
  
  title(sprintf('Zonal Velocity%s', ts))
  
  %%%%%%%

  subplot(212)
  contour_panel(abc, zc, v, levs, llevs, d);
  title(sprintf('Meridional Velocity%s', ts))
  
  
  set(0,'defaulttextfontsize',10)
  set(0,'defaultaxesfontsize',10)
  
  %% EF: what is the purpose of this phantom axes object?
  axes
  set(gca,'posit',[0.05 0.03 .9 .08])
  set(gca,'visible','off')
  
  set(0,'defaulttextfontweight','normal')
  set(0,'defaultaxesfontweight','normal')
  
  
%------------------------------
function contour_panel(ord, zc, u, levs, llevs, d)


[c,h] = contourf(ord,zc,u,levs);
  set(h, 'EdgeColor', 'none');
  caxis([levs(1) levs(end-1)])
  dcolbar(levs, 'vert', 'cm s^{-1}');
  set(gca, 'ydir', 'reverse', 'TickDir', 'out')
  ylim = get(gca, 'YLim'); ylim(1) = 0; set(gca, 'YLim', ylim);
  
  % Try to prevent collisions of the tick labels after
  % conversion to lat/lon by lltick; this could also be done
  % by leaving the ticks in place and just deleting every other
  % label after running lltick.
  xt = get(gca, 'XTick');
  if length(xt) > 6,
     n1 = length(num2str(xt(1))); n2 = length(num2str(xt(2)));
     if n1 > n2,
        xt = xt(2:2:end);
     else
        xt = xt(1:2:end);
     end
  end
  
  if d==1,
   xlabel('longitude')
   lltick(gca,'x','lon')
  elseif  d==2
   xlabel('latitude')
   lltick(gca,'x','lat')
  else % (d==3)
   xlabel('decimal day')
  end
  
  ylabel('depth (m)')
  hold on
  [c,h] = contour(ord,zc,u, llevs, 'k');
  [c,h] = contour(ord,zc,u, [0 0], 'k');
  set(h, 'linewidth', 2);
  set(gca, 'Box', 'on', 'Layer', 'top');
  
  colormap('jet');
  

%------------------------------
function mk_pgoodplot
  %set up the defaults for pgstruct
  %notes:
  %  (1) if it has been run before, HH should contain pgstruct.[fields]
  %         and we default to those if reasonable
  %  (2) check integrity of answers; repeat inputdialog if bad answers
  %
  % there is an inconsistency here between vector and contour which have 
  %    all their info in HH.[field] and attplot and pgplot which have all 
  %    their info in structures within HH (eg. pgstruct)
  % ---> TRYING here to keep pg info in pgstruct
  
  figure
  set(gcf,'defaulttextfontsize',12)
  set(gcf,'defaultaxesfontsize',12)
  set(gcf,'defaulttextfontweight','normal')
  set(gcf,'defaultaxesfontweight','normal')

  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata'); %this has pgstruct in it or not

  %initialize or change pgstruct

  %get default path for adcpdb
  if (isfield(HH,'pgstruct')) %like /home/[stuff]/adcp/adcpdb/
	this_dir  = HH.pgstruct.dbpath; 
	stopi=find(this_dir==filesep);
	startpath=this_dir(1:stopi(end-1)-1); %like /home/[stuff]/adcp
  elseif (isfield(HH,'default_path'))
	startpath=HH.default_path;
  else
	startpath=pwd;
  end
  [pgstruct.dbname,pgstruct.dbpath] = get_db(startpath);

  %get the yearday
  if (isfield(HH,'pgstruct'))
	defstr=sprintf('%f',HH.pgstruct.start_dd);
  elseif (isfield(HH,'dday'))
	defstr=sprintf('%f',floor(HH.dday(1)));
  else
	today=clock;
	defstr=sprintf('%d',floor(to_day(today(1),today)));
  end
  
  pgstruct.start_dd=get_dday(defstr);   % starting decimal day (required)

  %get the yearbase
  if (isfield(HH,'pgstruct'))   %use revious pg values if possible
	defstr=sprintf('%d',HH.pgstruct.year_base);
  elseif (isfield(HH,'year_base')) %otherwise use previous year_base
	defstr=sprintf('%d',HH.year_base);
  else

	defstr='';
  end
  pgstruct.year_base=get_yb(defstr); %set year_base in HH.year_base
  
  %get a comment for this cruise
  if (isfield(HH,'pgstruct'))
	defstr = HH.pgstruct.comment;
  elseif (isfield(HH,'comment'))
	defstr = HH.comment;
  else
	today=clock;
	defstr=sprintf('%4d',today(1));
  end
  pgstruct.comment = get_comment(defstr);     % title for plots (required)
	
  %now set the defaults: start with defaults, prompt for some changes
  pgstruct.PGOOD_MIN=0;        %these are not changed
  pgstruct.PGOOD_MAX=100;      % not changed
  pgstruct.interval_dd=4;      %not changed
  pgstruct.nbins = 60;         % prompt for change               line 1
  pgstruct.icolor=1;           % prompt for change               line 2
  pgstruct.reduce_res=0;       % prompt for change               line 3
  pgstruct.days_per_panel=1;   % prompt for change               line 4
  

  keepgoing = 1;
  while (keepgoing)
	keepgoing = 0;  %hope they get it right the first time
	title='percent good plot: set defaults';                       
	prompt={'number of bins';								 %line 1
	  'plot in color [c,C] or grayscale [g,G] ';			 %line 2
	  'reduce resolution ? [y,Y,n,N]';	             		 %line 3
	  'integer number of days per panel (there are 4 panels) '};  %line 4
	numlines=1;
	def={ sprintf('%d',pgstruct.nbins);                      %line 1	
	  'color';                                               %line 2
	  'no';                                         		     %line 3
	  sprintf('%d',pgstruct.days_per_panel)};				 %line 4
	  
	  returnstring = inputdlg(prompt,title,numlines,def);

	  %now do error checking
	  pgstruct.nbins=str2num(returnstring{1});
	  if (rem(pgstruct.nbins,1)~=0)
		warning('must choose an integer number bins to plot')
		keepgoing=1
	  end
	  
	  incolor=returnstring{2};
	  if ( strcmp(incolor(1),'c') | strcmp(incolor(1),'C') )
		pgstruct.icolor=1;
	  elseif ( strcmp(incolor(1),'g') | strcmp(incolor(1),'G') )
		pgstruct.icolor=0;
	  else
		warning('must choose the string ''color'' or ''grayscale'' ')
		keepgoing=1;
	  end
	  
	  reduceres=returnstring{3};
	  if ( strcmp(reduceres(1),'y') | strcmp(reduceres(1),'Y') )
		pgstruct.reduce_res=1;
	  elseif ( strcmp(reduceres(1),'n') | strcmp(reduceres(1),'N') )
		pgstruct.reduce_res=0;
	  else
		warning('reduce resolution?? choose ''yes'' or ''no'' ')
		keepgoing=1;
	  end

	  pgstruct.days_per_panel=str2num(returnstring{4});
	  if (isempty(pgstruct.days_per_panel))
		warning('must choose number of days per panel (eg. 1 or 2)')
		keepgoing=1;
	  end
	end
  
  
  %this has to match the following:
  % 4 panels is hardwired 
  pgstruct.interval_dd=4*pgstruct.days_per_panel;

  HH.pgstruct=pgstruct;  %isn't this wild?!
  set(adcpfighandle,'userdata',HH);
  
  gplotpg(pgstruct);

%------------------------------
function mk_attplot
  %set up the defaults for plotpgstruct
  %things to improve:
  % better rememberance of previous stuff
  % suggest dday from *.mat file
  % suggest year_base from *.mat file
  % test if the file loaded will work (does it have the right fields)
  % 
  
  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');

  if (~isfield(HH,'ubpath'))
	HH.ubpath=HH.default_path;
  end
  
  [attstruct.attfile,ubpath] = get_ubfile(HH.ubpath);
  HH.ubpath=ubpath;
  %now make the file match what we need, which is path/prefix (not .mat)
  attstruct.attfile = sprintf('%s/%s', ubpath,attstruct.attfile(1:end-4));
  
  attstruct.start_dd=get_dday;    % starting decimal day       (required)
  if (isfield(HH,'year_base'))
	attstruct.year_string=sprintf('%d',HH.year_base);
  else
	attstruct.year_string=sprintf('%d',get_yb); %set year_base in HH.year_base
  end
  HH.year_base=sscanf(attstruct.year_string,'%d');
  
  set(adcpfighandle,'userdata',HH);
    
  attstruct.title = get_comment;     % title for plots            (required)
 
  gattplot(attstruct);
%------------------------------
function print_help(helpstring)
  % echo help message for each type of plot
if (strcmp(helpstring,'overview'))
  string = [...
'This program is best run from the adcp cruise directory (where you would ',...
  'find newday.prl).  In general, you should load data and then make the ',...
  'plots.  "LoadData" is for vector or contour plots.  PercentGood and ',...
  'AshtechStats prompt for their own type of data.  CAUTION: BEWARE the ',... 
  'distinction between decimal day (noon Jan 1 = 0.5, these are used ',...
  'in the adcp processing) as opposed to the one-based naming system used ',...
  'for the named files (serially logged data).  If you process ONE day of ',...
  'data with newday.prl, you will type "newday.prl 308", and all the ',...
  'files will be named *308*.*, but the decimal day starting the data in ',...
  'those files will be 307.  END CAUTION.  More details for each ', ...
  'option are also available under the help menu.'];
  hh=helpdlg(string,'Overview help');
elseif (strcmp(helpstring,'vector'))
 string=[... 
 'Load data using the LoadData menu item.  The file to choose should have ',...
 'the form "*_uv.mat" and will probably be in the vector/ subdirecory of ',...
 'the main  processing directory for a given cruise.   Select the ',...
 'appropriate *_uv.mat file and the corresponding *_xy.mat file will',...
 'also be loaded.  Then choose the "Vector" menu option and zoom in on ',...
 'the region you want to plot.  (Use the buttons to change the axes you ',...
 'use to zoom, to reset, or to accept the region.  NOTE: do your zooming ',...
 'starting in the light blue region or you will have to reset the axes).',...
 'Sometimes the topography does not show up on the vector plot: it''s ',...
 'still there, but you''ll have to save the file first and look at the ',...
 'postscript file.  You can try either decreasing the region you''re ',...
 'choosing, or make sure  you''re using vector/*_uv.mat for vector plots ',...
 '(the contour/*_uv.mat data will sometimes have this problem). ',...
 'Use the "Save figure" menu item to save this figure to a postscript file.'];
  hh=helpdlg(string,'Vector');
elseif (strcmp(helpstring,'contour'))
  string=[...
 'Load data using the LoadData menu item.  The file to choose should have ',...
 'the form "*_uv.mat" and will probably be in the contour/ subdirecory of ',...
 'the main  processing directory for a given cruise.   Select the ',...
 'appropriate *_uv.mat file and the corresponding *_xy.mat file will ',...
 'also be loaded.  Then choose the "Contour" menu option and the ',...
 'independent variable for your plot.  Then zoom in on ',...
 'the region you want to plot.  (Use the buttons to change the axes you ',...
 'use to zoom, to reset, or to accept the region.  NOTE: do your zooming ',...
 'starting in the light blue region or you will have to reset the axes).',...
 'Use the "Save figure" menu item to save this figure to a postscript file'];
  hh=helpdlg(string,'Contour');
elseif (strcmp(helpstring,'pgood'))
  string=[...
  'Percent good plots default to 4 vertical panels, one day per panel. ',...
  'The program will extract 4 days of data from the database starting ',...
  'at the decimal day you choose when prompted.  If you choose an ',...
  'invalid decimal day, the program will indicate that it couldn''t ',...
  'find any data: try again and check your decimal day (this is a ',...
  'zero-based decimal day).  You will then be prompted to choose the ',...
  'database from which to extract data.  You must choose a file of the ',...
  'form "*dir.blk" and it will probably be located in the adcpdb/ ',...
  'subdirectory of the main  processing directory for a given cruise. ',...
  'You will be promted for "cruisename" which will be used as a comment ',...
  'in the figure title.  NOTE: this routine puts up a new figure, so ',...
  'you''ll have to use that new window''s menus or the command line to ',...
  'save the figure to disk. '];
  hh=helpdlg(string,'PercentGood');
elseif (strcmp(helpstring,'att'))
  string=[...
'Ashtech statistic plots default to 4 vertical panels, one day per panel. ',...
  'The program will extract 4 days of data from the database starting ',...
  'at the decimal day you choose when prompted.  If you choose an ',...
  'invalid decimal day, the program will indicate that it couldn''t ',...
  'find any data: try again and check your decimal day (this is a ',...
  'zero-based decimal day).  You will then be prompted to choose the ',...
  'database from which to extract data.  You must choose a file of the ',...
  'form "ub*.mat" and it will probably be located in the nav/ ',...
  'subdirectory of the main  processing directory for a given cruise. ',...
  'You will be promted for "cruisename" which will be used as a comment ',...
  'in the figure title.  NOTE: this routine puts up two new figures, so ',...
  'you''ll have to use that new window''s menus or the command line to ',...
  'save the figures to disk. CAUTION: BEWARE the ',... 
  'distinction between decimal day (noon Jan 1 = 0.5, these are used ',...
  'in the adcp processing) as opposed to the one-based naming system used ',...
  'for the named files (serially logged data).  If you process ONE day of ',...
  'data with newday.prl, you will type "newday.prl 308", and all the ',...
  'files will be named *308*.*, but the decimal day starting the data in ',...
  'those files will be 307.  END CAUTION.'];
  hh=helpdlg(string,'AshtechStats');
else 
  error('didn''t match string for print_help')
end
  
  
%------------------------------
function [dbname,dbpath]=get_db(dbpath)
  %try loading blockdir from here
  
  [uifile, uipath] = uigetfile(sprintf('%s/adcpdb/*dir.blk',dbpath),...
	  'choose block directory file (*dir.blk)');
  if (uifile~=0)
	disp(sprintf('loading %s%s',uipath,uifile))
	[fpath,fname,fext,fver] = fileparts(uifile) ;
    dbname=fname(1:end-3);
	dbpath=uipath;
  end	

%------------------------------
function [ubfile,defpath]=get_ubfile(ubpath)
  %try loading blockdir from here
  
  [ubfile, defpath] = uigetfile(sprintf('%s/nav/ub*.mat',ubpath),...
	  'choose a ubprint att file (*.mat)');
  defpath = defpath(1:end-1);
  
%------------------------------

function start_dday=get_dday(defstr);
  
  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');

  if (nargin==1)
	def={defstr};
  elseif (isfield(HH,'dday'))
	def={sprintf('%d',floor(min(HH.dday(1))))};
  else
	def={' '};
  end
  
  title='starting decimal day';
  prompt={'enter starting decimal day'};
  lineNo=1;
  returnstring=inputdlg(prompt,title,lineNo,def);
  ddaystr=returnstring{lineNo};
  start_dday=sscanf(ddaystr,'%f');
  
%------------------------------

function titlestr=get_titlestr(year_base,dday,ii,comment)


  if (isempty(comment))
	comment=[' '];
  end
  
  goodi = find(~isnan(dday));
  mindatestr=to_date(year_base,min(dday(goodi)));
  maxdatestr=to_date(year_base,max(dday(goodi)));
  titlestr=sprintf(' %s [%s to %s]',...
	  comment,mindatestr(1:10),maxdatestr(1:10));
  
 
%------------------------------
function year_base=get_yb(defstr)

  %sets HH.year_base and returns it as a function (-1 indicates failure)
  %only updates HH.year_base if it seems OK
  
  keepgoing=1;

  while (keepgoing)
	prompt = {'enter year_base: 4 digits'};
	datestr=eval('date');
	if (nargin==1)
	  def={defstr};
	elseif (isfield('HH','year_base'))
	  def={sprintf('%d',HH.year_base')};
	else
	  def={datestr(end-3:end)};
	end
	title='decimal day YEAR base';
	lineNo=1;
	returnstring=inputdlg(prompt,title,lineNo,def);
	if (length(returnstring)~=0)
	  string=returnstring{lineNo};
	  num=sscanf(string,'%d');
	  
	  if (length(string)~=4) | (num<1970) 
		year_base=-1;
		beep
		disp('must enter a 4 digit year')
	  else
		year_base = num;
		keepgoing=0;
	  end
	end
  end
  
disp(sprintf('year_base is %d',year_base))

%------------------------------
function vector_this_level=get_vectorlevel(z,zc);
%prompt user for what level to do the vectors at  

  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');
  keepgoing=1;

  %note: some z and zc are all zeros
  
  if sum(z)==0
	disp('NOTE: this is  the INDEX of the center of a pregridded dataset')
	
	while (keepgoing)
	  
	  prompt={sprintf('choose a center depth index from: 1 to  %d',...
			length(zc))};
	  
	  if (isempty(HH.vector_this_level))
		index=min(length(zc),min(3,round(length(zc)/3)));
		def={sprintf('%d',index)}; %default depth center
	  else
		def={sprintf('%d',HH.vector_this_level)};
	  end
	  													
	  title=sprintf('INTEGER INDEX of average depth for the vector plot %s');
	  
	  lineNo=1;
	  
	  returnstring=inputdlg(prompt,title,lineNo,def);
	  if (length(returnstring)~=0)
		string=returnstring{lineNo};
		num=sscanf(string,'%d');
		
		if ( (num<1) | (num>length(zc)))
		  vector_this_level=-1;
		  beep
		else
		  [mindist,index]=min(abs(num-zc));
		  vector_this_level = num;
		  HH.vector_this_level = vector_this_level;
		  keepgoing=0;
		end
	  end
	end
  else
	disp('NOTE: this is just the depth closest to the center of a pregridded dataset')
	while (keepgoing)
	  
	  if length(zc)<10
		rngstring=sprintf('%3.1f ',zc(:));
		zstring=[];
	  else
		[mm,ss,nn]=mstdgap(diff(z));
		if (ss<1)
		  % even grid in z
		  zstring=sprintf('(dz=%dm)',fix(mean(diff(z))));
		  rngstring=sprintf('z=[%3.1f, ..., %3.1f] ',	zc(1),zc(end));
		else
		  zstring=('(uneven grid');
		  rngstring=sprintf('z=[%3.1f, %3.1f, ...,  %3.1f, %3.1f] ',...
			  zc(1),zc(2),zc(end-1),zc(end));
		end
	  end
	  string=sprintf('choose a center depth from: %s %s',rngstring,zstring);
	  prompt = {string};
	  
	  if (isempty(HH.vector_this_level))
		def={'100'}; %default depth center
	  else
		def={sprintf('%f',zc(HH.vector_this_level))}; %default depth center
	  end		

	  title=sprintf('average depth for the vector plot %s');
	  
	  lineNo=1;
	  
	  returnstring=inputdlg(prompt,title,lineNo,def);
	  if (length(returnstring)~=0)
		string=returnstring{lineNo};
		num=sscanf(string,'%f');
		
		if ( (num<min(z)) | (num>max(z)) )
		  vector_this_level=-1;
		  beep
		else
		  [mindist,index]=min(abs(num-zc));
		  vector_this_level = index;
		  HH.vector_this_level = vector_this_level;
		  keepgoing=0;
		end
	  end
	end
  end
  
  set(adcpfighandle,'userdata',HH);
 
%------------------------------
function vec_scale=get_vecscale(defstr)

  %gets a vector scale
  
  prompt = {'smaller number makes longer vectors'};
  title='vector scale: m/s per inch';
  lineNo=1;
  returnstring=inputdlg(prompt,title,lineNo,{defstr});
  vec_scale=str2num(returnstring{lineNo});  
  
%------------------------------

function levstr=get_levs(deflevstr)

  title='contour levels';
  prompt={'enter contour levels (matlab notation)'};
  lineNo=1;
  returnstring=inputdlg(prompt,title,lineNo,{deflevstr});
  levstr=returnstring{lineNo};
  
%------------------------------
function comment=get_comment(defstr)

  %sets HH.year_base and returns it as a function (-1 indicates failure)
  %only updates HH.year_base if it seems OK
  

  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');

  prompt = {'enter cruisename (or short comment)'};
  if (nargin==1)  %first priority is what was passed in
	if (isempty(defstr))
	  def={''};
	else
	  def={defstr};
	end
  elseif (isempty(HH.comment))
	def={''};
  else
	def={HH.comment};
  end

  title='comment for figure';
  lineNo=1;
  returnstring=inputdlg(prompt,title,lineNo,def);
  comment=returnstring{lineNo};
  HH.comment = comment;
  set(HH.fig,'userdata',HH);
  
%------------------------------

function midz=mid(z)
  
  if (length(z)>1)
	midz= (z(1:end-1)+z(2:end))/2;
  else
	midz=z;
  end
  
%------------------------------------------------------------

function [lonrange, latrange] = map_range(x, y)
lonrange = [min(x) max(x)];
latrange = [min(y) max(y)];
ymid = mean(latrange);
xmid = mean(lonrange);
xsc = cos(ymid * pi/180);
h = diff(latrange);
w = diff(lonrange)*xsc;
s = max([h w]);
h = max([h, s/2])*1.3;
w = max([w, s/2])*1.3;

lonrange = xmid + 0.5 * [-w, w] / xsc;
latrange = ymid + 0.5 * [-h, h];

latrange(1) = max([-80, latrange(1)]);
latrange(2) = min([80, latrange(2)]);
