function [ event, tdelta ] = get_event_by_timestamp (self, tag, timestamp, direction)
    % event = GET_EVENT_BY_TIMESTAMP (self, tag, timestamp, direction)
    %
    % Retrieves event for tag at the time specified by timestamp
    %
    % Input:
    %  - self = @UbisenseDatabase instance
    %  - tag = tag ID, either in integer or in string form
    %  - timestamp = timestamp (Unix epoch)
    %  - direction = specifies the direction in which to search for the
    %    event, relative to the specified time instant:
    %    - 'next' = next event
    %    - 'prev' = previous event
    %    - 'closest' = choose the closest event from next and previous
    %      events
    %
    % Output:
    %  - event = event for the specified tag at specified time instant
    %  - tdelta = deviation from the specified timestamp
    %
    % Copyright (C) 2011-2012, Rok Mandeljc <rok.mandeljc@fe.uni-lj.si>
    
    % Default parameter for direction is 'prev' (zero-hold behavior)
    if nargin < 4,
        direction = 'prev';
    end

    % Convert tag string to tag int
    if isa(tag, 'char'),
        tag = self.get_tag_id_from_string(tag);
    end
    
    
    % Get events
    event_idx = [];
    
    if isequal(direction, 'prev') || isequal(direction, 'closest'),
        idx = find(self.data.tag == tag & self.data.timestamp <= timestamp, 1, 'last');
        
        % Verify and append to list of valid events
        if ~isempty(idx) && self.data.x(idx) ~= 0 && self.data.y(idx) ~= 0 && self.data.z(idx) ~= 0,
            event_idx = [ event_idx, idx ];
        end
    end
    
    if isequal(direction, 'next') || isequal(direction, 'closest'),
        idx = find(self.data.tag == tag & self.data.timestamp >= timestamp, 1, 'first');
        
        % Verify and append to list of valid events
        if ~isempty(idx) && self.data.x(idx) ~= 0 && self.data.y(idx) ~= 0 && self.data.z(idx) ~= 0,
            event_idx = [ event_idx, idx ];
        end
    end
    
    
    % No valid event?
    if isempty(event_idx),
        % No valid event found
        event = [];
        
        tdelta = NaN;
        
        return;
    end
    
    % Find event with minimal distance (or the only valid one)
    
    % Find the one with minimal distance (... or the only valid one)
    [ ~, i ] = min( abs( self.data.timestamp(event_idx) - timestamp) );
    event_idx = event_idx(i);
    
    % Copy the event
    fields = fieldnames(self.data);
    for f = 1:numel(fields),
        event.(fields{f}) = self.data.(fields{f})(event_idx);
    end
    
    tdelta = event.timestamp - timestamp;
end
