function  gautoedit(varargin)
%===============================  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
%           [blkprf, sel_dday] = cl_blkprf('uabs_sm', 'a_');
% - must have adcppath, aeditpath, mmappath, utilpath, ef_path
% - explore with "show now" and "show next"; 
%         list the flags to ascii files with "list flags"
%         ("list flags" writes flagging values used to a log file)
% - remember to apply the editing and rerun the nav steps after listing all 
% - the jitter criterion: do 'help alookit'
%============================================================================

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

%programming notes:
% useful updates: 
% use cl_blkprf to create bottom, badbin and badprf values to list
%      (use cl_blkprf to call old-fashioned editing (list to badbin.asc))
% plot jitter criteria and cutoff
%
%   fighandle = findobj('Tag','gautoedit_fig');      
%   AA = get(fighandle,'userdata');
%
%
% 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.

if (isempty(varargin))
   %start things up  ----------
   initialize;
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},'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

   %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
   
   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.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.bool = bool;
   AA.figbackground = [0 .9 .95];
   AA.figsize = [.01 .02 .5 .8];  %fractions of 1: [left bottom width height]
   %make the figure that holds the buttons
   AA.h.autoeditfig = figure(500);
   set(AA.h.autoeditfig,...
      'Tag','gautoedit', ...
      'units','normalized',...
      'ToolBar','none', ...
      'menubar','none', ...
      'color',AA.figbackground, ...
      'tag', 'gautoedit_fig',...
      'position', AA.figsize,...
       '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.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.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 = '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.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   = ...
       'measured velocity jitter: reject profile if jitter  > (cm/s)';
   bb.s31_color.jitter_cutoff   =            [.9 .6 .9];


   bb.s31.badpgrefl         = pfc.cfg.badpgrefl;
   bb.s31_label.badpgrefl   = ...
       'reference layer Percent Good cutoff (for N bins in refl, see next) ';
   bb.s31_color.badpgrefl   =            [.9 .6 .9];

   
   bb.s31.badpgrefl_nbins       = pfc.cfg.badpgrefl_nbins;
   bb.s31_label.badpgrefl_nbins = ...
       'reject profile (if fewer than N bins with good PG 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    = ...
       'reject profile (requires N neighbors)';
   bb.s31_color.orphan_slide    =            [.9 .6 .9];


   bb.s31.underway             = pfc.cfg.underway;
   bb.s31_label.underway       = ...
       'discard underway profiles (cutoff in m/s) ';
   bb.s31_color.underway       =         [.9 .6 .9];
   
   %reference layer bins ("pfc" structure)
   bb.s32.refl_startbin         = pfc.refl_startbin;
   bb.s32_label.refl_startbin   = ...
       'first reference layer bin (use ONE for the whole cruise)';
   bb.s32_color.refl_startbin   =        AA.figbackground;
   
   bb.s32.refl_endbin           = pfc.refl_endbin;
   bb.s32_label.refl_endbin     =  ...
       'last reference layer bin (use ONE for the whole cruise)';
   bb.s32_color.refl_endbin     =  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.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 ot 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]';
   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.cl_badtimes   = 'cl_badtimes';
   bb.s4_label.cl_badtimes = {'del time range',
                    'pg',
                    'uabs_sm',
                    'vabs_sm',
                    'fabs_sm'};
   bb.s4_color.cl_badtimes = [178 34 34]/255;

   
   bb.s4.rzap_badbins  = 'rzap_badbins';
   bb.s4_label.rzap_badbins = {'rzap bad bins',
                    'pg',
                    'uabs_sm',
                    'vabs_sm',
                    'fabs_sm'};
   bb.s4_color.rzap_badbins = [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); 
   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.box_start = .05*AA.figwidth;   %box is for editable text fields
   AA.box_width = .15*AA.figwidth;
   AA.box_height = 3*AA.vpad;

   AA.label_start = AA.box_start + AA.box_width + .1;  %labels
   AA.label_width = .8*AA.figwidth;
   AA.label_height = .8*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
   vppb = 4; %vpads per box
   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 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);
      AA.pfc = setfield(AA.pfc, ...
                        boxname,...
                        round(str2num(get(uihandle, 'string'))));

   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;
   
   hidenewflags = AA.bool.hidenewflags;
   hidepflags = AA.bool.hidepflags;
   newfigs = AA.bool.newfigs;
   showtopo = AA.bool.showtopo;
   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 (isempty(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)
      [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
   
   %% jitter type
   % AA.data.ref_std = AA.data.jitter(AA.jitterval,:);
   % data.ref_std = AA.data.ref_std;

   config = fillstruct(AA.config, AA.plotconfig);


   flagged = 0*data.umeas;
   if (~hidenewflags)
      [flagged] = (aflagit(data, config, pfc) | flagged);
   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')
      base_fig = gcf;
   else
      figure(AA.h.autoeditfig);
      base_fig = gcf;
      figure(base_fig + 1);
      hfig = gcf;
      set(hfig , 'menubar','none','toolbar','none');
   end

   uvfig = gcf;
   
   alookit;      %uabs, vabs, PG, ship speed
   
   if (showdiagn1)
      figure(base_fig + 2);
      hfig = gcf;      
      set(hfig, 'menubar','none','toolbar','none');
      % do not show editing for diagnostics
      config.flagged = 0*data.umeas;
      alookit_diagn1;  %fore, err vel, spectral width, amp
   end

   if (showdiagn2)
      figure(base_fig + 3);
      hfig = gcf;      
      set(hfig, 'menubar','none','toolbar','none');
      % do not show editing for diagnostics
      config.flagged = 0*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');
      %leave room for diagnostics  plot
      config.flagged = flagged;
      whitebg(base_fig + 4, 'w');
      apuv(data, config, topo_clev, mvec_scale, 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))
   %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 (~isempty(data))
      [flagged, pfc] = aflagit(data, config, pfc);

      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);
   
      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
   end
   
   gautoedit('print_listed')
   
%end of function

%%%%%%%%%%%%%%%%%%%% end list_flags %%%%%%%%%%%%%%%%%%%%
   


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
         3*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)*4*AA.vpad; %up
         AA.box_width;            %width of edit box
         3*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
         3*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 ~isempty(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
   
   string = ['This is cl_blkprf called with ''pg'' (see matlab commandline ',...
             'window for the output from ''help cl_blkprf''.  You can access ',...
             'cl_blkprf yourself from the command line.  ',...
             '          ',...
             'Click with the left button on locations of interest, and ',...
             'hit return when finished']
%   hh=helpdlg(string,'click [blk,prf] help');
%   pos = get(hh,'pos');
%   set(hh,'position',[30 30 pos(3:4)])
   
   
   [blkprf, sel_dday] = cl_blkprf('pg', 'a_');
   fprintf('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')
   
   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 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.config;
      pfc = AA.pfc;
      
      hidenewflags = AA.bool.hidenewflags;
      hidepflags = AA.bool.hidepflags;
      
      flagged = 0*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');
      cl_badtimes(AA.data, AA.config, pflag, figpos, AA.config.yearbase);
   end
   

%end of fcn   
%%%%%%%%%%%%%%%%%%%% end of cl_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 profiles 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 = 0*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');
      rzap_badbins(AA.data, AA.config, pflag, figpos, ...
                   AA.config.yearbase)        ;
   end


%end of fcn   
%%%%%%%%%%%%%%%%%%%% end of cl_badtimes  %%%%%%%%%%%%%%%%%%%%

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 = 0*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
   getp( data.iblkprf(bpi,1), data.iblkprf(bpi,2))
   %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




   
