#!/usr/bin/python
#
# JsUnHaXe 0.1.2 // Mindless Labs
#
#
# Changes:
#
# v0.1.2 - fixed output file (write to outdir/basename instead of full path)
#        - fixed state machine (wrote more than needed, resulting in invalid output)
#
# v0.1.1 - output directory can be the directory 
#          containing the js files to process
#

import sys, os

ST_NONE = 0
ST_WRITE = 1

def main():
   
   if len(sys.argv) < 3:
      print "JsUnHaXe v0.1.2"
      print "---------------"
      print "Removes entries of the K-th file already found in earlier files,"
      print "writes modified files into the output directory."
      print
      print " - The first file is not modified or written in the output dir"
      print " - The output dir must exist"
      print
      print "Usage: jsunhaxe.py <output dir> <1.js> <2.js> <...> <N.js>"
      print
      print "Example: jsunhaxe.py out core.js module.js"
      return

   outdir = sys.argv[1]

   files = sys.argv[2:]
   entries = {}
   first = True

   for f in files:
      outlines = []

      state = ST_NONE

      for line in filter(lambda x:x, file(f).readlines()):

         if line[0] in ('\t', ' ', '{', '}'):
            if state == ST_WRITE:
               outlines.append(line)

            if line[0] == '}':
               state = ST_NONE

         else:
            state = ST_NONE
            name = line.strip().split()[0]

            if not entries.has_key(name):
               entries[name] = True
               
               if not first:
                  state = ST_WRITE
                  outlines.append(line)

      if not first:
         of = file(os.path.join(outdir, os.path.basename(f)), "w");
         for l in outlines:
            of.write(l)
         of.close();

      first = False
               
main()

