function addevent(ts,e)
%ADDEVENT  Add events to a time series object
%   ADDEVENT(TS,E) adds the events object E to the time series object TS. 
%   When an event with the same name and time is already attached to the 
%   time series object, the EventData property of the pre-existing event is
%   modified to reflect that of the new event object. Create the event 
%   object E with the method EVENT. 
%
%   Example
%
%   Create a time series object:
%   ts=tsdata.timeseries(rand(5))
%
%   Create an event object called 'test' where the event occurs at time 3:
%   e=tsdata.event('test',3)
%
%   View the properties (EventData, Name, Time, and Parent) of the event 
%   object: 
%   get(e)
%
%   Add the event object to the time series object TS:
%   ts.addevent(e)
%
%   See also TSDATA.TIMESERIES/TIMESERIES

%   Author(s): James G. Owen
%   Copyright 1986-2003 The MathWorks, Inc. 
%   $Revision: 1.1.6.1 $  $Date: 2004/12/26 21:34:53 $

% Check that the event is a valid singleton
if isempty(e) % Ignore empty events
    return
end
if ~isa(e,'tsdata.event')
    error('timeseries:addevent:badtype',...
        'Only event objects can be added')
end
   
% Add events one at a time
eventadded = false;
for k=1:length(e)
    eventadded = localAddEvent(ts,e(k));
end

% If an event has been added fire a datachange
if eventadded
    ts.send('datachange')
end

function eventadded = localAddEvent(ts,e)
% Adds events one at a time
% Check for duplication
eventadded = false;
if ~isempty(ts.Events)
    I = strcmp(e.Name,get(ts.Events,{'Name'})) & ...
        abs(e.Time-cell2mat(get(ts.Events,{'time'})))<eps;  
    if ~any(I)
        set(e,'Parent',ts);
        ts.events = [ts.events, e];
        eventadded = true;
    end
else
    set(e,'Parent',ts);
    ts.events = e;
    eventadded = true;
end

