import sys
import os

dst = sys.argv[1]

sources = [
( "basics",      ("sprites256", "palettes", "rotate", "collision", "scroll")),
( "audio",       ("toccata", "player", "sample", "instruments2")),
( "advanced",    ("interrupt", "splitscreen", "jkcollision", "bitmap", "wireframe", "snow", "assets")),
( "demo",        ("ball", "chessboard", "asteroids")),
( "tools",       ("selftest", "screenshot", "memloader", "joytest"))]

if len(sys.argv) == 3:
    if sys.argv[2] == "-m":
        sources += [("manufacture", (
                          "load0", "load1", "load2", "load3", "load4",
                          "asset0", "asset1", "asset2", 
                          # "manufacture"
                          # "clone",
                          # "serial0", "serial1", "serial2", "serial3"
                          ))]

for i,(dir,inos) in enumerate(sources, 1):
    dirname = os.path.join(dst, "%d.%s" % (i, dir.capitalize()))
    print "mkdir %s" % dirname
    os.mkdir(dirname)
    for ino in inos:
        file = "%s.ino" % ino
        assert os.access(file, os.R_OK), file + " not exist"
        print "mkdir", os.path.join(dirname, ino)
        os.mkdir(os.path.join(dirname, ino))
        oino = open(os.path.join(dirname, ino, file), "w")
        for l in open(file):
            if not ("JCB" in l):
                oino.write(l)
            if '#include "' in l:
                includename = l.split('"')[1]
                assert includename != "debug.h", "Remove debug.h from %s" % file
                os.system("cp %s %s" % (includename, os.path.join(dirname, ino)))
        oino.close()
        home = os.getcwd()
        os.chdir(os.path.join(dirname, ino))
        if 0:
            rc = os.system("%s/arduino-cc %s" % (home, ino))
            assert rc == 0
        os.chdir(home)
