from warnings import warn


def find_torder(dic, shape):
    """
    Find the torder from the procpar dictionary.

    If propar dictionary is incomplete a UserWarning is issued and 'r' is
    returned.

    Parameters
    ----------
    dic : dict
        Dictionary of parameters in the procpar file.
    shaoe : tuple of ints
        Shape of NMR data.

    Returns
    --------
    torder : {'r', 'f', 'o'}
        File ording for using in :py:func:`read` or :py:func:`write`.

    """
    ndim = len(shape)

    # 1 and 2D files are flat
    if ndim < 3:
        return 'f'  # flat

    if "array" not in dic:
        warn("no array in dictionary, torder set to 'r'")
        return 'r'

    # extract the array list
    al = dic['array']['values'][0].split(',')

    # remove one dimension if non-phase parameter is present in array list
    if False in [s.startswith('phase') for s in al]:
        ndim = ndim - 1
        if ndim < 3:
            return 'f'  # flat

    if ndim == 3:
        if "phase" in al and "phase2" in al:
            if al.index("phase") > al.index("phase2"):
                return 'r'  # regular
            else:
                return 'o'  # opposite
        else:
            warn("missing phase order, torder set to 'r'")
            return 'r'

    if ndim == 4:
        if "phase" in al and "phase2" in al and "phase3" in al:
            if al.index("phase") > al.index("phase2") > al.index("phase3"):
                return 'r'  # regular
            if al.index("phase") < al.index("phase2") < al.index("phase3"):
                return 'o'  # opposite
            else:
                warn("bad phase order, torder set to 'r'")
                return 'r'
        else:
            warn("missing phase order, torder set to 'r'")
            return 'r'

    warn("No trace ordering for" + str(ndim) +
         "dimensional data, torder set to 'r'")
    return 'r'