function [ logYPosPosteriors, logXPosPosteriors ] = marginalisepositionlogposteriors( logPosLinearIndPost, PositionData )
    % Supplied with a matrix of the posteriors (filtered or smoothed) over
    % linearised positions, return the corresponding marginalised
    % posteriors over X and Y dimensions of discrete coordinates.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % logPosLinearIndPost - in general, a T by K by 2 matrix, where T is
    % the maximum number of discrete time bins (of any stream) and K is the
    % number of valid linearised positions.
    %
    % PositionData - struct with the following fields:
    % - discreteYDim
    % - discreteXDim
    % - discreteCoordsToPositionIndMap
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % CHANGELOG
    % 19.11.2014 - copied from old version.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    if nargin < 2,
        error('Insufficient arguments!')
    end
%     if length(size(logPosLinearIndPost)) ~= 3,
%         error('logPosLinearIndPost should be a 3-D matrix!')
%     end
    if any(any(any(logPosLinearIndPost > 0))),
        error('logPosLinearIndPost should be a matrix of log probabilities!')
    end
    if ~isfield(PositionData, 'discreteCoordsToPositionIndMap'),
        error('discreteCoordsToPositionIndMap must be a field of PositionData!')
    end
    if ~isfield(PositionData, 'discreteYDim'),
        error('discreteYDim must be a field of PositionData!')
    end
    if ~isfield(PositionData, 'discreteXDim'),
        error('discreteXDim must be a field of PositionData!')
    end
    
    nTimeBins = size(logPosLinearIndPost, 1);
    
%     % Multiply dimensions to get probabilitiy on each linearised position.
%     logPosLinearIndPost = sum(logPosLinearIndPost, 3);

    logYPosPosteriors = -inf([nTimeBins, PositionData.discreteYDim]);    
    logXPosPosteriors = -inf([nTimeBins, PositionData.discreteXDim]);

    for yCoord = 1:PositionData.discreteYDim,
        linearPosInds = PositionData.discreteCoordsToPositionIndMap(yCoord, PositionData.discreteCoordsToPositionIndMap(yCoord, :) > 0);
        % Will be empty if there is no linearised position in row yCoord.
        if ~isempty(linearPosInds),
            logYPosPosteriors(:, yCoord) = sumlogprobmat(logPosLinearIndPost(:, linearPosInds), 2);
        end
    end

    for xCoord = 1:PositionData.discreteXDim,
        linearPosInds = PositionData.discreteCoordsToPositionIndMap(PositionData.discreteCoordsToPositionIndMap(:, xCoord) > 0, xCoord);
        % Will be empty if there is no linearised position in col xCoord.
        if ~isempty(linearPosInds),
            logXPosPosteriors(:, xCoord) = sumlogprobmat(logPosLinearIndPost(:, linearPosInds), 2);
        end
    end
end