// Glue code for CW4
//===================
// generates j-files and runs class-files
//
//
// needs 
//
//  tokenise(s: String) : List[Token]
//
//  Stmts - parser consuming Tokens
//
//  compile(bl: Block, class_name: String) : String



import ammonite.ops._

def parse_tks(tks : List[Token]) = {
  Stmts.parse_all(tks).head
}
   


def compile_to_file(bl: Block, class_name: String) : Unit = {
  println(s"Start of compilation")
  write.over(pwd / s"$class_name.j", compile(bl, class_name))  
  println(s"generated $class_name.j file")
  os.proc("java", "-jar", "jasmin.jar", s"$class_name.j").call()
  println(s"generated $class_name.class file ")
}


@main
def main(fname: String) = {
    val path = os.pwd / fname
    val class_name = fname.stripSuffix("." ++ path.ext)
    val tks = tokenise(os.read(path))
    val ast = parse_tks(tks)
    compile_to_file(ast, class_name)
}

@main
def run(fname: String) = {
    val path = os.pwd / fname
    val class_name = fname.stripSuffix("." ++ path.ext)
    val tks = tokenise(os.read(path))
    val ast = parse_tks(tks)
    compile_to_file(ast, class_name)
    os.proc("java", s"${class_name}/${class_name}").call(stdout = os.Inherit, stdin = os.Inherit)
    println(s"done.")
}


