% computeTimeScale.m
% 
% Construct a scale factor to scale time based on the length and
% duration of the data set. For example use second, minutes, or 
% hours based on the length of the data set. 
% 
% Divide the time array by timeScale and label the time axis using
% timeString. 
% 

function [abscissa, statistics] = computeTimeScale( posData, key )

% Set up constants. 
time = posData(:,key.TIME);
startTime = time(1);
endTime = time(end);
% Save away unmodified start and end times for statistics
statsStartTime = startTime;
statsEndTime = endTime; 

%% Fill in statistics before further processing 
if isfield( key, 'WEEK' )
  weekNum = posData(:,key.WEEK);
else
  weekNum = 0; 
end

% Handle week rollover
if ( endTime < startTime )
  time = time - 302400;
  time  = myunwrap(time,302400.0);
  time = time - 302400;
end

% Adjust time scale to start at time 0.
time = time - time(1);
startTime = time(1);
endTime = time(end);

% Duration is in seconds
duration = endTime - startTime; 

if ( duration < 900 )
  % use seconds upto 15 minutes
  timeScale = 1; 
  timeString = 'seconds';
elseif ( duration < 60*300 )
  % use minutes upto 300 minutes ( 5 hours )
  timeScale = 60;
  timeString = 'minutes';
else
  % use hours for durations greater than 5 hours
  timeScale = 3600;
  timeString = 'hours';
end


% generate time scale
abscissa.time = time/timeScale;
abscissa.timeScale = timeScale; 
abscissa.timeString = timeString; 
abscissa.limits = [abscissa.time(1), abscissa.time(end)];
abscissa.startTime = startTime; 
abscissa.endTime = endTime; 

% generate statistics
statistics.startWeekNum = weekNum(1);
statistics.startTime = statsStartTime; 
statistics.endWeekNum = weekNum(end);
statistics.endTime = statsEndTime;

end
