import re
from typing import OrderedDict


def read_avg_residuemap(infile):
    """ Read sequence definition from PSN avg file, returning sequence Map

    :param infile: File handle pointing to WORDOM avgpsn output file
    :return: Returns an internal.map.Map object mapping the .pdb
             residues to WORDOM id's from "Seq" section of the avgpsn-file
    """
    m_start = re.compile("^\*\*\* Seq \*\*\*")
    m_end = re.compile("^============")
    m_entry = re.compile("^\s*\d+\s+.:.\d+\s+\d+\.\d+\s*$")
    residuemap = OrderedDict()
    reading = False
    for line in infile:
        if reading:
            # Stop reading if end of interaction strength section
            if m_end.search(line):
                break
            else:
                if m_entry.search(line):
                    [num, resname, normfact] = line.split()
                    residuemap[resname] = int(num)
        # Start reading when header found
        elif m_start.search(line):
            reading = True
    return residuemap