
# listTri.py
# Andrew Davison, ad@coe.psu.ac.th, April 2026
'''
Usage: 
> python listTri.py hi.tri 
'''

import sys, os


def loadTriples(f):
  mem = []
  for line in f:
    a, b, c = line.split()
    mem.append(int(a))
    mem.append(int(b))
    mem.append(int(c))
  return mem


def showMemory(mem):
  addr = 0
  print()
  while addr < len(mem):
    comment = ""
    a = mem[addr]
    b = mem[addr+1]
    if b == -1:
      comment += f"; print int mem[{a}]"
    elif b == -2:
      comment += f"; print ascii mem[{a}]"
    elif b == -3:
      comment += f"; print '{chr(a)}'"
    elif b == -4:
      comment += f"; input to mem[{a}]"
    c = mem[addr+2]
    if c == -1:
      comment += "; halt\n#===================\n"
    print(f"{addr:3d}: ({a:3d}, {b:3d}, {c:3d})\t{comment}")
    addr += 3
  print()


# -------------------------------------------

if not sys.argv[1:]:
  print("Usage: python listTri.py <file.tri>")
  sys.exit(1)

fnm = sys.argv[1]
if not fnm.endswith('.tri'):
  print("Error: input file must have a .tri extension")
  sys.exit(1)

if not os.path.isfile(fnm):
  print(f"File '{fnm}' not found.")
  sys.exit(1)

with open(fnm, 'r') as f:
  mem = loadTriples(f)
  showMemory(mem)
