function dday =  tablelegs(bindata, binstruct, timetable, errfile, debug)
% dday =  tablelegs(bindata, binstruct, timetable, errfile, debug )
%
% returns unixd in UTC 
%
%% timetable: good version of [unixd gga sec_pc_minus_utc]
%% bindata, binstruct are one of three types:
% (1) from gps: contains gga (!!! must apply QC !!!)
%         look for binstruct.rows to contain 'dday' or 'dday_frac'
% (2) from instrument (contains a reasonable timestamp though not gga)
%         look for binstruct.rows to contain 'adcp'
% (3) other serial stream (eg. gyro or soundspeed)  -- then rely on regularity
%                    of serial stream

efid = fopen(errfile,'a');
dday = [];

if isemptys(bindata)
   fprintf('empty tablelegs\n')
   tabled = [];
   fclose(efid);
   return
end

ser_udday  = timetable(1,:);
ser_gga    = timetable(2,:);
ser_dt     = timetable(3,:)/86400;  

% also called logger_dday in mk_gbin.m
u_dday = bindata(r_row(binstruct, 'u_dday'),:);
dday = NaN*u_dday;;


if nargin > 4
   if debug
      figure(444);clf
      subplot(311)
      plot(ser_udday,'g.-')
      hold on
      plot(ser_gga,'r.')
      subplot(312)
      plot(ser_dt*86400,'bo-')
      subplot(313)
      plot(u_dday,'k.')
      keyboard
   end
end

   


if ismember('dday_frac', binstruct.rows) | ismember('dday', binstruct.rows)
   %% this is a gga message: use it
   if ismember('dday', binstruct.rows)
      dday = bindata(r_row(binstruct, 'dday'),:);
   elseif ismember('dday_frac', binstruct.rows)
      tt = bindata(r_row(binstruct, 'dday_frac'),:);
      tt = rem(bindata(2,:),1);    %% make it between -1 and 1 
      tt = rem(tt + 1, 1);         %% make it between 0 and 1
      dt = rem(u_dday - tt + .5,1) - .5;
      dday = u_dday - dt;
   else
      fprintf('ERROR: no gga message in this serial %s data.  \n', ...
              rstruct.messagename)
      fprintf(' choose  another data stream for besttime\n')
      uutc = [];
      fclose(efid)
      return;
   end
elseif ismember('adcp_dday', binstruct.rows)
   
   % if here, we have no gga message but we have instrument times
   % and timetable: [u_dday utc sec_pc_minus_utc]
   % 
   % look for jumps in diff(adcp_dday - u_dday) that excede [something]
   % 
   
   
   %% the data:
   %  from above, 
   %% u_dday = bindata(r_row(binstruct, 'u_dday'),:);
   
   %initialize with NaN: if there are any left, there is a problem
   

   % these are jumps in serial (gga) offset from GGA   
   serjumpi = find(abs(diff(ser_dt)) > .5/86400);
   if length(serjumpi) == 0
      serseg_starti = 1;
      serseg_endi = length(ser_gga);
   else   
      serseg_starti = [1 ; serjumpi(:)+1];
      serseg_endi   = [serjumpi(:); length(ser_gga)];
   end
   
   fprintf(' found %d jump(s) in computer clock from gga\n', length(serjumpi))
   efid = fopen(errfile,'a');
   fprintf(efid,' found %d jump(s) in computer clock from gga\n', ...
           length(serjumpi));
   fclose(efid);

   %%%%%%   
   % these are jumps in computer time indicated by instrument clock
   
   udday_self_dt = diff(u_dday);
   adcp_dday = bindata(r_row(binstruct,'adcp_dday'),:);
   adcp_self_dt   = diff(adcp_dday);
   
   %%% other attemtps:
   % test_dt =  udday_self_dt - adcp_self_dt;
   % test_dt = u_dday - adcp_dday;
   
   numjumps = length(find(diff(u_dday) <= 0));
   if numjumps == 0
      % no correction necessary
      dday = u_dday - mstdgap(timetable(3,:)/86400);
   else
      test_dt = medfilt(u_dday - adcp_dday,7, .1/86400);
      for secjump = 0:.01:100
         logjumpi = find(abs(diff(test_dt)) > secjump/86400);
         if length(logjumpi) == length(serjumpi)
            fprintf(' matched jumps with adcp logdata at dt=%3.2fsec\n',secjump)
            efid = fopen(errfile,'a');
            fprintf(efid, 'matched jumps with adcp logdata at dt=%3.2fsec\n',...
                    secjump);
            fclose(efid);
            break
         end
      end
      if secjump == 100
         fprintf('could not match number of jumps \n')
         fprintf('returning something cheap\n')
         efid = fopen(errfile,'a');
         fprintf(efid,'could not match number of jumps \n');
         fprintf(efid,'returning something cheap\n');
         fclose(efid)
         
         scalefactor = (length(ser_gga)-1)/(length(bindata(1,:))-1);
         index = [0 : length(bindata(1,:))-1];
         dday = table1([  [0:(length(ser_gga)-1)]' ser_gga'], scalefactor*index)';
         return
      end
      
      if length(serjumpi) == 0
         logseg_starti = 1;
         logseg_endi = length(u_dday);
      else
         logseg_starti = [1 ; logjumpi(:)+1];
         logseg_endi   = [logjumpi(:); length(u_dday)];
      end
      
      dday = zeros(size(u_dday));
      for segnum = 1:length(serseg_starti)
         serstarti = serseg_starti(segnum);           %timetable
         serendi   = serseg_endi(segnum);             
         serjj = serstarti:serendi;
         
         logstarti = logseg_starti(segnum);           %adcp
         logendi   = logseg_endi(segnum);             
         logjj = logstarti:logendi;
         
         % try u_dday - dt      
         dday(logjj) = u_dday(logjj) - mstdgap(ser_dt(serjj)); 
         
         if segnum > 1
            clf
            plot(u_dday,'g.')
            hold on
            plot(logjj, u_dday(logjj), 'ro')
         end
      end   
   end
   
else
   
   gga_index = [1:length(ser_gga)];
   log_index = table1( [ 1             1;
                     length(u_dday)   length(ser_gga)], [1:length(bindata(1,:))])';

   dday = table1([gga_index'  ser_gga'], log_index)';

end


if length(find(isnan(dday))) ~= 0
   fprintf('in tablelegs; NaN found\n')
   dday = [];
   return
end
  
 

if min(diff(dday)) <= 0
   fprintf('in tablelegs; non monotonic best times \n')
   dday = [];
   return
end
  
  
        
        
           
        
        
  
        
      
      
      
   


