function [data,Ts,varargout] = tsToRegular(src)

%% Resamples a time series on a unform time vector with the same start and
%% end times and the same number of observations. Also removes NaNs. Used
%% by periodogram to obtain a power spec

%% If there are two time series they must be sampled at the same times
twotimeseries = false;
if ~isempty(src.Timeseries2) && src.Timeseries2~=src.Timeseries
    if ~isequal(src.Timeseries2.Time,src.Timeseries.Time)
        error('xx')
    else
        twotimeseries = true;
    end
end

%% Deal with scalars
if src.TimeSeries.TimeInfo.Length==1
    data = src.TimeSeries.Data;
    Ts = 1;
    return
end

%% Deal with non-scalars
Ts = src.TimeSeries.TimeInfo.Increment;
if isnan(Ts) % Non uniform time series - resample to uniform
    [data, Ts] = localInterpolate(src.TimeSeries);
    if twotimeseries
       varargout{1} = localInterpolate(src.TimeSeries2);
    end
else % Uniform time series - if necessary resample to uniform
    data = src.Timeseries.Data;
    if any(any(isnan(data)))
        [data, Ts] = localInterpolate(src.TimeSeries);
    end
    if twotimeseries
        data2 = src.Timeseries2.Data;
        if any(any(isnan(data2)))
            data2 = localInterpolate(src.TimeSeries2);
        end
        varargout{1} = data2;
    end
end         
                
function [data, Ts] = localInterpolate(ts)

%% Interpolate the time series on a uniform time vector to remove any NaNs
%% TO DO: Deal with NaNs at the beginning and end
time = ts.Time;
tuniform = time(1):min(diff(time)):time(end);

%% Note: Do not use resample to perform the interpolation since this
%% function may be recalled using transactions which cannot reverse time
%% series construction
data = ts.dataInfo.Interpolation.interpolate(...
    time,ts.data,tuniform(:));
Ts = tuniform(2)-tuniform(1);

