% Plot Clock Offset

function plotClockError ( posData, key, parameters, ctrl, abscissa ) 

if ~ctrl.plotClk
  disp( 'Skip plotting clock data');
  return;
else
  disp('Plotting clock data');
end
  

% Extract relevant data
time = posData(:,key.TIME);
bias = posData(:,key.CLKBIAS); % ms 
drift = posData(:,key.CLKDRIFT); % ms/s
unwrappedBias = myunwrap( bias, 0.5 ); % ms
detrendedBias = detrend( unwrappedBias );

% Remove end of week rollovers from diffTime. 
diffTime = diff(time);
weekends = find(diffTime > (604800.0/2));
diffTime(weekends) = diffTime(weekends) - 604800.0;
weekends = find(diffTime < (-604800.0/2));
diffTime(weekends) = diffTime(weekends) + 604800.0;

for verticalView = 0:1
  %% Create figure
  figHandle = newfigure('Visible',ctrl.plotsVisible);

  if ( verticalView )
    subplot(4,1,1);
  else
    subplot(2,2,1);
  end
  plot(abscissa.time, bias,'.' );
  title( 'Clock Bias vs Time');
  xlabel(abscissa.timeString);
  xlim(abscissa.limits);
  ylabel('milliseconds');
  grid on;

  if ( verticalView )
    subplot(4,1,4);
  else
    subplot(2,2,2);
  end
  plot( abscissa.time ( 2:end ), diffTime, '.');
  title('Diff Time - missing epochs');
  xlabel(abscissa.timeString);
  xlim(abscissa.limits);
  ylabel('seconds');
  grid on;

  if ( verticalView )
    subplot(4,1,2);
  else
    subplot(2,2,3);
  end
  plot ( abscissa.time, unwrappedBias,'.' );
  title ('Unwrapped Bias');
  xlabel(abscissa.timeString);
  xlim(abscissa.limits);
  ylabel('milliseconds');
  grid on;

  if ( verticalView )
    subplot(4,1,3);
  else
    subplot(2,2,4);
  end
  plot( abscissa.time, detrendedBias,'.' );
  title('Detrended Unwrapped Bias');
  xlabel(abscissa.timeString);
  xlim(abscissa.limits);
  ylabel('milliseconds');
  grid on;

  suptitle ('Clock/Time Errors');

  if ( verticalView )
    printPngPlot( 'VertClkerr.png', ctrl.printPlots, verticalView );
  else  
    printPngPlot( 'Clkerr.png', ctrl.printPlots, verticalView );
  end
  
  if ~ctrl.viewPlots
    close;
  end

end

end