function mktrkrng(year_base, infile, outfile, dxy, halfwidth);

% function mktrkrng(year_base, infile, outfile, dxy, halfwidth);
% Make Alongtrack Time Ranges
%
% Generate a set of time ranges to be used by adcpsect
% for extracting velocities, typically for vector plotting.
% Ranges are generated at uniform along-track intervals,
% based on a smoothed version of the ship's velocity from
% the output of smoothr.
%
% yearbase: 4-digit year.
% infile: made up of lines from *.sm (smoothr output)
% outfile will have time ranges
% dxy is the interval in km
% (optional) halfwidth is the half width of the ship
%     velocity smoothing blackman filter, in units of adcp
%     ensembles.  Default is 6.
%
% EF Sun  99/02/28
%

if nargin < 4, help('mktrkrng'); error('need 4 or 5 args'); end
if nargin == 4, halfwidth = 6; end

[t,x,y] = read_asc(infile, 8, [1 6 7]);
ii = find(x > 1e30);
t(ii) = []; x(ii) = []; y(ii) = [];

dxm = lon_to_m(diff(x), y(2:end));
dym = lat_to_m(diff(y), y(2:end));
dt = diff(t) * 86400;

uvship = (dxm + i * dym) ./ dt;
uvship_sm = bl_filt(uvship, halfwidth);  % 4 -> 20-min half-width for 5-min ens.

spd_sm = abs(uvship_sm);
disp = [0; cumsum(spd_sm .* dt)];

disp_grid = (disp(1):(dxy*1000):disp(end)).';

it = (1:length(t)).';
it_grid = floor(table1([disp, it], disp_grid));

it0 = (it_grid(1:(end-1)) + 1).';  % row
it1 = (it_grid(2:end)).';

ibad = find(diff([it0; it1]) < 2);
it0(ibad) = []; it1(ibad) = [];


date0 = to_date(year_base, t(it0), 'n');
date1 = to_date(year_base, t(it1), 'n');
format1 = '%4d/%02d/%02d %02d:%02d:%02.0f to %4d/%02d/%02d %02d:%02d:%02.0f\n';

format2 = '   /* %4.0f, %10.5f to %10.5f, x,y: %8.3f %7.3f to %8.3f %7.3f */\n';
outarray = [date0, date1, ...
            (1440 * (t(it1) - t(it0))), ...
            t(it0), t(it1), ...
            x(it0), y(it0), x(it1), y(it1)].';

fid = fopen(outfile, 'wt');
fprintf(fid, '/* mktrkrng.m: input file %s, dxy %.1f km */\n', ...
                  infile, dxy);
fprintf(fid, [format1, format2], outarray);
fclose(fid);

