function  gautoedit(varargin)
% gautoedit % to start the window
% gautoedit('initialize',  [.01 .02 .5 .8]) % same as default
% gautoedit('initialize', figsize) % to specify figure size:
%                                  % fractions of 1: [left bottom width height];
%===============================  gautoedit ===================================
% gui interface to autoedit 
%
% - should be run from $cruiseid/edit/ subdirectory
% - must have "asetup.m" and "aflagit_setup.m" here too
% - reads asetup.m and aflagit_setup.m to set configurations config and pfc
% - commandline is available to explore the .mat files you are looking at, but
%         changed values from the gui are not reflected in the workspace.
%         (particularly useful commands are: 
%           [data, config] = agetmat('a_'); %then plot fields of data structure
% - must have paths from "adcppath" already
% - a link to a fuller tutorial is in PROGRAMS/index.html
%
% NOTE: 
% (1) automatic editing flags are written to ascii files when you push
%     'list to disk', but the files are only  applied to the database when you 
%     run "badbin" , "dbupdate", "set_lgb", and "setflags".
% (2a) manual editing flags are appended to ascii files immediately.
% (2b) manual editing is only visible during the current gautoedit session
%
% AUTOMATIC EDITING:  (see note 1)
% buttons at the bottom:
% BLUE: extract data and make plots: 
%       "show now"        (if ddrange or startdd is changed, extract new data,
%                           otherwise use what was just extracted)
%       "show next";     (add ddrange to startdd and then "show now")
% GREEN: information:
%       "help"           (show this help)
%       "find [blk,prf]  (click, [click...], return): prints block, profile,
%                           bin, decimal day, and date for bins clicked on
%       "show listed"    print to screen all time ranges that have had 
%                            "list to disk" run on them
% RED:  "old edit"       brings up a PG plot: click on the starting time you 
%                            want and it will run "setup" and do waterfall
%                            plotting.  You can edit and list using the old
%                            editing.  (You might have to run "setup" again).
%       "list flags"     writes bad bins, bottom, and bad profiles to ascii 
%                            (*.asc) files; notes the time range listed to a 
%                            log file
%
% MANUAL EDITING: (see note 2)
%      "del time range" choose your field, click on start and end time to 
%                            flag as bad profiles.  It will append the list
%                            of bad profile times to abadtimes.asc.
%       "rzap bins"      choose your field, drag a rectangle around the bad bins
%                            and it will append the bad bins to abadbins.asc.
%       "pzap bins"      choose your field, drag a rectangle around the bad bins
%                            and it will append the bad bins to abadbins.asc.
%       "bottom"         choose your field, click to draw a line indicating the 
%                           bottom. Double-click to finish) and it will
%                           append to abottom.asc.
%
% - remember to apply the editing and rerun the nav steps after listing all 
%
% NOTE ABOUT (*) EDITING: color plots start at a bin and a time; when you select
%   a time range or drag on a bin range, be sure to select the STARTING point, 
%   not the whole colored bar, or you'll get one too many
%============================================================================
% HINTS:
%  %to examine the userdata, 
%   fighandle = findobj('Tag','gautoedit_fig');
%   AA = get(fighandle,'userdata');
%  % save pixels: if you have a really big monitor:
%gautoedit('initialize', [0 0 .4 .7]); 
% 
  

% Jules 2001/1/16
% Dedicated to Nathanial B. Palmer and Mrs. Chippy.

% see gotchas in editing flag dependencies in the 'update_userdata' function
%% JH 2002/01/24 added adcp_nav, rzap_badbins, cl_badtimes, and changed jitter
%%    - should work OK with older astup files: defaults are added if necessary.
%%    - need this entire directory on your path though.
%% JH 2002/06/28 - adding badbins and badtimes indicators
%% JH 2002/11/25 trying to speed up graphics: adding 'backingstore' 'off':
% Off screen pixel buffer. When BackingStore is on, MATLAB stores a copy
% of the figure window in an off-screen pixel buffer. When obscured parts of 
% the figure window are exposed, MATLAB copies the window contents from this 
% buffer rather than regenerating the objects on the screen. This increases 
% the speed with which the screen is redrawn.
% JH 2003/02/22 add bottom indicator; add manual editing to alistit rather than
%    having the files appended to immediately; store the manual editing
%    in memory
% JH 2003/03/07 add pzap bins and glitch editing


if (isempty(varargin))
   %start things up  ----------
   figsize = [.01 .02 .5 .8];  %fractions of 1: [left bottom width height];
   initialize(figsize);
elseif strcmp(varargin{1},'initialize')
   figsize = varargin{2};
   initialize(figsize);
elseif strcmp(varargin{1},'show_next')
   gautoedit('update_userdata');  % use values in the boxes in userdata
   show_next;
elseif strcmp(varargin{1},'show_now')
   gautoedit('update_userdata');  % use values in the boxes in userdata
   show_now;
elseif strcmp(varargin{1},'list_flags')
   gautoedit('update_userdata');  % use values in the boxes in userdata
   list_flags;
elseif strcmp(varargin{1},'list_AA')
   list_AA;
elseif strcmp(varargin{1},'update_userdata')
   update_userdata;
elseif strcmp(varargin{1},'print_help')
   help gautoedit
   print_help;
elseif strcmp(varargin{1},'print_listed')
   print_listed;
elseif strcmp(varargin{1},'cl_blkprf')
   get_blkprof;
elseif strcmp(varargin{1},'cl_badtimes')
   get_badtimes;
elseif strcmp(varargin{1},'rzap_badbins')
   get_rzap_badbins;
elseif strcmp(varargin{1},'pzap_badbins')
   get_pzap_badbins;
elseif strcmp(varargin{1}, 'polybottom')
   get_polybottom;
elseif strcmp(varargin{1},'zap_edit')
   zap_edit;
elseif strcmp(varargin{1},'vv')
   fprintf('try this: \n\n')
   fprintf('fighandle = findobj(''Tag'',''gautoedit_fig''); \n')
   fprintf('AA = get(fighandle,''userdata''); \n\n')
   fprintf('[data, config] = agetmat(''a_'');\n');
   fprintf('[blkprf, sel_dday] = cl_blkprf(''uabs_g'', ''gautoedit''); \n')   
else
   error(sprintf('"%s" not a good argument',varargin{1}))
end

fprintf('hit <CR> to get the command line\n')





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


function initialize(figsize)

   set(0,'defaulttextinterpreter','none')

   %initialize window with boxes

   fighandle = findobj('Tag','gautoedit_fig');
   if (~isempty(fighandle)) %then there is one already  - can only have one
      error('only one gautoedit can run per matlab session')
   end
   

   %initialize data
   asetup;
   config.prefix = 'a_';

   %test for paths:
   if (  (~exist('matchbox', 'file')) | ...
         (~exist('mstdgap', 'file'))   )
      fprintf('you have a path missing: \n')
      fprintf('please edit asetup.m to include m_map, misc, and utils\n')
      error('autoedit path problem')
   end
   

   aflagit_setup;
   if (~isfield(pfc.cfg, 'underway'))
      pfc.cfg.underway = 100;
   end
   if (~isfield(pfc.cfg,'agility'))
      pfc.cfg.agility = 3;        
   end
   if (~isfield(pfc.cfg,'degperminute'))
      pfc.cfg.degperminute = 20;  
   end
   if (~isfield(pfc.cfg,'glitchfactor'))
      pfc.cfg.glitchfactor = 3;   
   end
   if (~isfield(pfc.cfg,'topglitchbin'))
      pfc.cfg.topglitchbin = 1;   
   end
   
   [junk, flagstruct] = aflagit;
   pfc.flag = flagstruct.flag;
   
   bool.ordinateisz = 0 ; % start of false: i.e. vertical coordinate is 'bins'
   bool.hidenewflags = 0; % start of false: i.e. show effects of new editing
   bool.hidepflags = 0;   % start of  true: i.e. show profile flags
   bool.newfigs = 0;      % start of false: i.e. do not show in new figures 
   bool.userawnav = 0;    % start of false: i.e. use smoothed nav (not raw nav)
   bool.showdiagn1 = 0;   % start of false: i.e. do not show diagnostics panels
   bool.showdiagn2 = 0;   % start of false: i.e. do not show diagnostics panels
   bool.showtopo = 1;     % start of true:  i.e.        show topography

   %AA is the whole structure; AA.h will be the handles;
   %store the config info in AA 
   %put in userdata at the bottom of initialization
   AA.config = config;
   AA.pfc = pfc;
   AA.badprof = [];
   AA.badrect = [];
   AA.badpoly = [];
   AA.mabs = [];
   AA.bool = bool;
   AA.figbackground = [0 .9 .95];
   AA.figsize = figsize;
   %make the figure that holds the buttons
   AA.h.autoeditfig = figure(500);
   set(AA.h.autoeditfig,...
      'units','normalized',...
      'ToolBar','none', ...
      'menubar','none', ...
      'color',AA.figbackground, ...
      'Tag', 'gautoedit_fig',...
       'position', AA.figsize,...
       'backingstore', 'off',...
       'hittest', 'off',...
       'name', 'gautoedit buttons',...
       'numbertitle', 'off',...
       'units', 'pixels');

   AA.got_ddrange = [];
   AA.data = [];
   
   %%%%% set up the structures for the buttons, add to userdata
   
   %boxes (bb) are in sets (s1,s2,s30,s31,s32,s0,s4)
   %set 1 is start_dd, end_dd, dd_range
   %set 2 is (y/n): topography, new figures, showflags, show_diagnostics
   %set 3 is pfc.cfg (subset; see bottom of upgrade_userdata for gotchas)
   %set 0 is click_blkprf, help, print_listed
   %set 4 is show_now; show_next; list;
   
   %stick it all in a structure : 
   %  supposedly, for s1,s2,s3  (change here, look for more later)

   %floats with editable fields
   bb.s1.start_dd = config.start_dd;    
   bb.s1_label.start_dd = 'decimal day (start)';
   bb.s1_color.start_dd    =   [245 245 220]/255;;

   bb.s1.ddrange  = config.ddrange;
   bb.s1_label.ddrange = 'decimal day step';
   bb.s1_color.ddrange    =   [245 245 220]/255;;
   
   bb.s1.end_dd   = config.end_dd;
   bb.s1_label.end_dd = 'decimal day (end)';
   bb.s1_color.end_dd    =  AA.figbackground;
   
   %checkboxes: make them in bb.s2 
   bb.s2.ordinateisz = bool.ordinateisz;
   bb.s2_label.ordinateisz = 'use depth as vertical coordinate (else use bins)';
   bb.s2_color.ordinateisz = .8*[1 1 1];

   bb.s2.hidenewflags = bool.hidenewflags;
   bb.s2_label.hidenewflags = 'do not show (autoedit) editing';
   bb.s2_color.hidenewflags = .8*[1 1 1];

   bb.s2.hidepflags = bool.hidepflags;
   bb.s2_label.hidepflags = ' do not show effect of profile flags in database';
   bb.s2_color.hidepflags = .8*[1 1 1];
   
   bb.s2.newfigs = bool.newfigs;
   bb.s2_label.newfigs = 'plot in new figures';
   bb.s2_color.newfigs = .8*[1 1 1];

   bb.s2.userawnav = bool.userawnav;
   bb.s2_label.userawnav = 'use ship speed from raw nav (usually runs refsm)';
   bb.s2_color.userawnav = .8*[1 1 1];

   bb.s2.showdiagn2 = bool.showdiagn2;
   bb.s2_label.showdiagn2 = 'show bias param and errvel (all values shown)';
   bb.s2_color.showdiagn2 = .8*[1 1 1];

   bb.s2.showdiagn1 = bool.showdiagn1;
   bb.s2_label.showdiagn1 = 'show amp and forward (all values shown)';
   bb.s2_color.showdiagn1 = .8*[1 1 1];

   bb.s2.showtopo = bool.showtopo;
   bb.s2_label.showtopo = 'show lat, lon, cruisetrack';
   bb.s2_color.showtopo = .8*[1 1 1];

   %number of bins to extract  (s30 is from "config." structure)
   bb.s30.nbins               = config.nbins;
   bb.s30_label.nbins         = 'number of bins to extract';
   bb.s30_color.nbins         =            [1 1 .3];
   
   %flagit (most common) config values at the top,  ("pfc.cfg" structure)
   %  integers with editable fields
   bb.s31.ecutoff             = pfc.cfg.ecutoff;
   bb.s31_label.ecutoff       = ...
       'bins rejected above this Error Velocity (mm/s)';
   bb.s31_color.ecutoff       =            [1 1 .3];
   
   bb.s31.wire_onstation       = pfc.cfg.wire_onstation;
   bb.s31_label.wire_onstation = 'for EV: "on station" if slower than this (m/s)';
   bb.s31_color.wire_onstation =            [1 1 .3];
   
   bb.s31.wire_ecutoff       = pfc.cfg.wire_ecutoff;
   bb.s31_label.wire_ecutoff  = '(on station only) bins rejected above this EV';
   bb.s31_color.wire_ecutoff  =            [1 1 .3];
   
   bb.s31.trimtopbins         = pfc.cfg.trimtopbins;
   bb.s31_label.trimtopbins   = 'number of bins rejected at the top';
   bb.s31_color.trimtopbins   =            [1 1 .3];
   
   bb.s31.maxpgbin_fudge         = pfc.cfg.maxpgbin_fudge;
   bb.s31_label.maxpgbin_fudge   = 'reject shallow low PG (tolerance: smaller# rejects more, 100 disables)';
   bb.s31_color.maxpgbin_fudge   =            [1 1 .3];
   
   bb.s31.bigtarget_amp       = pfc.cfg.bigtarget_amp;
   bb.s31_label.bigtarget_amp = 'bottom: like AMP_THRESHOLD to determine the bottom';
   bb.s31_color.bigtarget_amp =            [.9 .7  0];
   
   bb.s31.bigtarget_avg       = pfc.cfg.bigtarget_avg;
   bb.s31_label.bigtarget_avg = 'bottom: 0 (no smoothing) 1,2,3: smooth with 3,5,7 pts';
   bb.s31_color.bigtarget_avg =            [.9 .7 0];

   bb.s31.bigtarget_offset    = pfc.cfg.bigtarget_offset;
   bb.s31_label.bigtarget_offset = 'bottom: distance away (bins) to calculate amp bump';
   bb.s31_color.bigtarget_offset =         [.9 .7  0];

   bb.s31.pgcutoff            = pfc.cfg.pgcutoff;
   bb.s31_label.pgcutoff      = ...
       'Percent Good cutoff (use ONE for the whole cruise)';
   bb.s31_color.pgcutoff      =        AA.figbackground;

   bb.s31.jitter_cutoff         = pfc.cfg.jitter_cutoff;
   bb.s31_label.jitter_cutoff   = ...
       'jitter: reject profile if jitter in measured velocity  > (cm/s)';
   bb.s31_color.jitter_cutoff   =            [.9 .6 .9];


   bb.s31.badpgrefl         = pfc.cfg.badpgrefl;
   bb.s31_label.badpgrefl   = ...
       'ref layer: PG cutoff (at least N bins must excede this: see next) ';
   bb.s31_color.badpgrefl   =            [.9 .6 .9];

   
   bb.s31.badpgrefl_nbins       = pfc.cfg.badpgrefl_nbins;
   bb.s31_label.badpgrefl_nbins = ...
       'ref layer: N bins good bins required in ref layer (see prev)';
   bb.s31_color.badpgrefl_nbins =            [.9 .6 .9];
   
   bb.s31.orphan_slide          = pfc.cfg.orphan_slide;
   bb.s31_label.orphan_slide    = ...
       'N neighbors required on each side of a "good" profile (uses ref layer editing)';
   bb.s31_color.orphan_slide    =            [.9 .6 .9];


   bb.s31.underway             = pfc.cfg.underway;
   bb.s31_label.underway       = ...
       'underway: discard data with ship speed higher than this (m/s) ';
   bb.s31_color.underway       =         [.9 .6 .9];
   

   % new, 2003/03/07
   bb.s31.agility = pfc.cfg.agility;
   bb.s31_label.agility       = ...
       'glitch flagging: only if ship turning faster than this (degrees per minute)';
   bb.s31_color.agility       =         [.6 1 0.4];
   
   bb.s31.glitchfactor = pfc.cfg.glitchfactor;
   bb.s31_label.glitchfactor       = ...
       'glitch flagging: glitch factor (positive, larger disables)';
   bb.s31_color.glitchfactor       =         [.6 1 0.4];
   
   bb.s31.topglitchbin = pfc.cfg.topglitchbin;
   bb.s31_label.topglitchbin       = ...
       'glitch flagging: apply to bins starting here and deeper';
   bb.s31_color.topglitchbin       =         [.6 1 0.4];
   
   %reference layer bins ("pfc" structure)
   bb.s32.refl_startbin         = pfc.refl_startbin;
   bb.s32_label.refl_startbin   = ...
       'first reference layer bin (for reference layer editing)';
   bb.s32_color.refl_startbin   =        AA.figbackground;
   
   bb.s32.refl_endbin           = pfc.refl_endbin;
   bb.s32_label.refl_endbin     =  ...
       'last reference layer bin (for reference layer editing)';
   bb.s32_color.refl_endbin     =  AA.figbackground;

   %velocity range (color scale)
   bb.s32.uvmax         = 60;
   bb.s32_label.uvmax   = 'maximum u and v (for colorbar)';
   bb.s32_color.uvmax   =        AA.figbackground;

   bb.s32.uvmin         = -60;
   bb.s32_label.uvmin   = 'minimum u and v (for colorbar)';
   bb.s32_color.uvmin   =        AA.figbackground;

   
   %callback pushbuttons (equals one box vertically)
   %ths used to be at the top, now move it down to just above s4
   bb.s0.zap_edit  = 'zap_edit';
   bb.s0_label.zap_edit = 'old edit';
   bb.s0_color.zap_edit = [178 34 34]/255;

   %
   bb.s0.cl_badtimes   = 'cl_badtimes';
   bb.s0_label.cl_badtimes = {'del bad times',
                    'pg',
                    'uabs_sm',
                    'vabs_sm',
                    'fabs_sm'};
   bb.s0_color.cl_badtimes = [178 34 34]/255;
   
   
   bb.s0.print_help   = 'print_help';
   bb.s0_label.print_help = 'help';
   bb.s0_color.print_help = [46 139 87]/255;
   

   
   %%% if adding this here, ...
   
   %   bb.s0.jittertype   = 'jittertype';
   %   bb.s0_label.jittertype = {'jitter: mean',
   %                    'jitter: std';
   %                    'jitter: SEM'};
   %   bb.s0_color.jittertype = [46 139 87]/255;
   
   % ... add this to the list of possible calls at the top
   %     elseif strcmp(varargin{1},'jittertype')
   %          update_userdata;
   %
   
   bb.s0.cl_blkprf   = 'cl_blkprf';
   bb.s0_label.cl_blkprf = {'find [blk, prf]',
                    'pg',
                    'uabs_sm',
                    'vabs_sm',
                    'fabs_sm'};
   bb.s0_color.cl_blkprf = [46 139 87]/255;
   
   bb.s0.print_listed   = 'print_listed';
   bb.s0_label.print_listed = 'show listed';
   bb.s0_color.print_listed = [46 139 87]/255;
   
   
   %callback pushbuttons (equals one box vertically)
   bb.s4.show_now   = 'show_now';
   bb.s4_label.show_now = 'show now';
   bb.s4_color.show_now = [12 12 123]/255;
   %
   bb.s4.show_next  = 'show_next';
   bb.s4_label.show_next = 'show next';
   bb.s4_color.show_next = [12 12 123]/255;
   %
   bb.s4.rzap_badbins  = 'rzap_badbins';
   bb.s4_label.rzap_badbins = {'rzap bins',
                    'pg',
                    'uabs_sm',
                    'vabs_sm',
                    'fabs_sm'};
   bb.s4_color.rzap_badbins = [178 34 34]/255;
   %
   bb.s4.pzap_badbins  = 'pzap_badbins';
   bb.s4_label.pzap_badbins = {'pzap bins',
                    'pg',
                    'uabs_sm',
                    'vabs_sm',
                    'fabs_sm'};
   bb.s4_color.pzap_badbins = [178 34 34]/255;
   %

   bb.s4.polybottom  = 'polybottom';
   bb.s4_label.polybottom = {'bottom',
                    'pg',
                    'uabs_sm',
                    'vabs_sm',
                    'fabs_sm',
                    'amp'};
   bb.s4_color.polybottom = [178 34 34]/255;
   %
   bb.s4.list_flags = 'list_flags';
   bb.s4_label.list_flags = 'list to disk.';
   bb.s4_color.list_flags = [178 34 34]/255;


   %%%% now set up the spacing (arithemetic)
   % need this to get padding
   %OK.  How many boxes are there in the vertical?  (too many cases to loop)
   num_s0boxes = 1; %boxes are horizontal
   num_s1boxes = length(fieldnames(bb.s1)); %top
   num_s2boxes = length(fieldnames(bb.s2)); %upper  middle
   num_s30boxes = length(fieldnames(bb.s30)); %midddle
   num_s31boxes = length(fieldnames(bb.s31)); %midddle
   num_s32boxes = length(fieldnames(bb.s32)); %midddle
   num_s4boxes = 1;  %boxes are horizontal
   num_boxes =   ...
       num_s0boxes + num_s1boxes + num_s2boxes + ...
       num_s30boxes + num_s31boxes + num_s32boxes + ...
       num_s4boxes;
   
   num_segments = 5; %s0,s1,s2,s30,s31,s32,s4

   %numpads = num_boxes*4 + (num_segments) + 4;   %% add 4 for title
   %vpad_frac = 1/numpads;
   %vppb = 4; %vpads per box
   
   vppb = 4; %vpads per box
   numpads = num_boxes*vppb + (num_segments) + vppb;   %% for title
   vpad_frac = 1/numpads;

   % get some geometry: fraction of width and height 
   %starting in the lower left corner:  [right, up, width, height]
   AA.figpos = get(AA.h.autoeditfig,'position');
   AA.figwidth = AA.figpos(3);
   AA.figheight = AA.figpos(4);
   AA.vpad = vpad_frac * AA.figheight;
   AA.vppb = vppb;
   
   AA.box_start = .05*AA.figwidth;   %box is for editable text fields
   AA.box_width = .15*AA.figwidth;
   AA.box_height = vppb*AA.vpad;

   AA.label_start = AA.box_start + AA.box_width + .1;  %labels
   AA.label_width = .8*AA.figwidth;
   AA.label_height = AA.box_height;
   AA.label_background = AA.figbackground;

   AA.bb = bb;
   fighandle = AA.h.autoeditfig;
   set(fighandle, 'userdata', AA);

   
   %% geometry for the button spacing in the vertical:
   %might as well set the bottom fraction for each set
   % start at the bottom and work towards the top
   s4_vfracstart = 0;                                                    % make s0 and s4
   s0_vfracstart =  s4_vfracstart  + (num_s4boxes*vppb     )*vpad_frac;  % one segment
   %
   s32_vfracstart = s0_vfracstart  + (num_s0boxes*vppb  + 1)*vpad_frac;  % s3 is a segment
   s31_vfracstart = s32_vfracstart + (num_s32boxes*vppb    )*vpad_frac;
   s30_vfracstart = s31_vfracstart + (num_s31boxes*vppb    )*vpad_frac;
   %
   s2_vfracstart =  s30_vfracstart + (num_s30boxes*vppb + 1)*vpad_frac;  %s2 is a segment
   %
   s1_vfracstart =  s2_vfracstart  + (num_s2boxes*vppb  + 1)*vpad_frac;  %s1 is a segment


   %%%%%%%%% make the title
   hh=uicontrol( 'Parent',AA.h.autoeditfig, ...
                 'units','normalized',...
                 'BackgroundColor','k', ...
                 'ForegroundColor', 'w',...
                 'ListboxTop',0, ...
                 'horizontalalignment', 'center',...
                 'Position',[.45 1-4*vpad_frac, .25, vppb*vpad_frac],...
                 'Style','text',...
                 'string', AA.config.comment,...
                 'fontsize',14,...
                 'fontweight','bold');

   
   %%%%%%%%% make the buttons
   %now make top pressboxes ("help") (s0)
   binfo.vfracstart = s0_vfracstart;
   binfo.boxinfo = bb.s0;
   binfo.labels = bb.s0_label;
   binfo.colors = bb.s0_color;
   mk_pushbuttons(binfo);
   clear binfo

   %%% now do editable fields for dday information (s1)
   binfo.vfracstart = s1_vfracstart;
   binfo.boxinfo = bb.s1;
   binfo.colors = bb.s1_color;
   binfo.labels = bb.s1_label;
   mk_textedit(binfo); 
   clear binfo
   
   %%% now do checkboxes (s2)
   binfo.vfracstart = s2_vfracstart;
   binfo.boxinfo = bb.s2;
   binfo.colors = bb.s2_color;
   binfo.labels = bb.s2_label;
   mk_checkboxes(binfo);
   clear binfo
   
   %%% now do editable fields for config (s30)
   binfo.vfracstart = s30_vfracstart;
   binfo.boxinfo = bb.s30;
   binfo.colors = bb.s30_color;
   binfo.labels = bb.s30_label;
   mk_textedit(binfo);
   clear binfo
   
   %%% now do editable fields for profile flags configuration (s31)
   binfo.vfracstart = s31_vfracstart;
   binfo.boxinfo = bb.s31;
   binfo.colors = bb.s31_color;
   binfo.labels = bb.s31_label;
   mk_textedit(binfo);
   clear binfo
   
   %%% now do editable fields for profile flags configuration (s32)
   binfo.vfracstart = s32_vfracstart;
   binfo.boxinfo = bb.s32;
   binfo.colors = bb.s32_color;
   binfo.labels = bb.s32_label;
   mk_textedit(binfo);
   clear binfo
   
   %now make pressboxes ("do it") (s4)
   binfo.vfracstart = s4_vfracstart;
   binfo.boxinfo = bb.s4;
   binfo.labels = bb.s4_label;
   binfo.colors = bb.s4_color;
   mk_pushbuttons(binfo);
   clear binfo

   
   fighandle = findobj('Tag','gautoedit_fig');      
   AA = get(fighandle,'userdata');
   AA.config
   
% end of function   
   
%%%%%%%%%%%%%%%%%%%%% end first_init %%%%%%%%%%%%%%%%%%%%

function update_userdata;

   % update userdata to reflect values in boxes

   %find the object
   fighandle = findobj('Tag','gautoedit_fig');
   
   %get the userdata
   AA = get(fighandle,'userdata');
   
      
   %override things in old userdata with stuff in boxes

   %%there are is one field to update for s0 (jitter type)
   %AA.jitterval = get(AA.h.jittertypeButton, 'val');
   %AA.jittername =  AA.bb.s0_label.jittertype{AA.jitterval};
   %fprintf('jitter type is %s\n', AA.jittername)

   %update fields in bb.s1 (decimal day info) - these can be floats
   fnames = fieldnames(AA.bb.s1);
   for num = 1:length(fnames)
      boxname = fnames{num};
      texthandlename = sprintf('%sText', boxname);
      uihandle = findobj('Tag', texthandlename);
      AA.config = setfield(AA.config, ...
                           boxname, ...
                           str2num(get(uihandle, 'string')));
   end
      
   %update fields in bb.s2 (on or off)
   fnames = fieldnames(AA.bb.s2);
   for num = 1:length(fnames)
      boxname = fnames{num};
      texthandlename = sprintf('%sCheck', boxname);
      uihandle = findobj('Tag', texthandlename);
      AA.bool = setfield(AA.bool, boxname, get(uihandle, 'value'));
   end

   %update fields in bb.s30 (config) flag config info these must be integers
   fnames = fieldnames(AA.bb.s30);
   for num = 1:length(fnames)
      boxname = fnames{num};
      texthandlename = sprintf('%sText', boxname);
      uihandle = findobj('Tag', texthandlename);
      AA.config = setfield(AA.config, ...
                        boxname,...
                        round(str2num(get(uihandle, 'string'))));
   end
   %update fields in bb.s31 (pfc.cfg) flag config info these must be integers
   fnames = fieldnames(AA.bb.s31);
   for num = 1:length(fnames)
      boxname = fnames{num};
      texthandlename = sprintf('%sText', boxname);
      uihandle = findobj('Tag', texthandlename);
      AA.pfc.cfg = setfield(AA.pfc.cfg, ...
                        boxname,...
                        round(str2num(get(uihandle, 'string'))));
   end

   %update fields in bb.s32 (pfc) config info) these must be integers
   fnames = fieldnames(AA.bb.s32);
   for num = 1:length(fnames)
      boxname = fnames{num};
      texthandlename = sprintf('%sText', boxname);
      uihandle = findobj('Tag', texthandlename);
      if (strcmp(fnames{num}(1:4), 'refl'))
         AA.pfc = setfield(AA.pfc, ...
                           boxname,...
                           round(str2num(get(uihandle, 'string'))));
      else
         AA = setfield(AA, boxname,...
                           round(str2num(get(uihandle, 'string'))));
      end
   end

   %there are no fields to update for s4
   

   % there are gotchas with updating things in the flagit pfc.cfg fields
   % check aflagit_setup.m for what is set and
   %     aflagit.m for dependencies
   % make these assumptions

   %either make these assumptions or if the dependent field is added to the
   % list of buttons, take out the assumption here
   
   %(1) require reference layer percent good to be the same as plain old pg   
   % (no longer requiring same PG cutoff: get it from pfc.cfg

   %(2) make the number of bins for orphan_slide equal to refl layer PG 
   if (isfield(AA.pfc.cfg, 'orphan_slide') & ...
       isfield(AA.pfc.cfg, 'orphan_numbins') & ...
       isfield(AA.pfc.cfg, 'badpgrefl_nbins'))
      if (AA.pfc.cfg.orphan_slide > 0)
         AA.pfc.cfg.orphan_numbins =  AA.pfc.cfg.badpgrefl_nbins;
      else
         AA.pfc.cfg.orphan_numbins =  0;
      end
   else
      fprintf('update_userdata: ')
      fprintf(' missing one of the following fields of pfc.cfg:\n')
      error('"orphan_slide" or "orphan_nbins" or "badpgrefl_nbins"')
   end
   

   %(3) choosing reference layer bins
   % in commandline;  asetup sets config.rl_range and aflagit_setup
   %     is slaved to those values as pfc.refl_startbin and pfc.refl_endbin
   % because this program is only set up to make text buttons for scalar
   %     inputs, I'll allow setting reference layer bins from pfc
   %     and then slave config.rl_range from those.

   if (isfield(AA.pfc, 'refl_startbin') & ...
       isfield(AA.pfc, 'refl_endbin') & ...
       isfield(AA.config, 'rl_range'))
      AA.config.rl_range = [AA.pfc.refl_startbin AA.pfc.refl_endbin];
   else
      fprintf('update_userdata: missing one of the following fields:\n')
      fprintf('from pfc: "refl_startbin" or "refl_endbin" \n')
      error('from config: "rl_range" \n')
   end      
   

     
   set(fighandle, 'userdata', AA);  %update userdata

%end of function   
   
%%%%%%%%%%%%%%%%%%%%  end of update %%%%%%%%%%%%%%%%%%%%

function show_now;

   %now replicate run_alookit ------------------------------

   
   fighandle = findobj('Tag','gautoedit_fig');
   %get the userdata
   AA = get(fighandle,'userdata');
   
   pfc = AA.pfc;
   data = AA.data;
   
   if  AA.bool.ordinateisz == 1
      ord_name = 'z';
   else
      ord_name = 'bins';
   end
   
   
   hidenewflags = AA.bool.hidenewflags;
   hidepflags = AA.bool.hidepflags;
   newfigs = AA.bool.newfigs;
   showtopo = AA.bool.showtopo;
   userawnav = AA.bool.userawnav;
   showdiagn1 = AA.bool.showdiagn1;  
   showdiagn2 = AA.bool.showdiagn2;  
   
   %set up some graphing parameters for apuv.m
   topo_clev = [-9000:500:0];  % Topography contour levels.
   mvec_scale = 100;           %100cm/s per inch on paper

   getnewdata = 0;
   %only get new data if necessary
   if (isemptys(AA.got_ddrange)),   
      getnewdata = 1;       
   else
      if ((AA.got_ddrange(1)  ~= AA.config.start_dd) | ...
         (AA.got_ddrange(2)  ~= AA.config.start_dd + AA.config.ddrange))
         getnewdata = 1;
      end
   end

   if (getnewdata)
      %pass the on_station cutoff to the next extraction
      AA.config.os_cutoff = AA.pfc.cfg.wire_onstation;
      [data, plotconfig] = agetmat(AA.config);
      AA.got_ddrange = AA.config.start_dd + [0 AA.config.ddrange];
      AA.data = data;
      AA.plotconfig = plotconfig;
      % config is already set
      set(fighandle, 'userdata', AA);  %update userdata
   else
      fprintf('using currently-loaded userdata\n')
   end
   
   config = fillstruct(AA.config, AA.plotconfig, 1);
  
   
   flagged = zeros(size(data.umeas));
   if (~hidenewflags)
      flagged = (aflagit(data, config, pfc) | flagged | manflags(AA));
      %% 02/02/21 also create flags from bad time range, rzap, or bottom
   end

   if (~hidepflags)
      flagged = (flagged | data.pflag);
   end

   config.flagged = flagged;   %set flagit to zero to show all data

   if (newfigs)
      figure( 'menubar','none','toolbar','none', 'hittest', 'off')
      base_fig = gcf;
   else
      base_fig = AA.h.autoeditfig;
      figure(base_fig + 1);
      hfig = gcf;
      set(hfig, 'hittest', 'off');
   end

   uvfig = gcf;
   set(uvfig , 'menubar','none','toolbar','none',...
                 'name', 'u,v,PG');

   alookit;      %uabs, vabs, PG, ship speed
   
   if (showdiagn1)
      figure(base_fig + 2);
      hfig = gcf;      
      set(hfig, 'menubar','none','toolbar','none',...
                'hittest', 'off',...
                 'name', 'AMP and fore');
      % do not show editing for diagnostics
      config.flagged = zeros(size(data.umeas));
      alookit_diagn1;  %fore, err vel
   end

   if (showdiagn2)
      figure(base_fig + 3);
      hfig = gcf;      
      set(hfig, 'menubar','none','toolbar','none',...
                'hittest', 'off',...                
                 'name', 'EV and bias param');
      % do not show editing for diagnostics
      config.flagged = zeros(size(data.umeas));
      alookit_diagn2;  %fore, err vel, spectral width, amp
   end

   if (showtopo)
      figure(base_fig + 4)
      hfig = gcf;      
      set(hfig, 'menubar','none','toolbar','none',...
                'hittest', 'off',...                
                 'name', 'topog');
      %leave room for diagnostics  plot
      config.flagged = flagged;
      whitebg(base_fig + 4, 'w');
      apuv(data, config, 'topo_clev', topo_clev,...
           'mvec_scale', mvec_scale, 'pfc', pfc);
   
   end
   
   figure(uvfig);
      
%end of function

%%%%%%%%%%%%%%%%%%%%% end show_now  %%%%%%%%%%%%%%%%%%%%

function show_next;

    %update userdata with the stuff in the boxes
      
   fighandle = findobj('Tag','gautoedit_fig');
   %get the userdata
   AA = get(fighandle,'userdata');

   %add ddrange to update start_dd 
   %update structure
   AA.config.start_dd = AA.config.start_dd + AA.config.ddrange;
   %update box
   set(AA.h.start_ddText, 'string', sprintf('%5.2f',AA.config.start_dd))
  
   % do not update edited regions: carry these flags around until session ends
   % 02/02/21
   %AA.badprof = [];
   %AA.badrect = [];
   %AA.mabs = [];

   %update userdata
   set(fighandle, 'userdata', AA);  %update userdata
   
   gautoedit('show_now');

% end of function   
   
%%%%%%%%%%%%%%%%%%%% end show_next %%%%%%%%%%%%%%%%%%%%


function list_flags;

   fighandle = findobj('Tag','gautoedit_fig');
   %get the userdata
   AA = get(fighandle,'userdata');
   config = AA.config;
   pfc = AA.pfc;

   fileprefix = 'auto';
   dt = .1;  %pad ranges by this amount
   dt = 0;   %JH 2001/09/14 - don't pad

   %now call the editing driver
   config.start_dd = config.start_dd - dt;  
   config.ddrange = config.ddrange + 2*dt;   %pad on each side by dt;
   
   %now call 
   [data, config] = agetmat(config);
   
   if (~isemptys(data))
      % write automatic flagging to disk:
      [flagged, pfc] = aflagit(data, config, pfc);
      
      fprintf('===> APPLYING THRESHOLDS TO DATA (creating pflags) <====\n')

      pflags.yearbase = config.yearbase;
      pflags.dday = data.dday;
      pflags.flagged = flagged;
      pflags.flag = pfc.flag;
      save g_flagged.mat pflags;
      
      flagfile = dir('g_flagged.mat');
      alistit(flagfile);
      
      %% document it
      cc = fix(clock);
      fid = fopen('gautoedit.log','a');
      fprintf(fid, 'listing flags at %s\n',...
              to_date(cc(1),to_day(cc(1),cc),'s'));
      fprintf(fid, 'data time range listed: %s - %s (%5.2f-%5.2f)\n',...
              to_date(config.yearbase, config.start_dd,'s'),...
              to_date(config.yearbase, config.start_dd + config.ddrange,'s'),...
              config.start_dd, config.start_dd + config.ddrange);
      fprintf(fid, '%25s: %d to %d\n','reference layer bins',...
              config.rl_range(1), config.rl_range(2));
      fnames = fieldnames(AA.pfc.cfg);
      for fni = 1:length(fnames)
         value = getfield(pfc.cfg,  fnames{fni});
         fprintf(fid, '%25s:  ', fnames{fni});
         for ii=1:length(value)
            fprintf(fid,'%d ',value(ii));
         end
         fprintf(fid,'\n');
      end
      fprintf(fid, 'BUT percent good is only used for display: \n');
      fprintf(fid, '..it must be set with setflags.\n\n\n\n');
      fclose(fid);
   
      if (exist('g_flagged.mat','file')),  delete g_flagged.mat,  end
      if (exist('m_flagged.mat','file')),  delete m_flagged.mat,  end
   end
   
   gautoedit('print_listed')
   
%end of function

%%%%%%%%%%%%%%%%%%%% end list_flags %%%%%%%%%%%%%%%%%%%%
   
function [flagged, mstruct] = manflags(aa);
% mimic 'aflagit': return a matrix of flagged (1 if flagged) and a structure
% with fields
startdd =  aa.data.dday(1);
secs = round(86400*(aa.data.dday - startdd));
[secM, binM] = meshgrid(secs, aa.data.bins);

%initialize to unflagged
unflagged = zeros(size(secM));
mstruct.mask.badtimes  = unflagged;
mstruct.mask.maxampbin = unflagged;
mstruct.mask.rzapbins   = unflagged; %rzap
mstruct.mask.bottom    = unflagged;  % for (in) visibility only

mstruct.flag            = aa.pfc.flag;
mstruct.cfg             = aa.pfc.cfg;
mstruct.refl_startbin   = aa.pfc.refl_startbin;
mstruct.refl_endbin     = aa.pfc.refl_endbin;
mstruct.yearbase        = aa.pfc.yearbase;

if (isfield(aa, 'badprof'))
   if ~isemptys(aa.badprof)
      bprofsecs = round(86400*(aa.badprof - startdd));
      ii = find(ismember(secs, bprofsecs) == 1);
      mstruct.mask.badtimes(:,ii) = aa.pfc.flag.badtimes;
   end
end

if (isfield(aa, 'badrect'))
   if ~isemptys(aa.badrect)
      for cnum = 1:length(aa.badrect)
         segsecs = round(86400*(aa.badrect{cnum}.abcissa-startdd));
         jj = find(ismember(secs, segsecs) == 1);
         ii = find(ismember(aa.data.bins, aa.badrect{cnum}.ordinate) == 1);
         mstruct.mask.rzapbins(ii,jj) = aa.pfc.flag.rzapbins;
      end
   end
end



if (isfield(aa, 'badpoly'))
   if ~isemptys(aa.badpoly)
      for cnum = 1:length(aa.badpoly)
         polysecs = round(86400*(aa.badpoly{cnum}.abcissa-startdd));
         polybins = aa.badpoly{cnum}.ordinate;
         %index "inside" polygon         
         ini = inpolygon(secM(:), binM(:), polysecs, polybins); 
         if (length(find(ini)) > 0)
            mstruct.mask.rzapbins(ini) = aa.pfc.flag.rzapbins;
         end
      end
   end
end


if (isfield(aa,'mabs'))
   
   if ~isemptys(aa.mabs)
      badi = find(isnan(aa.mabs.ordinate));
      aa.mabs.ordinate(badi)=[];
      aa.mabs.abcissa(badi)=[];
      
      %get the shallowest MAB 
      abc = unique(aa.mabs.abcissa);
      ord = zeros(size(abc));
      for num=1:length(abc)
         ord(num) = min(aa.mabs.ordinate(find(aa.mabs.abcissa == abc(num))));
      end
      aa.mabs.ordinate = ord;
      aa.mabs.abcissa = abc;
      
      mabsecs = round(86400*(aa.mabs.abcissa - startdd));   
      
      if (length(mabsecs) > 0)
         bflag = unflagged;
         for ii=1:length(secs)
            jj=find(mabsecs == secs(ii));
            if (~isemptys(jj))
               bflag(aa.mabs.ordinate(jj), ii) = 1;
            end
         end
         mstruct.mask.maxampbin = bflag * aa.pfc.flag.maxampbin;
         [bmask, b]=bigstarget(4*bflag, ...
                               'thresh',1, ...
                               'offset',1, ...
                               'nside', 0);
         mstruct.mask.bottom  = aa.pfc.flag.bottom*...
             bottommask(bmask, bmask,  0.85, 0);
      end
   end
end


flagged = unflagged;
masknames = {'badtimes', 'maxampbin', 'rzapbins', 'bottom'};
for maski = 1:length(masknames)
   flagged = flagged + getfield(mstruct.mask, masknames{maski});
end


%%%%%%%%%%%%%%%%%%%%%%%%%%% end mflags %%%%%%%%%%%%%%%%%%

function  mk_pushbuttons(binfo);
%% watch out: function call is from variable name, not value

   vfracstart               =   binfo.vfracstart      ;
   fontweight               =   'bold';
   fontsize                 =   10;
   alignment                =   'center';
   colors                   =   binfo.colors;
   boxinfo                  =   binfo.boxinfo         ;
   labels                   =   binfo.labels;
   
   fighandle = findobj('Tag','gautoedit_fig');
   %get the userdata
   AA = get(fighandle,'userdata');

   fnames = fieldnames(boxinfo);

   buttonwidth = AA.figwidth/(length(fnames)*1.1);
   buttonhpad = (AA.figwidth - length(fnames)*buttonwidth)/...
       (length(fnames) + 1);

   for num = 1:length(fnames);
      buttonname = fnames{num};
      handlename = sprintf('%sButton', buttonname);
      callbackstr = sprintf('gautoedit(''%s'')', buttonname);
      color = getfield(colors, buttonname);
      label = getfield(labels, buttonname);
      buttonposition = ceil([...
         num*buttonhpad + (num - 1)*buttonwidth ;           %right
         (AA.figheight*vfracstart) + AA.vpad;      %up
         buttonwidth;            %width of pushbutton
         AA.vppb*AA.vpad])';              %height of pushbutton
     
      
      if (iscell(label))
         stylestr = 'popupmenu';
         val = 1;
      elseif (isstr(label))
         stylestr = 'pushbutton';
         val = 0;
      else
         fprintf('OOps!!  There is a problem in mk_pushbuttons\n')
      end
      
      AA.h = setfield(AA.h, handlename, ...
                     uicontrol(...
                        'Parent',AA.h.autoeditfig, ...
                        'units','pixels',...
                        'ListboxTop',0, ...
                        'Position', buttonposition,...
                        'string', label,...
                        'fontweight', fontweight,...
                        'fontsize', fontsize,...
                        'horizontalalignment', alignment,...
                        'Callback', callbackstr,...
                        'foregroundcolor',[1 1 1],...
                        'backgroundcolor', color,...
                        'style', stylestr,...
                        'val', val,...
                        'Tag', handlename));
   
   end

   fighandle = AA.h.autoeditfig;
   set(fighandle, 'userdata', AA);
   
%%%%%%%%%%%%%%%%%%%% end of mk_pushbuttons %%%%%%%%%%%%%%%%%%%%

function mk_textedit(binfo)

   vfracstart               =   binfo.vfracstart      ;
   boxinfo                  =   binfo.boxinfo         ;
   colors                   =   binfo.colors           ;
   labels                   =   binfo.labels           ;
   
   fnames = fieldnames(boxinfo);
   fnames = flipud(fnames);

   
   fighandle = findobj('Tag','gautoedit_fig');
   %get the userdata
   AA = get(fighandle,'userdata');

   for num = 1:length(fnames)
      boxname = fnames{num};
      texthandlename = sprintf('%sText', boxname);
      labelhandlename = sprintf('%sLabel', boxname);
      color = getfield(colors, boxname);
      label = getfield(labels, boxname);
      boxposition = ceil([...
         AA.box_start ;           %right
         (AA.figheight*vfracstart) + 1 +  (num-1)*AA.vppb*AA.vpad; %up
         AA.box_width;            %width of edit box
         AA.vppb*AA.vpad])';            %height of edit box

      
      labelposition = boxposition; 
      labelposition(1) = AA.label_start;
      labelposition(3) = AA.label_width;
      labelposition(4) = AA.label_height;
      

      AA.h = setfield(AA.h, texthandlename,...
                            uicontrol(...
                               'Parent',AA.h.autoeditfig, ...
                               'units','pixels',...
                               'BackgroundColor',color, ...
                               'ListboxTop',0, ...
                               'horizontalalignment', 'center',...
                               'Position', boxposition,...
                               'Style','edit', ...
                               'string', getfield(boxinfo, boxname),...
                               'Tag',texthandlename));
      AA.h = setfield(AA.h, labelhandlename,...
                            uicontrol(...
                               'Parent',AA.h.autoeditfig, ...
                               'units','pixels',...
                               'ListboxTop',0, ...
                               'BackgroundColor',AA.label_background, ...
                               'Position', labelposition,...
                               'horizontalalignment', 'left',...
                               'Style','text', ...
                               'string', label,...
                               'fontweight', 'bold',...
                               'Tag', labelhandlename));
      

   end
   fighandle = AA.h.autoeditfig;
   set(fighandle, 'userdata', AA);
   
   
%%%%%%%%%%%%%%%%%%%%%%% end of mk_textedit %%%%%%%%%%%%%%%%%%%%   
function mk_checkboxes(binfo)

   vfracstart               =   binfo.vfracstart      ;
   boxinfo                  =   binfo.boxinfo         ;
   labels                   =   binfo.labels;
   colors                   =   binfo.colors   ;        
   
   fnames = fieldnames(boxinfo);

   
   fighandle = findobj('Tag','gautoedit_fig');
   %get the userdata
   AA = get(fighandle,'userdata');

   for num = 1:length(fnames);
      boxname = fnames{num};
      texthandlename = sprintf('%sCheck', boxname);
      label = getfield(labels, boxname);
      color = getfield(colors, boxname);
      boxposition = ceil([...
         AA.box_start ;           %right
         (AA.figheight*vfracstart) + 1 +  (num - 1)*4*AA.vpad; %up
         4*AA.box_width;            %width of edit box
         AA.vppb*AA.vpad])';            %height of edit box
      
      AA.h = setfield(AA.h, texthandlename,...
                            uicontrol(...
                               'Parent',AA.h.autoeditfig, ...
                               'units','pixels',...
                               'ListboxTop',0, ...
                               'Position',boxposition,...
                               'string', label,...
                               'Style','checkbox', ...
                               'backgroundcolor', color,...
                               'max',1, 'min', 0, ...
                               'value', getfield(boxinfo, boxname),...
                               'horizontalalignment', 'left',...
                               'Tag',texthandlename));
      

   end
   fighandle = AA.h.autoeditfig;
   set(fighandle, 'userdata', AA);
   
   %end of function
%%%%%%%%%%%%%%%%%%%% end of mk_checkboxes %%%%%%%%%%%%%%%%%%%%

function list_AA

   fighandle = findobj('Tag','gautoedit_fig');
   if ~isemptys(fighandle)
      %get the userdata
      AA = get(fighandle,'userdata');
      AA.config
      AA.pfc
   end
   
%end of list


%%%%%%%%%%%%%%%%%%%% end of list_AA %%%%%%%%%%%%%%%%%%%%

function    get_blkprof;

   help cl_blkprf
   
   fprintf('This is cl_blkprf called with ''pg'' (see matlab commandline \n')
   fprintf('window for the output from ''help cl_blkprf''.  \n')
   fprintf('Click with the left button on locations of interest, and\n');
   fprintf('    hit return when finished\n\n')
   fprintf('You can access "cl_blkprf" yourself from the command line\n')
   fprintf('   by running this:\n')
   fprintf('[blkprf, sel_dday] = cl_blkprf(''pg'', ''a_''); \n')
   fprintf('try it with other variables such as ''umeas_g'', ''vmeas_g'' \n')
   

   fighandle = findobj('Tag','gautoedit_fig');
   AA = get(fighandle,'userdata');

   buttonhandle = findobj('Tag','cl_blkprfButton');
   buttonstrings = get(buttonhandle, 'string');
   buttonval = get(buttonhandle, 'value');

   if (buttonval ~= 1)
      buttonstring = buttonstrings{buttonval};
      set(buttonhandle, 'value', 1);

      if (isfield(AA.data, buttonstring))
         fprintf('getting block, profile info from data field %s\n', buttonstring)
         fn = buttonstring;
      else
         fprintf('select a field from the popup menu to use for cl_blkprf\n')
      end

      [blkprf, sel_dday] = cl_blkprf(fn, 'a_');
      
      if (length(blkprf(:,1)) > 0)
         fprintf('\n\n');
         for ii = 1:length(blkprf(:,1))
            fprintf('block: %4d,  profile: %4d,  bin %2d\n',...
                    blkprf(ii,1), blkprf(ii,2), sel_dday(ii,2))
         end
         close
         fprintf('\n\n');
      end
  end

%end of fcn   
%%%%%%%%%%%%%%%%%%%% end of cl_blkprf  %%%%%%%%%%%%%%%%%%%%


function     get_badtimes;
   
   fighandle = findobj('Tag','gautoedit_fig');
   AA = get(fighandle,'userdata');
   

   if ( get(AA.h.cl_badtimesButton, 'val') ~= 1)
   
      fprintf('\n\nIn the new figure showing percent good, \n')
      fprintf('Click on the beginning and end of the time range to flag as bad.\n')
      fprintf('The profiles are appended to badtimes.asc.\n\n')
      
      data = AA.data;
      config = AA.plotconfig;
      pfc = AA.pfc;
      
      hidenewflags = AA.bool.hidenewflags;
      hidepflags = AA.bool.hidepflags;
      
      flagged = zeros(size(data.umeas));
      if (~hidenewflags)
         [flagged] = (aflagit(data, config, pfc) | flagged);
      end
      if (~hidepflags)
         flagged = (flagged | data.pflag);
      end
      pflag = flagged;   %set flagit to zero to show all data
      
      figpos = get(501, 'position');

      badtimes = ...
          cl_badtimes(data, config, pflag, figpos, AA.config.yearbase);

      %Nx1 array of bad times
      if (isfield(AA, 'badprof'))
         AA.badprof = [AA.badprof; badtimes(:)];
      else
         AA.badprof = badtimes(:);
      end

      % write to ascii files using alistit
      [flagged, pfc] = manflags(AA);
      clear pflags % alistit expects "pflags"; must use that name
      pflags.yearbase = AA.config.yearbase;
      pflags.dday = AA.data.dday;
      pflags.flagged = flagged;
      pflags.flag = AA.pfc.flag;
      save m_flagged.mat pflags;
      flagfile = dir('m_flagged.mat');
      alistit(flagfile);
      
      set(fighandle,'userdata', AA);
      gautoedit('show_now');
   end
   

%end of fcn   
%%%%%%%%%%%%%%%%%%%% end of get_badtimes  %%%%%%%%%%%%%%%%%%%%

function    get_rzap_badbins;
   % fn is field name
   fighandle = findobj('Tag','gautoedit_fig');
   AA = get(fighandle,'userdata');
   
   if ( get(AA.h.rzap_badbinsButton, 'val') ~= 1)

      fprintf('\n\nIn the new figure, \n')
      fprintf('drag on a rectangle to flag bins as bad.\n')
      fprintf('The bins are appended to abadbins.asc.\n\n')

      data = AA.data;
      config = AA.config;
      pfc = AA.pfc;
      
      hidenewflags = AA.bool.hidenewflags;
      hidepflags = AA.bool.hidepflags;
      
      flagged = zeros(size(data.umeas));
      if (~hidenewflags)
         [flagged] = (aflagit(data, config, pfc) | flagged);
      end
      if (~hidepflags)
         flagged = (flagged | data.pflag);
      end
      pflag = flagged;   %set flagit to zero to show all data
      
      figpos = get(501, 'position');
      
      %% badrect is a structure with badrect.dday; badrect.bins

      badrect = rzap_badbins(AA, pflag, figpos);
      
      if (isemptys(AA.badrect))
         AA = rmfield(AA, 'badrect');
         numrect = 0;
      else
         numrect = length(AA.badrect);
      end
      %AA.badrect is a cellarray with elements of badbin structure
      AA.badrect{numrect + 1}.abcissa = badrect.dday;
      AA.badrect{numrect + 1}.ordinate = badrect.bins;
      
      
      % write to ascii files using alistit
      [flagged, pfc] = manflags(AA);
      clear pflags % alistit expects "pflags"; must use that name
      pflags.yearbase = AA.config.yearbase;
      pflags.dday = AA.data.dday;
      pflags.flagged = flagged;
      pflags.flag = AA.pfc.flag;
      save m_flagged.mat pflags;
      flagfile = dir('m_flagged.mat');
      alistit(flagfile);
      
     
      set(fighandle,'userdata', AA);
      gautoedit('show_now');
      
   end


%end of fcn   
%%%%%%%%%%%%%%%%%%%% end of get_rzap_badbins  %%%%%%%%%%%%%%%%%%%%

function    get_pzap_badbins;
   % fn is field name
   fighandle = findobj('Tag','gautoedit_fig');
   AA = get(fighandle,'userdata');
   
   if ( get(AA.h.pzap_badbinsButton, 'val') ~= 1)

      fprintf('\n\nIn the new figure, \n')
      fprintf('click on points to create vertices of a polygon.\n')
      fprintf('double-click to complete.\n')
      fprintf('The bins are appended to abadbins.asc.\n\n')

      data = AA.data;
      config = AA.config;
      pfc = AA.pfc;
      
      hidenewflags = AA.bool.hidenewflags;
      hidepflags = AA.bool.hidepflags;
      
      flagged = zeros(size(data.umeas));
      if (~hidenewflags)
         [flagged] = (aflagit(data, config, pfc) | flagged);
      end
      if (~hidepflags)
         flagged = (flagged | data.pflag);
      end
      pflag = flagged;   %set flagit to zero to show all data
      
      figpos = get(501, 'position');
      
      %% badrect is a structure with badrect.dday; badrect.bins

      badpoly = pzap_badbins(AA, pflag, figpos);
      
      if (isemptys(AA.badpoly))
         AA = rmfield(AA, 'badpoly');
         numpoly = 0;
      else
         numpoly = length(AA.badpoly);
      end
      %AA.badpoly is a cellarray with elements of badbin structure
      AA.badpoly{numpoly + 1}.abcissa = badpoly.dday;
      AA.badpoly{numpoly + 1}.ordinate = badpoly.bins;
      
      
      % write to ascii files using alistit
      [flagged, pfc] = manflags(AA);
      clear pflags % alistit expects "pflags"; must use that name
      pflags.yearbase = AA.config.yearbase;
      pflags.dday = AA.data.dday;
      pflags.flagged = flagged;
      pflags.flag = AA.pfc.flag;
      save m_flagged.mat pflags;
      flagfile = dir('m_flagged.mat');
      alistit(flagfile);
      
     
      set(fighandle,'userdata', AA);
      gautoedit('show_now');
      
   end


%end of fcn   
%%%%%%%%%%%%%%%%%%%% end of get pzap_badbins  %%%%%%%%%%%%%%%%%%%%


function    get_polybottom;
   % fn is field name
   fighandle = findobj('Tag','gautoedit_fig');
   AA = get(fighandle,'userdata');
   
   if ( get(AA.h.polybottomButton, 'val') ~= 1)

      
      fprintf('\n\nIn the new figure, \n')
      fprintf('click once at each vertex to define the bottom\n')
      fprintf('double-click to finish.\n')
      fprintf('The bins are appended to abottom.asc.\n\n')

      data = AA.data;
      config = AA.config;
      pfc = AA.pfc;
      
      hidenewflags = AA.bool.hidenewflags;
      hidepflags = AA.bool.hidepflags;
      
      flagged = zeros(size(data.umeas));
      if (~hidenewflags)
         [flagged] = (aflagit(data, config, pfc) | flagged);
      end
      if (~hidepflags)
         flagged = (flagged | data.pflag);
      end
      pflag = flagged;   %set flagit to zero to show all data
      
      figpos = get(501, 'position');
      
      %% mabs is a structure with mabs.dday; mabs.bins

      mabs = polybottom(AA, pflag, figpos) ;

      %AA.mabs is a structure with max amp bin
      if isemptys(AA.mabs)
         AA.mabs.abcissa = mabs.dday(:);
         AA.mabs.ordinate = mabs.bins(:);
      else
         AA.mabs.abcissa = [AA.mabs.abcissa; NaN; mabs.dday(:)];
         AA.mabs.ordinate = [AA.mabs.ordinate; NaN; mabs.bins(:)];
      end
      
      % write to ascii files using alistit
      % this is a bit wasteful
      [flagged, pfc] = manflags(AA);
      clear pflags % alistit expects "pflags"; must use that name
      pflags.yearbase = AA.config.yearbase;
      pflags.dday = AA.data.dday;
      pflags.flagged = flagged;
      pflags.flag = AA.pfc.flag;
      save m_flagged.mat pflags;
      flagfile = dir('m_flagged.mat');
      alistit(flagfile);

      set(fighandle,'userdata', AA);
      gautoedit('show_now');
      
   end


%end of fcn   
%%%%%%%%%%%%%%%%%%%% end of get_polybottom  %%%%%%%%%%%%%%%%%%%%

function    zap_edit;
   
string = ['Click with the left button on the dday to start editing using',...
          'the old waterfall editing.  This drops you into the old-style ',...
          'waterfall editing using the values in "setup.m".  Go to the ',...
          'command line and procede as usual.'];

   
   [data, config] = agetmat('a_');
   figure
   figpos = get(501, 'position');
   set(gcf, 'menubar','none','toolbar','none', 'pos', ...
            [figpos(1:3) round(figpos(4)/4)])
   whitebg(gcf,'w')

   new_pos = [.08 NaN .92 NaN];   %(new xstart and new width)
   ax1 = axes;
   pos = get(ax1, 'pos');

   set(ax1, 'pos', [new_pos(1)  pos(2) new_pos(3) pos(4)])


   fighandle = findobj('Tag','gautoedit_fig');
   AA = get(fighandle,'userdata');
   fprintf('%s\n', string)

   flagged = zeros(size(data.umeas));
   if (~AA.bool.hidenewflags)
      [flagged] = aflagit(data, AA.config, AA.pfc) | flagged;
   end
   if (~AA.bool.hidepflags)
      flagged = (flagged | data.pflag);
   end
   
   config.xlim = [AA.config.start_dd AA.config.start_dd+AA.config.ddrange];   
   cfg = aplotit(data, config, 'flagged', flagged , 'fn', 'pg');
   axes(cfg.cur_ax)
   %get dday
   sel_dday = ginput(1);  
   close
   %get the index to the closest profile
   [junk, bpi] = min(abs(data.dday - sel_dday(1)));

   data.iblkprf(bpi,:);
   data.time(bpi,:);
   fprintf(' %s  (dday %10.7f),  ', ...
           to_date(data.time(bpi,1), ...
                   to_day(data.time(bpi,1), data.time(bpi,:)),'s'),...
           data.dday(bpi))
   
   fprintf('block: %2d,  profile: %3d,  bin %2d\n',...
           data.iblkprf(bpi,1), data.iblkprf(bpi,2), floor(sel_dday(2)))

   %use what's there
   setup

   disp('running waterfall editing setup program')
   delete a.mat e.mat amp.mat depth.mat pf.mat other.mat 
   delete pg.mat u.mat v.mat w.mat
   getp( data.iblkprf(bpi,1), data.iblkprf(bpi,2))
   
   if (~exist('u.mat'))
      msgbox('waterfall editing program "setup.m" not properly configured.  Please check that program, edit, and restart gautoedit.')
      fprintf('\n\n\======================================================\n')
      fprintf('===============       !!! NOTE:   ====================\n\n')
      fprintf('waterfall editing program "setup.m" improperly configured.\n')
      fprintf('Please check that program, edit, and restart gautoedit.\n')
      fprintf('======================================================\n\n\n')
   else
      getp( data.iblkprf(bpi,1), data.iblkprf(bpi,2))
   end
   
   
   %override some stuff
   figure(2);uv
   figure(3);a
   fprintf('Use the command line to edit as usual with the waterfall plots\n')
   fprintf('Be sure to "list" when through\n')
   fprintf('Edit "setup.m" to change any editing parameters if desired\n')


%end of fcn   

%%%%%%%%%%%%%%%%%%%% make some help %%%%%%%%%%%%%%%%%%%%

function print_help
string = ['help is on the way... (look in the matlab window for now)'];

hh=helpdlg(string,'gautoedit help');

%%%%%%%%%%%%%%%%%%%% end of print_help %%%%%%%%%%%%%%%%%%%%

function print_listed

disp('segments listed by gautoedit:')

filename = 'gautoedit.log';

if (~exist(filename,'file'))
   fprintf('no data listed')
else
   fid = fopen(filename,'r');
   ff = fread(fid);
   ss = char(ff');
   cri = find(ff == 10);  %find the <CR>
   
   startlinei = [0;cri(1:end-1)]+1;
   endlinei = [cri];
   
   compare_str = 'listed';
   
   fprintf('\n\n-----  time ranges listed (for editing) in gautoedit.log ------\n')
   for linei = 1:length(startlinei)
      numstr = ff(startlinei(linei):endlinei(linei));
      linestr = char(numstr');
      if (findstr(compare_str, linestr));
         badi = find(numstr == 10);
         linestr(badi) = [];
         fprintf('<%s>\n',linestr)
      end
   end
   fprintf('------------------------------------------------------------\n\n')
   
   fclose(fid);
end




   
