···11+import os
22+import sys
33+import time
44+import fileinput
55+import threading
66+from collections import deque
77+88+from intcode import emulate
99+1010+1111+TAPE = [int(x) for x in fileinput.input()[0].split(',')]
1212+TAPE += [0] * 1000
1313+1414+VMS = 50
1515+PACKET_QUEUES = [deque([i]) for i in range(VMS)]
1616+NAT = [None, None]
1717+1818+1919+def start_nic(pid):
2020+ vm = emulate(TAPE, PACKET_QUEUES[pid], consume_input=True)
2121+2222+ while True:
2323+ addr = next(vm)
2424+ x = next(vm)
2525+ y = next(vm)
2626+2727+ if addr == 255:
2828+ NAT[0] = x
2929+ NAT[1] = y
3030+ else:
3131+ PACKET_QUEUES[addr].extend([x, y])
3232+3333+3434+def start_nat():
3535+ first_nat = False
3636+ seen = set()
3737+3838+ while True:
3939+ if NAT[1] is not None:
4040+ if not first_nat:
4141+ print "First Y value sent to NAT:", NAT[1]
4242+ first_nat = True
4343+4444+ if not any(PACKET_QUEUES):
4545+ x, y = NAT
4646+ if y in seen:
4747+ print "Value delivered by NAT twice in a row:", y
4848+ os._exit(1)
4949+ seen.add(y)
5050+5151+ PACKET_QUEUES[0].extend(NAT)
5252+ NAT[0] = None
5353+ NAT[1] = None
5454+5555+ time.sleep(1)
5656+5757+5858+threads = []
5959+6060+sys.stdout.write("Starting NICs and NAT")
6161+for pid in range(VMS):
6262+ t = threading.Thread(target=start_nic, args=(pid,))
6363+ threads.append(t)
6464+ t.start()
6565+ sys.stdout.write(".")
6666+ sys.stdout.flush()
6767+6868+t = threading.Thread(target=start_nat)
6969+threads.append(t)
7070+t.start()
7171+sys.stdout.write("!\n")
7272+7373+for t in threads:
7474+ t.join()