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.
% - 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 
%============================================================================

% 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

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},'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_';
   config.ddrange = 2;  %override for this
   aflagit_setup;
   if (~isfield(pfc, 'reject_underway'))
      pfc.reject_underway = 0;
   end
   
   
   bool.showraw = 0;
   bool.newfigs = 0;
   bool.showdiagn = 0;
   bool.showtopo = 1;
   
   %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 .3 .6];
   %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');


   %%%%% 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.showraw = bool.showraw;
   bb.s2_label.showraw = 'do not show editing';
   bb.s2_color.showraw = .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.showdiagn = bool.showdiagn;
   bb.s2_label.showdiagn = 'show diagnostics panel';
   bb.s2_color.showdiagn = .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 0];
   
   %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 0];
   
   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 0];
   
   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 0];
   
   bb.s31.trimtopbins         = pfc.cfg.trimtopbins;
   bb.s31_label.trimtopbins   = 'number of bins rejected at the top';
   bb.s31_color.trimtopbins   =            [1 1 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   = ...
       'reject profile (if meas vel jitter exceeds (cm/s))';
   bb.s31_color.jitter_cutoff   =            [.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) ';
   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];

   %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.print_help   = 'print_help';
   bb.s0_label.print_help = 'help';
   bb.s0_color.print_help = [46 139 87]/255;
   
   bb.s0.cl_blkprf   = 'cl_blkprf';
   bb.s0_label.cl_blkprf = 'find PG [blk, prf]';
   bb.s0_color.cl_blkprf = [46 139 87]/255;
   
   bb.s0.print_listed   = 'print_listed';
   bb.s0_label.print_listed = 'show times 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 = [178 34 34]/255;
   
   bb.s4.show_next  = 'show_next';
   bb.s4_label.show_next = 'show next';
   bb.s4_color.show_next = [178 34 34]/255;
   
   bb.s4.zap_edit  = 'zap_edit';
   bb.s4_label.zap_edit = 'zap edit';
   bb.s4_color.zap_edit = [178 34 34]/255;

   bb.s4.list_flags = 'list_flags';
   bb.s4_label.list_flags = 'list flags 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_pressbuttons(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_pressbuttons(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 no fields to update for s0

   %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   
   if (isfield(AA.pfc.cfg, 'badpgrefl') & isfield(AA.pfc.cfg, 'pgcutoff'))
      AA.pfc.cfg.badpgrefl = AA.pfc.cfg.pgcutoff;
   else
      error('update_userdata: pfc.cfg missing field "badpgrefl" or "pgcutoff"')
   end
   

   %(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');
   
   
   config = AA.config;
   pfc = AA.pfc;
   
   flagit = ~(AA.bool.showraw);   %because I wanted to use checkbox not radio
   newfigs = AA.bool.newfigs;
   showtopo = AA.bool.showtopo;
   showdiagn = AA.bool.showdiagn;  
   
   %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

   [data, config] = agetmat(config);

   if (flagit)
      flagged = (aflagit(data, config, pfc) | data.pflag);
   else
      flagged = 0*data.umeas;
   end
   config.flagged = flagged;   %set flagit to zero to show all data


   if (newfigs)
      figure;
      base_fig = gcf;
   else
      figure(AA.h.autoeditfig);
      base_fig = gcf;
      figure(base_fig + 1);
   end

   uvfig = gcf;
   alookit;      %uabs, vabs, PG, ship speed
   
   if (showdiagn)
      figure(base_fig + 2);
      alookit_diagn;  %fore, err vel, spectral width, amp
   end

   if (showtopo)
      figure(base_fig + 3 );    %leave room for diagnostics  plot
      whitebg(base_fig + 3, '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

   %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 = 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_pressbuttons(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 pressbutton
         3*AA.vpad])';              %height of pressbutton
      
      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,...
                        'Tag', handlename));
   
   end

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

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 list_AA %%%%%%%%%%%%%%%%%%%%

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
   fighandle = findobj('Tag','gautoedit_fig');
   AA = get(fighandle,'userdata');
   flagged = aflagit(data, AA.config, AA.pfc);
   fprintf('%s\n', string)
   cfg = aplotit(data, config, 'flagged', (flagged | data.pflag) , '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




   
