function [msg] = apply_ednav(varargin)
% [msg] = apply_ednav(name1, val1, name2, val2,...)
% * all options are optional except 'use_refsm', which is required (0 or 1)
% * apply editing, get smoothed navigation, apply navigation
% * start from edit directory; use asetup.m to set up variables;
% * writes log messages to edit.log and nav.log
%
%   ** This program is set up to run after quick_adcp.prl **
%  
%  name          default                       what
% config             []               % structure with required information
%                                     % Default is to read the info from 
%                                     % asetup.m.  
%                                     % if NOT running refsm, minimally
%                                     %   required fields are 
%                                     %   config.dbname = a0008 %database name
%                                     %   config.dbpath = '../adcpdb' 
%                                     % if YES running refsm, requires
%                                     %   a structure config.refsm_cfg with
%                                     %   appropriate defaults for refsm
% edit_log      'edit.log'            % timestamped log of applied edit steps
% nav_log       'nav.log'             % timestamped log of applied nav steps
% badbin_files  {'badbin.asc',        % cellarray of files for 'badbin'
%                'abadbin.asc'};      %
% dbupdate_files{'badprf.asc',        % cellarray of files for 'dbupdate'
%                'badtimes.asc',      %
%                'bottom.asc',        %
%                'abadprf.asc',       %
%                'abadtimes.asc',     %
%                'abottom.asc'}'      %
% suffix         'tmp';               % in edit: setflags.tmp, 
%                                     % in nav:  as_nav.tmp, refabs.tmp, 
%                                     % smoothr.tmp, putnav.tmp
%                                     % 
% apply_ed            1               % (1) apply editing, (0) skip that step
% get_smoothed_nav    1               % (1) get smoothed nav, (0) skip it
% navtype             []              % for smoothed navigation file:
%                                     % 'smoothr' [adcpsect, refabs, smoothr]
%                                     % 'refsm'   [refsm]
% putnav              1               % (1) run putnav: (does not create
%                                     %     control file.  you must already 
%                                     %     have it made correctly)
%                                     % (0) skip putnav
% 
%
%%  eg: (run from the edit/ subdirectory; "asetup" must be correct
% apply_ednav('navtype', 'refsm')

%% JH 2002/1/25
%% should add something to make sure there's some consistency (or a check) 
%% as to what kind of nav is being put into the database
%% 
%% also need to add refplots for refsm



%%log files
edcfg.edit_log = 'edit.log';
edcfg.nav_log =  'nav.log';
%% for editing:
edcfg.badbin_files = {'badbin.asc', 'abadbin.asc'};
edcfg.dbupdate_files = {'badprf.asc', 'badtimes.asc', 'bottom.asc', ...
                  'abadprf.asc', 'abadtimes.asc', 'abottom.asc'}';
edcfg.config = [];
edcfg.suffix = 'tmp';  %could be ".cnt" -- assume all are the same

edcfg.apply_ed = 1; %yes, by default
edcfg.get_smoothed_nav = 1; %yes, by default. %% for smoothed navigation
edcfg.navtype  = [];        %'smoothr' (use adcpsect, refabs, smoothr)
                            % use refsm instead
edcfg.putnav = 1;           %yes, by default


%%% 

if (nargin >= 1)
   edcfg = fillstruct(edcfg, varargin, 0);
end

if (nargin == 0)
   edcfg.navtype = 'refsm';
   fprintf('about to use navigation type REFSM\n')
   fprintf('counting down to implimentation:\n')
   for count = 4:-1:1
      fprintf('%d...\n',count)
      pause(1)
   end
end



badi = find(edcfg.suffix == '.'); edcfg.suffix(badi) = [];

%%% check things before continuing

[pp, nn, ee] = fileparts(pwd);
if (~strcmp(nn, 'edit'))
   fprintf('this program assumes you are in the edit/ subdirectory \n')
   fprintf('of an adcptree.  it will go to ../nav/ and then come back.\n')
   error('You must be in the edit/ subdirectory to start')
end

if (isempty(edcfg.config))
   if (exist('asetup', 'file'))
      asetup;
   else
      help(mfilename)
      error('must input config structure or must have asetup.m present')
   end
   edcfg.config = config;
end

if ( ~isfield(edcfg.config, 'dbname') | ~isfield(edcfg.config, 'dbpath'))
   error('config structure must contain fields dbname and dbpath')
end


if (edcfg.get_smoothed_nav)
   if (strcmp(edcfg.navtype, 'smoothr'))
      use_refsm = 0;
   elseif (strcmp(edcfg.navtype, 'refsm'))
      use_refsm = 1;
   else
      error('must specify navtype of ''smoothr'' or ''refsm'' ')
   end
end

%--------------------------------------------

% apply editing: badbin; dbupdate; set_lgb; setflags
if (edcfg.apply_ed)
   fprintf('applying editing\n')
   
   %%% editing steps
   %%% (1)  badbin
   
   [pp, nn, ee] = fileparts(pwd);
   if (~strcmp(nn, 'edit'))
      fprintf('You must be in the edit/ subdirectory to start')
   else
      flog = fopen(edcfg.edit_log, 'a');
   end

      
   for index = 1:length(edcfg.badbin_files)
      filename = edcfg.badbin_files{index};
      if (exist(filename, 'file'))
         command = sprintf('badbin %s%s %s', ...
                           edcfg.config.dbpath, edcfg.config.dbname, filename)
         
         [waserr, errstring] = unix(command);
         str = nowstr;
         if waserr
            str = sprintf('%s  error: %s\n', str, errstring);
         else
            str = sprintf('%s  ran %s\n', str, command);
         end
         fprintf(flog, str);
         msg.badbin{index} = str;
      else
         msg.badbin{index} =sprintf('file %s does not exist \n', filename);
      end
      fprintf(flog, msg.badbin{index})
   end
   
   fclose(flog);

   %%% (2)  dbupdate

   flog = fopen(edcfg.edit_log, 'a');
   for index = 1:length(edcfg.dbupdate_files)
      filename = edcfg.dbupdate_files{index};
      if (exist(filename, 'file'))
         command = sprintf('dbupdate %s%s %s', ...
                           edcfg.config.dbpath, edcfg.config.dbname, filename)
         
         [waserr, errstring] = unix(command);
         str = nowstr;
         if waserr
            str = sprintf('%s  error: %s\n', str, errstring);
         else
            str = sprintf('%s  ran %s\n', str, command);
         end
         fprintf(flog, str);
         fprintf(flog, '\n');
      
         msg.dbupdate{index} = str;
      else
         msg.dbupdate{index} =sprintf('file %s does not exist\n', filename);
      end
      fprintf(flog, msg.dbupdate{index})
   end
   fclose(flog);

   %%% (3) set_lgb
   
   flog = fopen(edcfg.edit_log, 'a');
   command = sprintf('set_lgb %s%s', ...
                     edcfg.config.dbpath, edcfg.config.dbname)
   [waserr, errstring] = unix(command);
   str = nowstr;
   if waserr
      str = sprintf('%s  error: %s\n', str, errstring);
   else
      str = sprintf('%s  ran %s\n', str, command);
   end
   fprintf(flog, str);
   msg.set_lgb = str;
   
   fclose(flog);

   %%% (4) setflags

   flog = fopen(edcfg.edit_log, 'a');
   command = sprintf('setflags setflags.%s', edcfg.suffix)
   [waserr, errstring] = unix(command);
   str = nowstr;
   if waserr
      str = sprintf('%s  error: %s\n', str, errstring);
   else
      str = sprintf('%s  ran %s\n', str, command);
   end
   fprintf(flog, str);
   msg.setflags = str;
   fclose(flog);

end

%---------------------------------------%
% nav steps 
%(1) either [adcpsect, refabs, smoothr] or [refsm]
                  
cd ../nav

if (edcfg.get_smoothed_nav)

   [pp, nn, ee] = fileparts(pwd);
   if (~strcmp(nn, 'nav'))
      fprintf('You must be in the nav/ subdirectory to start')
   else
      flog = fopen(edcfg.nav_log, 'a');
   end

   
   if (use_refsm)
      str = nowstr;
      str = sprintf('%s running refsm\n', str) 
      fprintf(flog, str);
      refsm                       %%%beware: loads asetup.m (with config)
      msg.refsm = str;
      fprintf(flog, msg.refsm);
      fprintf(flog, '\n');
   else
      
      %adcpsect
      
      command = sprintf('adcpsect as_nav.%s', edcfg.suffix)
      [waserr, errstring] = unix(command);
      str = nowstr;
      if waserr
         str = sprintf('%s  error: %s\n', str, errstring);
      else
         str = sprintf('%s  ran %s\n', str, command);
      end
      fprintf(flog, str);
      msg.adcpsect = str;
      

      %refabs

      
      command = sprintf('refabs refabs.%s', edcfg.suffix)
      [waserr, errstring] = unix(command);
      str = nowstr;
      if waserr
         str = sprintf('%s  error: %s\n', str, errstring);
      else
         str = sprintf('%s  ran %s\n', str, command);
      end
      fprintf(flog, str);
      msg.refabs = str;
      

      %smoothr
      
      
      command = sprintf('smoothr smoothr.%s', edcfg.suffix)
      [waserr, errstring] = unix(command);
      str = nowstr;
      if waserr
         str = sprintf('%s  error: %s\n', str, errstring);
      else
         str = sprintf('%s  ran %s\n', str, command);
      end
      fprintf(flog, str);
      msg.smoothr = str;

   end
   
   fclose(flog);
end
cd ../edit

%--------------------------------------------

cd ../nav
if (edcfg.putnav)
   [pp, nn, ee] = fileparts(pwd);
   if (~strcmp(nn, 'nav'))
      fprintf('You must be in the nav/ subdirectory to start')
   else
      flog = fopen(edcfg.nav_log, 'a');
   end

   command = sprintf('putnav putnav.%s', edcfg.suffix)
   [waserr, errstring] = unix(command);
   str = nowstr;
   if waserr
      str = sprintf('%s  error: %s\n', str, errstring);
   else
      str = sprintf('%s  ran %s\n', str, command);
   end
   fprintf(flog, str);
   msg.putnav = str;

end
cd ../edit


if (~exist('msg', 'var'))
   msg = [];
end
