function [osdday, osv]=get_osvel(dday, varargin)
% osdday = get_osvel(dday)
% [osdday, osv]=get_osvel(dday, varargin)
% given on-station times, group into stations
%
% varargin:          what                       default
% 'vel'             velocity                     (none)
%  'interval'       ensemble length in seconds    300
%  'duration'       int: number of intervals
%                   that counts as a transit       5
%  'statime'        station time: 
%                       'start'   Nx1
%                       'mean'    Nx1            'mean'
%                        'end'    Nx1
%                      'startend' Nx2     
%
% note: this works with underway times and station lengths as 
%    well as onstation times and transit lengths

% JH 2003/07/07 

cfg.interval = 300;
cfg.vel = [];
cfg.duration = 5;
cfg.statime = 'mean';

cfg = fillstruct(cfg, varargin,0);

statimes = {'start','end','mean','startend'};
if ~ismember(cfg.statime, statimes)
   fprintf('must choose ''statimes'' from this list\n')
   statimes
   return
end

if (~isempty(cfg.vel))
   if (length(cfg.vel) ~= length(dday))
      fprintf('velocity and dday do not have the same lengths\n')
      return
   end
end



transit = cfg.duration * cfg.interval;  %in seconds
jumpi = find(diff(dday*86400) > transit);

starti = [1 ,  jumpi(1:end)+1]';
endi =   [jumpi(1:end), length(dday)]';


dummy = ones(size(starti));
if (strcmp(cfg.statime, 'startend'))
   osdday = NaN*[ dummy dummy];
else
   osdday = NaN*dummy;
end
osv =  NaN*dummy;


for ii=1:length(osdday)
   if (strcmp(cfg.statime, 'mean'))
      osdday(ii) = mean(dday(starti(ii):endi(ii)));
   elseif (strcmp(cfg.statime, 'start'))
      osdday(ii) = dday(starti(ii));
   elseif (strcmp(cfg.statime, 'end'))
      osdday(ii) = dday(endi(ii));
   else
      osdday(ii,1) = dday(starti(ii));      
      osdday(ii,2) = dday(endi(ii));      
   end
      
   if (~isempty(cfg.vel))
      osv(ii) = mstdgap(cfg.vel(starti(ii):endi(ii)));
   end
end
