function [linearPositionToCoordsMap, coordsToLinearPositionMap] = formpositioncoordinatemaps( validPositionsLogMat, nValidPositions )
    % Compute the two structures that enable us to convert positions
    % between discrete grid coordinates and linear indices of valid
    % positions.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Using validPositionsLogMat makes this easier to vectorise than in the
    % old version, in which we had to use nested loops.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % CHANGELOG
    % 30.09.2014 - copied from old version.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    if nargin < 1,
        error('You must supply a validPositionsLogMat!')
    end
    if nargin < 2,
        nValidPositions = sum(sum(validPositionsLogMat));
    else
        if nValidPositions ~= sum(sum(validPositionsLogMat)),
            error('nValidPositions does not match the valid positions in validPositionsLogMat!')
        end
    end
    dims = size(validPositionsLogMat);
    yDim = dims(1);
    xDim = dims(2);

    linearPositionToCoordsMap = zeros(nValidPositions, 2);
    [linearPositionToCoordsMap(:, 1), linearPositionToCoordsMap(:, 2)] = find(validPositionsLogMat);
    
    coordsToLinearPositionMap = zeros([yDim, xDim]);
    coordsToLinearPositionMap(validPositionsLogMat) = 1:nValidPositions;
end