#!/usr/bin/python
import os
import sys
import re

funclist = [];

def visit(arg, dirname, names):
    out = open(sys.argv[2],'a')
    for name in names:
        (root, ext) = os.path.splitext(name)
        if ext == '.cpp':
            fullpath = os.path.join(dirname,name)
            f = open(fullpath,'r')
            line = ' '
            while line != '':
                line = f.readline()
                if (line.startswith("JitScalarFunc")):
                    function_name = re.search("\((.*),",line).group(1)
                    funclist.append(function_name);
                    arg_count = int(line[13])
                    out.write('  double _jit_%s('%(function_name))
                    if (arg_count > 0):
                        out.write('double a0')
                        for i in range(arg_count-1):
                            out.write(',double a%d'%(i+1))
                    out.write(');\n');
            f.close()
    out.close()

f = open(sys.argv[2],'w')
f.write("#ifndef __CScalarFuncs_hpp__\n");
f.write("#define __CScalarFuncs_hpp__\n");
f.write("// WARNING - this file is automatically generated by\n");
f.write("// the jitgen.py script in tools.  Do not\n");
f.write("// edit it by hand, or changes will be lost!  If you\n");
f.write("// need to add a JIT scalar function to FreeMat, add a\n");
f.write("// JitScalarFunc documentation tag to the code.\n");
f.write("// \n\n// Here, each function gets prototyped.\n");
f.close()

os.path.walk(sys.argv[1], visit, '')

f = open(sys.argv[2],'a')
f.write("static const char* jit_scalar_list[] = {");
for nam in funclist:
    f.write("\"%s\","%(nam))
f.write("\"\"};\n");
f.write("static const int jit_scalar_list_len = sizeof(jit_scalar_list)/sizeof(jit_scalar_list[0]);\n");
f.write("#endif\n");
f.close();

#dirname = sys.argv[1]
#names = os.listdir(dirname)
#gfuncs = [];
#classdefs = [];

#if (len(gfuncs) > 0):
#    writeloader(sys.argv[1],gfuncs,sys.argv[2])
