def distance_index(i, j, length):
    """Helper function to calculate the distance between two indices in a
    circular HMM.

    Args:
        i (int): first index
        j (int): second index
        length (int): length of the HMM

    Returns:
        int: The distance between the indices ``i`` and ``j``: As the HMM
        is circular ``j`` may have a smaller value than ``i``, even though
        ``j`` is ahead of ``i``.

    .. todo:: May be replaced by a simple mod, as distance_index is used only
        once in the code at current.

    """
    if j > i:
        return j - i
    else:
        return length + j - i
