
# mbFormat.py
# Andrew Davison, ad@coe.psu.ac.th, April 2026

'''
Minimal BASIC BNF

  program   ::= { [label] statement }
  statement ::= 'P' (var | '!')
              | 'I' var
              | var expr
              | 'J' atom label

  expr      ::= atom [ op atom ]     
  atom      ::= var | int
  op        ::= '+' | '-' | '*' | '/' | '&' | '|'
                | '=' | '!'  | '<' | '>' 

  var       ::= a-z
  label     ::= A-Z (excluding P, J, I)
  int       ::= (0-9)+

The call to mbFormat.py
  python mbFormat.py "Ina1i1Abi>nJbEaa*iii+1J1AEPa"
uses the BNF given above to reformat the string and print

  I n
  a 1
  i 1
A b i>n
  J b E
  a a*i
  i i+1
  J 1 A
E P a
'''

import sys

if len(sys.argv) != 2:
  print('usage: python mbFormat.py "<string>"')
  sys.exit(1)

code = sys.argv[1]
i = 0
while i < len(code):
  line = ""

  # 1. Label (A-Z excluding P, J, I)
  if code[i].isupper() and (code[i] not in "PJI"):
    line += code[i] + " "
    i += 1
  else:
    line += "  " # Indentation for lines without labels

  if i >= len(code):
    break

  ch = code[i]
  # 2. 'P' (Print)
  if ch == 'P':
    i += 1
    arg = code[i]
    '''
    if arg == '"': # Handle string literal
      start = i
      i += 1
      while i < len(code) and code[i] != '"':
        i += 1
      i += 1 # close quote
      line += "P " + code[start:i]
    else:
    '''
    line += "P " + arg
    i += 1

  # 3. 'I' (Input)
  elif ch == 'I':
    line += "I " + code[i+1]
    i += 2

  # 4. 'J' (Jump)
  elif ch == 'J':
    # Format: J [atom] [label]
    cond = code[i+1]
    target = code[i+2]
    line += f"J {cond} {target}"
    i += 3

  # 5. Assignment (var expr)
  elif ch.islower():
    var = ch
    i += 1
    expr = ""
    # Consume the expression (atom [op atom])
    # First atom
    expr += code[i]
    i += 1
    # Optional op + atom
    if i < len(code) and (code[i] in "+-*/&|=!<>"):
      expr += code[i] # op
      expr += code[i+1] # atom
      i += 2
    line += f"{var} {expr}"
  else:
    print(f"Unknown character: {ch}")

  print(line)