classdef CircularBuffer < handle
    properties
        buffer          % 2 x N uint32 matrix [timestamps; values]
        capacity        % Maximum number of samples
        writeIndex = 1  % Next write position
        isFull = false  % Buffer full flag
    end
    
    methods
        function obj = CircularBuffer(capacity)
            obj.capacity = capacity;
            obj.buffer = zeros(2, capacity, 'uint32');
        end
        
        function addSample(obj, timestamp, value)
            obj.buffer(1, obj.writeIndex) = timestamp;
            obj.buffer(2, obj.writeIndex) = value;

            obj.writeIndex = obj.writeIndex + 1;
            if obj.writeIndex > obj.capacity
                obj.writeIndex = 1;
                obj.isFull = true;
            end
        end
        
        function data = getBuffer(obj)
            if obj.isFull
                % Return data in chronological order
                data = [ ...
                    obj.buffer(:, obj.writeIndex:end), ...
                    obj.buffer(:, 1:obj.writeIndex-1) ...
                ];
            else
                data = obj.buffer(:, 1:obj.writeIndex-1);
            end
        end
        
        function clear(obj)
            obj.buffer(:) = 0;
            obj.writeIndex = 1;
            obj.isFull = false;
        end
    end
end
