function gplotadcp(varargin)
% usage: gplotadcp
% NOTE: you must have just about everything on your path.  It's better to 
% call "gplotadcp" 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 contour 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
% making it work with uh programs tree (specifically autovect and autocont)


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

  %these used to be globals.  They may be added to menus later
  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},'savedata')
     savedata;
  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_panelplot')
     disp(sprintf('load the block directory file from (adcpdb/*dir.blk)\n'))
     if (nargin == 2)
        mk_panelplot(varargin{2});
     end
  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(adcpfighandle,'defaulttextinterpreter','tex');
   set(adcpfighandle,'name','gplotadcp', 'numbertitle', 'off');
	set(adcpfighandle,'defaulttextfontsize',12)
	set(adcpfighandle,'defaultaxesfontsize',12)
	set(adcpfighandle,'defaulttextfontweight','bold')
	set(adcpfighandle,'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=unwrap_lon(HH.x);
	  	  
	  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
     HH.ii = 1:length(HH.x);
	  
	  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','gplotadcp(''loadadcp'')');
  HH.m_b = uimenu(HH.m_label,...
	  'Label','&Save figure','Callback','gplotadcp(''savefig'')');
  HH.m_b = uimenu(HH.m_label,...
	  'Label','&Save Section Data ','Callback','gplotadcp(''savedata'')');
  HH.m_c = uimenu(HH.m_label,...
	  'Label','&Vector plot','Callback','gplotadcp(''mk_adcpvector'')');
  HH.m_d = uimenu(HH.m_label,'Label','&Contour plot');
  HH.m_e = uimenu(HH.m_label,...
	  'Label','&Panel plot','Callback','gplotadcp(''mk_panelplot'')');
  HH.m_f = uimenu(HH.m_label,...
	  'Label','&AshtechStats plot','Callback','gplotadcp(''mk_attplot'')');
  HH.m_g = uimenu(HH.m_label,'Label','&Help');
  
  %what kind of contour plot?
  HH.m_da = uimenu(HH.m_d,...
	  'Label','against time',...
	  'Callback','gplotadcp(''mk_adcpcontour'',''time'')');
  HH.m_db = uimenu(HH.m_d,...
	  'Label','against lat',...
	  'Callback','gplotadcp(''mk_adcpcontour'',''lat'')');
  HH.m_dc = uimenu(HH.m_d,...
	  'Label','against lon',...
	  'Callback','gplotadcp(''mk_adcpcontour'',''lon'')');

  % what kind of panel plot?
  HH.m_ea = uimenu(HH.m_e,'label','percent good',...
                   'Callback','gplotadcp(''mk_panelplot'',''pgood'')');
  HH.m_eb = uimenu(HH.m_e,'label','profile flags',...
                   'Callback','gplotadcp(''mk_panelplot'',''pflag'')');
  HH.m_ec = uimenu(HH.m_e,'label','AGC',...
                   'Callback','gplotadcp(''mk_panelplot'',''amp'')');
  HH.m_ed = uimenu(HH.m_e,'label','spectral width',...
                   'Callback','gplotadcp(''mk_panelplot'',''sw'')');
  HH.m_ee = uimenu(HH.m_e,'label','error velocity',...
                   'Callback','gplotadcp(''mk_panelplot'',''e'')');
  HH.m_ef = uimenu(HH.m_e,'label','measured u',...
                   'Callback','gplotadcp(''mk_panelplot'',''umeas'')');
  HH.m_eg = uimenu(HH.m_e,'label','measured v',...
                   'Callback','gplotadcp(''mk_panelplot'',''vmeas'')');
  HH.m_eh = uimenu(HH.m_e,'label','measured forward',...
                   'Callback','gplotadcp(''mk_panelplot'',''fmeas'')');
  HH.m_ei = uimenu(HH.m_e,'label','measured port',...
                   'Callback','gplotadcp(''mk_panelplot'',''pmeas'')');
  HH.m_ej = uimenu(HH.m_e,'label','absolute u',...
                   'Callback','gplotadcp(''mk_panelplot'',''uabs_sm'')');
  HH.m_ek = uimenu(HH.m_e,'label','absolute v',...
                   'Callback','gplotadcp(''mk_panelplot'',''vabs_sm'')');
  
  
  %help!!
  HH.m_fa = uimenu(HH.m_g,...
	  'Label','overview',...
	  'Callback','gplotadcp(''print_help'',''overview'')');
  HH.m_fb = uimenu(HH.m_g,...
	  'Label','vector',...
	  'Callback','gplotadcp(''print_help'',''vector'')');
  HH.m_fc = uimenu(HH.m_g,...
	  'Label','contour',...
	  'Callback','gplotadcp(''print_help'',''contour'')');
  HH.m_fd = uimenu(HH.m_g,...
	  'Label','PercentGood',...
	  'Callback','gplotadcp(''print_help'',''pgood'')');
  HH.m_fe = uimenu(HH.m_g,...
	  'Label','AshtechStats',...
	  'Callback','gplotadcp(''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
   HH.ii = 1:length(HH.x);

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

   %% load temperature file
   startdir = pwd;
   if (exist('../edit','dir'))
      chdir('../edit')
      changed_dir = 1;
   else
      changed_dir = 0;
   end
   
   [uifile, uipath] =uigetfile('*.tem',...
      'Select a temperature file with columns dday, temperature');
   if (changed_dir)
      chdir(startdir)
   end
      
         
   if (uifile~=0)
      tdata = load(fullfile(uipath, uifile));
      HH.temp = table1(tdata(:,[1 2]), HH.dday);
   else
      HH.temp = NaN*HH.dday;
   end
   set(adcpfighandle,'userdata',HH); 
  else
     fprintf('no adcp data loaded');
  end

%------------------------------
function savefig
  
  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');
  
  [uifile, uipath] = uiputfile(sprintf('%s/*.ps',HH.default_path),...
	  'save6 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 savedata

  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');
  
  ii=HH.ii;
  data.lon = HH.x(ii);
  data.lat = HH.y(ii);
  data.dday = HH.dday(ii);
  data.u = HH.u(:,ii);
  data.v = HH.v(:,ii);
  data.z = HH.z;
  data.zc = HH.zc;
  if (isfield(HH,'temp'))
     data.temp = HH.temp(ii);
  end
  save6 gplot_data data
  fprintf('in %s, saving this section to gplot_data.mat\n',pwd)
  
%-----------------------------
function mk_adcpvector
  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata'); %this has pgstruct in it or not
  HH.ii=gxytzoom(HH.x, HH.y, HH.dday, HH.ii);
 
  vector_this_level=get_vectorlevel(HH.z, HH.zc);
  comment=get_comment; %writes comment to HH.comment
  HH.comment = comment;

  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, HH.dday, HH.ii, HH.comment);

  figure(HH.fig);	  clf;   HH=mk_menus(HH);
  autovect(HH.x(HH.ii), HH.y(HH.ii), ...
           HH.u(vector_this_level,HH.ii), HH.v(vector_this_level,HH.ii),...
           'newfig',0, 'T', HH.temp(HH.ii),...
           'titlestr', titlestr, 'mvec_scale', HH.vec_scale,...
           'axesfontsize',10);

  date_it;
  set(adcpfighandle,'userdata',HH);

%-----------------------------  
function mk_adcpcontour(dstr)

  adcpfighandle = findobj('Tag','adcpfig');
  HH=get(adcpfighandle,'userdata');
  HH.ii=gxytzoom(HH.x, HH.y, HH.dday, HH.ii);

  if (strcmp(dstr,'lon'))
     d=1;
     abcissa = HH.x(HH.ii);
     disp('select data to contour against longitude')
  elseif (strcmp(dstr,'lat'))
     d=2;
     abcissa = HH.y(HH.ii);
     disp('select data to contour against latitude')
  elseif (strcmp(dstr,'time'))
     d=3;
     abcissa = HH.dday(HH.ii);
     disp('select data to contour against time')
  else
        error('incorrect call of mk_adcpcontour in gplotadcp')
  end


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

  titlestr=get_titlestr(HH.year_base, HH.dday, HH.ii, HH.comment);

 
  figure(HH.fig);	  clf;   HH=mk_menus(HH);
  autocont( 100*HH.u(:,HH.ii), 100*HH.v(:,HH.ii), 'abc_name',dstr, ...
           'newfig', 0,   'axesfontsize',10,...
           'ordmin',0, ...
           'abc', abcissa, 'ord', HH.zc, 'ord_name', 'depth');
  
  date_it;
  set(adcpfighandle,'userdata',HH);
  
%------------------------------
function mk_panelplot(fname)
  
  if (nargin == 1)
     
     adcpfighandle = findobj('Tag','adcpfig');
     HH=get(adcpfighandle,'userdata'); %this has pgstruct in it or no
     set(HH.fig, 'defaulttextinterpreter','none')
     
     %initialize or change pgstruct
     startdir = pwd;
     if (exist('../adcpdb','dir'))
        chdir('../adcpdb');
        changed_dir = 1;
     else
        changed_dir = 0;
     end
     
     [uifile, uipath] = uigetfile('*dir.blk',...
                                  'choose block directory file (*dir.blk)');
     if (changed_dir)
        chdir(startdir)
     end
     
     if (uifile~=0)
        HH.ii=gxytzoom(HH.x, HH.y, HH.dday, HH.ii);
        if length(HH.ii) > 200
           bname = ...
               questdlg(sprintf('about to extract and panel-plot %d points',...
                                   length(HH.ii)),'length question',...
                            'yes','no','yes');
        end
        
        if (strcmp(bname, 'yes') | length(HH.ii) <= 200)
           cfg.start_dd= HH.dday(HH.ii(1));
           cfg.end_dd = HH.dday(HH.ii(end));
           cfg.dbname = uifile(1:end-7);
           cfg.dbpath = uipath;
           cfg.yearbase = get_yb;
           cfg.ddrange = cfg.end_dd - cfg.start_dd;
           cfg.prefix = 'j_';
           cfg.nbins = 60;
           [data,config] = agetmat(cfg);
           
           figure(HH.fig);	  clf;   HH=mk_menus(HH);
           cc = aplotit(data, config, 'fn', fname,'cur_ax',subplot(211));
           title([comment,' ', fname])
           hh = subplot(4,1,3);
           plot(data.dday, data.lon); ylabel('deg lon')
           %lltick(gca,'y','lon');
           matchbox(hh,cc.cur_ax,'width');xl(data.dday([1 end]))
           hh = subplot(4,1,4);
           plot(data.dday, data.lat); ylabel('deg lat');
           %lltick(gca,'y','lat');
           matchbox(hh,cc.cur_ax,'width');xl(data.dday([1 end]))
        end
     end     
     date_it;
     set(adcpfighandle,'userdata',HH);
  end
%------------------------------
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 [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);
  
%------------------------------
