function i = rok_room_xy_to_cell (room, x, y)
    % i = ROK_ROOM_XY_TO_CELL (room, x, y)
    %
    % Convert cell coordinates into cell indices.
    %
    % Input:
    %  - room = room configuration structure, obtained by ROK_ROOM_CREATE()
    %  - x = 1xN array of x coordinates (or 2xN array of x and y
    %    coordinates, if y array is not provided)
    %  - y = 1xN array of y coordinates
    %
    % Output:
    %  - i = 1xN array of corresponding cell indices
    %
    % See also: ROK_ROOM_CELL_TO_XY, ROK_ROOM_CREATE
    %
    % Copyright (C) 2011-2012, Rok Mandeljc <rok.mandeljc@fe.uni-lj.si>
    
    if nargin < 3,
        y = x(2, :);
        x = x(1, :);
    end
    
    % Move to room coordinate system
    x = x - room.area(1);
    y = y - room.area(2);
    
    x = x - room.cell_size(1)/2;
    y = y - room.cell_size(2)/2;
    
    % Round to cell center
    x = round( x / room.cell_stride(1) ) + 1;
    y = round( y / room.cell_stride(2) ) + 1;
    
    % Allocate output
    i = -1 * ones(size(x));
    
    % Find valid points
    % FIXME: points on the outer border fall out
    invalid = isinf(x) | isinf(y) | isnan(x) | isnan(y) | x < 1 | y < 1 | x > room.nx | y > room.ny;
    valid = ~invalid;
    
    % Convert valid locations to indices
    i(valid) = sub2ind([ room.nx, room.ny ], x(valid), y(valid));
end