def METHOD_NAME(filename, portnames):
    with open(filename, 'r') as ifile:
        magtext = ifile.read().splitlines() 
    labrex = re.compile('<< labels >>')
    in_labs = False
    portidx = 0
    with open(filename, 'w') as ofile:
        for line in magtext:
            lmatch = labrex.match(line)
            if lmatch:
                in_labs = True
                print(line, file=ofile)
            elif in_labs:
                linetok = line.split()
                if linetok[0] == 'port':
                    if portidx > 0:
                        print(linetok[0] + ' ' + str(portidx) + ' ' + linetok[2], file=ofile)
                    else:
                        print(line, file=ofile)
                    portidx = 0
                elif linetok[0] == 'flabel':
                    portlab = linetok[-1]
                    try:
                        portidx = portnames.index(portlab) + 1
                    except:
                        print('Error: Port order list does not contain "' + portlab + '"')
                        portidx = 0
                    print(line, file=ofile)
                else:
                    print(line, file=ofile)
            else:
                print(line, file=ofile)