function [uvss, fmm, fss] = best_xducerxy(varargin);
%[uvss, fm, fss] = best_xducerxy(varargin);
% varargin is name, value pairs
%
%  name          what                                default
% 'yearbase', 1993                                    (required)
% 'dbpath',    relative databse path                 ../adcpdb
% 'dbname' ,  database name                        ../adcpdb/*dir.blk
% 'fixfile'     positions                             '../nav/[dbname].ags'
% 'xoffsets',    offset athwartship                           0
% 'yoffsets',    offset fore/aft                       [-35:5:35];
% 'enl',  enlarge outside time ranges by 'enl' secs    300  
% 'plotref',   (plot actual ref velocites)               0
%
% run from nav subdirectory

cfg.yearbase = [];
cfg.dbpath = '../adcpdb';
cfg.dbname = [];
cfg.xoffsets = 0;
cfg.yoffsets = [-35:5:35];
cfg.plotref = 0;
cfg.enl = 300;
cfg.fixfile = [];


cfg = fillstruct(cfg, varargin, 0);

if isempty(cfg.yearbase)
   help(mfilename)
   fprintf('must select yearbase\n');
   return
end

   

if (isempty(cfg.dbname))
   dirblklist = dirs(fullfile(cfg.dbpath, '*dir.blk'));
   if (isempty(dirblklist))
      fprintf('no database found in path %s\n', cfg.dbpath)
      help(mfilename)
      return
   else
      if (length(dirblklist) > 1)
         fprintf('found more than one database.  Block files:\n')
         for ii=1:length(dirblklist)
            fprintf('%s\n', dirblklist(ii).name)
         end
         return
      end
   end
   % one dbname
   cfg.dbname = dirblklist(1).name;
   cfg.dbname(end-6:end) = [];
end


if isempty(cfg.fixfile)
   cfg.fixfile = sprintf('../nav/%s.ags', cfg.dbname)
   fprintf('setting fix file to %s\n', cfg.fixfile)
end


%% detemine the along-ship offset

%stores stddev of 2nd derivative (to look for characteristic peaks)
% for inferred ocean u, v, and abs(u+i*v) in columns 1,2,3
uvss  = zeros(length(cfg.xoffsets), length(cfg.yoffsets));
%filtered mean diff
fmm =  zeros(length(cfg.xoffsets), length(cfg.yoffsets));
fss =  zeros(length(cfg.xoffsets), length(cfg.yoffsets));

colors = 'rgbk';
if (cfg.plotref)
   figure
   colornum = 1;
end

for yoffseti = 1:length(cfg.yoffsets)
   yoffset = cfg.yoffsets(yoffseti);
   
   for xoffseti = 1:length(cfg.xoffsets)
      xoffset = cfg.xoffsets(xoffseti);

      fprintf('running xducerxy_core for dx=%d, dy=%d\n', xoffset, yoffset)
      
      % run lst_hdg only on the first iteration
      if (xoffseti + yoffseti == 2)
         run_lsthdg = 1;
      else
         run_lsthdg = 0;
      end
         
      xducerxy_core('yearbase', cfg.yearbase,  'hdgsrc', run_lsthdg,...
                    'fixfile', cfg.fixfile,...
                    'dx', xoffset, 'dy', yoffset,'enl', cfg.enl);

      fid = fopen('refabs_test.tmp','w');
      fprintf(fid, '      fix_file_type:    simple\n', cfg.dbname);
      fprintf(fid, '      reference_file:   %s.nav\n', cfg.dbname);
      fprintf(fid, '      fix_file:         %s.agt\n', cfg.dbname);
      fprintf(fid, '      output:           %s.reftest\n', cfg.dbname);
      fprintf(fid, '      year_base=        %d\n', cfg.yearbase);
      fprintf(fid, '      ensemble_length=  300\n');
      fprintf(fid, '      gap_tolerance=    10\n');
      fclose(fid);
      
      !refabs refabs_test.tmp
      
      data = read_asc(sprintf('%s.reftest', cfg.dbname));
      dday = data(:,1);
      refu = data(:,4);
      refv = data(:,5);
      [mm,uss(xoffseti,yoffseti)]=mstdgap( diff(diff(refu)));
      [mm,vss(xoffseti,yoffseti)]=mstdgap( diff(diff(refv)));
      [mm,uvss(xoffseti,yoffseti)]=mstdgap(abs(diff(diff(refu + i*refv))));
      [fmm(xoffseti, yoffseti), fss(xoffseti, yoffseti)] = ...
          mstdgap(abs((refu - boxfilt(refu,3))+i*(refv - boxfilt(refv,3))));
      
      if (cfg.plotref)
         subplot(211);plot(dday, refu, 'color', colors(colornum)); hold on
         subplot(212);plot(dday, refv, 'color', colors(colornum)); hold on
         colornum = colornum + 1;
         if (colornum == 5); colornum = 1; end
      end
   end
end

if (cfg.plotref)
   subplot(211)
   title('ref u')
   subplot(212)
   title('refv')
end


figure
if (length(cfg.yoffsets)==1) | (length(cfg.xoffsets)==1)
   subplot(211)
   plot(cfg.yoffsets,uvss,'b.-');
   xlabel('transducer offset in meters forward of antenna')
   title(sprintf('%s: std(scaled 2nd derivative of abs(ocean velocity))',...
                 cfg.dbname))
   subplot(212)
   plot(cfg.xoffsets,uvss','b.-');
   xlabel('transducer offset in meters starboard of antenna')
   title(sprintf('%s: std(scaled 2nd derivative of abs(ocean velocity))',...
              cfg.dbname))
   
else
   subplot(221)
   plot(cfg.yoffsets,uvss,'b.-');
   xlabel('transducer offset in meters forward of antenna')
   title(sprintf('%s: std(scaled 2nd derivative of abs(ocean velocity))',...
                 cfg.dbname))
   subplot(222)
   plot(cfg.xoffsets,uvss','b.-');
   xlabel('transducer offset in meters starboard of antenna')
   title(sprintf('%s: std(scaled 2nd derivative of abs(ocean velocity))',...
              cfg.dbname))
   
   subplot(212)
   contour(cfg.xoffsets,cfg.yoffsets,uvss','r')
   hold on
   contour(cfg.xoffsets,cfg.yoffsets,fmm','g') 
   contour(cfg.xoffsets,cfg.yoffsets,fss','b')
   xlabel('transducer offset in meters starboard of antenna')
   ylabel('transducer offset in meters forward of antenna')
   title('2nd diff (r), mean(vel-filt) (g), std(vel-filt) (k)')
   axis('equal')
end


printit('best_xducerxy.ps','orient','tall')
%%%%%%%%%