% This is the matlab driver for adcp_nav (matlab-driven reference layer
% and smoothr calculation.
%
% set up variables cfg, dbname, fixfile as below,  and run.
% It will write a smoothr file in the current directory (presumably "nav/") 
%     (file set to 'refsm.sm' below) and will delete the matlab files 
%     which were created.
% 
% You can of course just copy this file to your nav/ directory and edit it.
% 
% refsm.sm is written with slightly different columns:
%  1       2      3      4      5      6    7      8
% dday  dx(km) dy(km)  shipu  shipv   lon  lat  was_adjusted
%
% set variables as follows:
%
%
% cfg.yearbase = 2001;
% cfg.min_pg = 50;
% cfg.min_maxpg = 70;
% cfg.bl_half_width = 3;
% cfg.xy_bl_half_width = 6;
% cfg.ref_top = 1;
% cfg.ref_mid = 20;
% cfg.ref_bot = 20;
% cfg.fix_t_mismatch = 10; % seconds between ensemble time and fix time
% cfg.min_xy_frac = 0.05;
% cfg.min_uv_frac = 0.5;
% cfg.max_dt = 310;

% dbname = 'a0104';
% fixfile = 'a0104.ags';


%---------------------------------------------------------
dbpath = '../adcpdb/';
sm_filename = 'refsm.sm'
cleanup = 1;

[fixes.dd, fixes.x, fixes.y] = read_asc(fixfile);

% do the whole thing:
if ~exist('refsm_u.mat', 'file'),
   eval(['!getmat -f refsm_ ', ...
         fullfile(dbpath, dbname), ' 0 0 100000 ', int2str(cfg.ref_bot)]);
end

load refsm_u
load refsm_v
load refsm_pg
load refsm_pf
load refsm_other

profs.dd = to_day(cfg.yearbase, TIME).';  % Row vector
profs.u = U;        clear U
profs.v = V;        clear V
profs.pg = PGOOD;   clear PGOOD
profs.pf = PFLAG;   clear PFLAG

if cleanup,
   delete refsm_*.mat
end

[fixed, uv] = adcp_nav(fixes, profs, cfg);


ii = cfg.ref_top:cfg.ref_mid;
uv_reflayer_adj = mstdgap(uv.adj(ii, :));
uv_reflayer_raw = mstdgap(uv.raw(ii, :));

sm_table = ones(8, length(profs.dd));
sm_table(1,:) = profs.dd;
%%% change these [2 and 3] from their old meanings
% make these indicate how far points have been moved (meters)
sm_table(2,:) = lon_to_m(fixed.x_adj - fixed.x, [fixed.y_av(1) fixed.y_av]);
sm_table(3,:) = lat_to_m(fixed.y_adj - fixed.y, [fixed.y_av(1) fixed.y_av]);
%the rest are the same:
sm_table(4,:) = fixed.u_adj;
sm_table(5,:) = fixed.v_adj;
sm_table(6,:) = fixed.x_adj;
sm_table(7,:) = fixed.y_adj;
sm_table(8,:) = fixed.was_adjusted;


fid = fopen(sm_filename, 'w');
ff = '%12.6f  %7.3f %7.3f  %7.3f %7.3f %12.6f %12.6f %4.2f\n';
bigstring = sprintf(ff, sm_table);
newstring = strrep(bigstring, ' NaN', '1e38');
fprintf(fid, '%s', newstring);
fclose(fid);

   