classdef UbisenseDatabase < handle
    % UBISENSEDATABASE Ubisense Database class
    %  self = UBISENSEDATABASE (config)
    %
    %  Input:
    %   - config = Ubisense configuration INI file or an already-parsed 
    %     config structure, as produced by ROK_PARSE_CONFIG_INI().
    %     The structure must contain the following fields:
    %      - config.data_file = Ubisense data file
    %      - config.timestamp_config = timestamps configuration file name
    %      - config.people = cell array containing people's names
    %      - config.tags = cell array containing tag IDs
    %
    %  Output:
    %   - self = @UbisenseDatabase instance
    %
    % (C) 2011-12, Rok Mandeljc <rok.mandeljc@fe.uni-lj.si>
    
    properties (SetAccess = private, GetAccess = private)
        data;
    end
    
    properties (SetAccess = private, GetAccess = public)
        timestamp;
        people = {};
        tags = {};
    end
    
    methods
        % Constructor
        function self = UbisenseDatabase (config)
            %% Parse the config INI
            if ischar(config),
                config = rok_parse_config_ini(config);
            end
            
            %% Assign people and tags
            self.people = config.people;
            self.tags = config.tags;
            
            %% *** Load Ubisense data ***
            dataFile = rok_path_find_file(config.data_file, config.source_ini_filename);
            fid = fopen(dataFile, 'r', 'l');
            
            % A nifty record parser found on internet
            recordType = { 'double', 'int32', 'int32', 'double', 'double', 'double', 'double', 'double' };
            recordLen = [ 8 4 4 8 8 8 8 8 ];
            recordName = { 'timestamp', 'tag', 'timeslot', 'x', 'y', 'z', 'gdop', 'error' };
            
            for i = 1:numel(recordType),
                % Seek to the first field in the record
                fseek(fid, sum(recordLen(1:i-1)), 'bof');
                
                % Read the record
                self.data.(recordName{i}) = fread(fid, Inf, recordType{i}, sum(recordLen)-recordLen(i)); 
            end
                        
            fclose(fid);
                        
            %% Load timestamps
            timestampConfig = rok_path_find_file(config.timestamp_config, config.source_ini_filename);
            self.timestamp = TimestampDatabase(timestampConfig);
        end
    end
end