#!/usr/bin/env python2.7

# Adds a ZZZZ comment with the total score of a graded homework based on the
# ZZZ comments found in that file (e.g. "-- ZZZ -0.5p"). The total score (e.g.,
# 10) from which points are subtracted must be passed as first argument.

import os
import re
import sys

def grade(max_score, file_name):
  print("Grading {0}".format(file_name))

  score = float(max_score)
  see_comments_below = False
  short_comment = ""

  inp = open(file_name)

  for l in inp:
    if "ZZZZ" in l:
      print("File already contains a ZZZZ marker, skipping")
      return
    elif "ZZZ" in l:
      z = re.match(".*ZZZ:?\s-([0-9.]+)(pt?)?.*", l)
      if z:
        score = score - float(z.groups()[0])
      see_comments_below = True

  inp.close()

  if max_score - score <= 1:
    short_comment = " -- well done!"

  inp = open(file_name)
  out = open(file_name + ".out", "w")

  out.write("-- ZZZZ {0}p{1}\n".format(score, short_comment))
  if see_comments_below:
    out.write("-- ZZZ: See comments below\n")
  for l in inp:
    out.write(l)

  inp.close()
  inp.close()
  os.rename(file_name + ".out", file_name)

if __name__ == "__main__":
  if len(sys.argv) <= 1:
    print("Please provide the maximum number of points")
  else:
    max_score = 0
    try:
      max_score = int(sys.argv[1])
    except:
      print("Please provide the maximum number of points as an integer")
      exit(1)
    for file_name in sys.argv[2:]:
        grade(max_score, file_name)
