function addTs(h,ts,varargin)

%% If necessary build the xyplot
if isempty(h.Plot)
    viewpanel = tsguis.uitspanel(h.Figure,'Time series xyplot');
    h.Plot = tsguis.xyplot(viewpanel,1,1);
    h.Plot.Parent = h; %  Install parent
    
    % Enable drag and drop after creating the property editor. The
    % property editor must be created first because otherwize the
    % plottools will overwrite the AxisCanval drop adaptor.
    propedit(h.Plot.AxesGrid.Parent);
    h.setDropAdaptor(h.DropAdaptor);
    
    % Drop out of plotedit mode. This must be done here or when the 
    % axes are copied by the resize method the callbacks will be in the 
    % wrong state.
    plotedit(h.Figure,'off')
    
    % Hack to refresh the figure window so that the Property Editor will
    % not appear overlapping the axes
    jf = get(h.Figure,'javaframe');
    mdi = javax.swing.SwingUtilities.getWindowAncestor(jf.getAxisComponent);
    s = mdi.getSize;
    s.width = s.getWidth+1;
    mdi.setSize(s);
end

%% If the 3rd arg is not either X oy Y act as if it were not specified
if nargin>=3 && (~ischar(varargin{1}) || ~any(strcmpi(varargin{1},{'x','y'})))
    nargin==2;
end
    

%% Add the new time series
%% Case 1: Less than 2 time series added
if (isempty(h.Timeseries1) && isempty(h.Timeseries2)) || (nargin>=3 && ...
        strcmpi(varargin{1},'x') && isempty(h.Timeseries2)) || (nargin>=3 && ...
        strcmpi(varargin{1},'y') && isempty(h.Timeseries1))
    if nargin>=3 && strcmpi(varargin{1},'y')
        h.Timeseries2 = ts;
    else
        h.Timeseries1 = ts;
    end
    % Update status text
    set(h.Handles.InitTXT,'String',sprintf('Time Series object ''%s'' is now loaded.  Please add another one.',ts.Name))
%% Case 2: Two timeseries already there - ask which one to replace
elseif nargin<=2 && (~isempty(h.Timeseries1) && ~isempty(h.Timeseries2))
   ButtonName = questdlg('Replace which time series?', ...
                       'Time Series Tools', ...
                       ['' h.Timeseries1.Name '' ' '],['' h.Timeseries2.Name '' '  '],'Cancel','Cancel');
   switch ButtonName,
     case ['' h.Timeseries1.Name '' ' '], 
          h.Timeseries1 = ts;
     case ['' h.Timeseries2.Name '' '  '],
          h.Timeseries2 = ts;
     case 'Cancel',
          return
   end 
   h.Plot.addTs(h.Timeseries1,h.Timeseries2);
%% Case 3: Put the time series in the missing spot and show
else
   if nargin<=2 
       if isempty(h.Timeseries1)
           h.Timeseries1 = ts;
       else
           h.Timeseries2 = ts;
       end
   else
       if strcmpi(varargin{1},'x')
           h.Timeseries1 = ts;
       else
           h.Timeseries2 = ts;
       end
   end
   % Hide status text
   set(h.Handles.InitTXT,'Visible','off')
   h.Plot.addTs(h.Timeseries1,h.Timeseries2);
end

%% Fire tschanged event to announce the change
h.send('tschanged',handle.EventData(h,'tschange'));

%% Refresh
if ~isempty(h.Plot)
    h.Plot.Visible = 'on';
end
    

