import re


def ref2equations(filestr):
    """
    Replace references to equations. Unless "Equation(s)" already
    precedes the reference, the following transformations are done:

    (ref{my:label}) -> Equation (my:label)
    (ref{my:label1})-(ref{my:label2}) -> Equations (my:label1)-(my:label2)
    (ref{my:label1}) and (ref{my:label2}) -> Equations (my:label1) and (my:label2)
    (ref{my:label1}), (ref{my:label2}) and (ref{my:label3}) -> Equations (my:label1), (my:label2) and (ref{my:label2})

    """
    # "Store away" references that are prefixed by Equation/Eq.
    filestr = re.sub(r'(Equations?|Eqs?\.)([ ~]) *(\(ref\{)',
                     r'XXX___\g<1>\g<2>___XXX',  # coding of the prefix
                     filestr)
    filestr = re.sub(r'\(ref\{(.+?)\}\)-\(ref\{(.+?)\}\)',
                     r'Equations (\g<1>)-(\g<2>)', filestr)
    filestr = re.sub(r'\(ref\{(.+?)\}\)\s+and\s+\(ref\{(.+?)\}\)',
                     r'Equations (\g<1>) and (\g<2>)', filestr)
    filestr = re.sub(r'\(ref\{(.+?)\}\),\s*\(ref\{(.+?)\}\)(,?)\s+and\s+\(ref\{(.+?)\}\)',
                     r'Equations (\g<1>), (\g<2>)\g<3> and (\g<4>)', filestr)
    filestr = re.sub(r'\(ref\{(.+?)\}\)',
                     r'Equation (\g<1>)', filestr)

    # Restore Equation/Eq. prefix
    filestr = re.sub(r'XXX___(.+?)___XXX', r'\g<1>(ref{', filestr)
    return filestr