function ensgyro2rbin(instclass, ensfile, fast)
% ensgyro2rbin(instclass, ensfile)
% reads ens (or enx) file and outputs (samebase.hdg.rbin)
% 


%% undocumented:
% ensgyro2rbin(instclass, enrfile, fast)
% reads enr files  (note: ens is uncorrected times)
% or reads ens (enx) files (note: times are UTC)
%    ... outputs (samebase.hdg.rbin)
% if fastread is 1, use fastread (only works for os)
% if ens or enx, times are UTC

if ~exist('fast', 'var')
   fast = 0;
end


[pp,nn,ext]=fileparts(ensfile);
gfile = sprintf('%s.hdg.rbin', nn);
if ~exist(gfile,'file')
   
   if fast == 1
      r = fastread(os, ensfile);
      hdg = [rdata.dday; rdata.heading];
      fprintf('writing to %s\n', gfile);
      write_bin(gfile, hdg, 'hdg', {'u_dday', 'heading'});
   else
      rdata = read(instclass, ensfile,'vars',{'ts','nav'});
      
      %%% NOTE: vmdas error wherein rdata.nav.txy may be wrong
      if isemptys(find(diff(rdata.nav.txy2(1,:)) <= 0))
         hdg = [rdata.nav.txy2(1,:); rdata.heading];
         fprintf('writing to %s\n', gfile);
         write_bin(gfile, hdg, 'hdg', {'u_dday', 'heading'});
      else
         %%% try this hack if the bug is there
         fprintf('WARNING: file %s may have bad times\n',gfile);
         dt = rdata.nav.sec_pc_minus_utc;
         [medfilt_dt, ibig] = medfilt(dt, 3, 20);
         oktimei = find(~ismember([1:length(dt)], ibig));
         
         figure
         subplot(211)
         plot(dt);hold on
         plot(medfilt_dt,'k.')
         plot(oktimei, medfilt_dt(oktimei),'g*')
         title(ensfile)
         
         % get instrument times (no glitches); 
         % don't copy this method for positions.
         instdday = rdata.dday;
         % convert instrument time to UTC time (does not include OS-PC)
         fprintf('correcting this file''s instrument times by %d seconds\n', round(medfilt_dt))
         utcdday = instdday - medfilt_dt/86400;
         
         subplot(212)
         plot(instdday,'ro')
         hold on
         plot(rdata.nav.txy2(1,:),'co')
         plot(utcdday,'b.')


         if ~isemptys(find(diff(utcdday) <= 0))
            utcdday = instdday - mstdgap(medfilt_dt)/86400;
            plot(utcdday,'mx')
         end            
         hdg = [utcdday; rdata.heading];
         fprintf('writing to %s\n', gfile);
         write_bin(gfile, hdg, 'hdg', {'u_dday', 'heading'});
            
      end
   end
else
   fprintf('file  %s exists. not overwriting\n', gfile);
end
