#!/usr/bin/env python

import re
import os
import string
import fnmatch

MACRO = """
#define %(func_name)s%(macro_args)s ({ \\
   ret_t __ret = %(func_orig)s %(macro_args)s; \\
   if (unlikely (__ret != ret_ok)) return __ret; \\
   __ret; \\
})
"""

def parse_file (fullpath_h, replacement_pair):
	with open(fullpath_h, 'r') as f:
		cont = f.read()

	# Find functions
	funcs = re.findall (r'ret_t\s+?[^\\#]+?\(.+?\);', cont, re.S)

	output = ''
	for func in funcs or []:
		# Remove new-lines and multiple spaces
		func = re.sub(' +',' ', func.replace('\n',' '))

		# Ignore function typedefs
		if re.findall('\(\s*?\*', func):
			continue

		# Parse it
		tmp = (re.findall (r'ret_t (.+?)\s*(\(.+\));', func) or [()])[0]
		if not tmp:
			print func
			raise SystemExit
		func_orig = tmp[0]
		func_name = func_orig.replace(replacement_pair[0], replacement_pair[1])

		# Arguments
		func_args = [x.strip() for x in tmp[1].split(',')]
		func_argn = len(func_args)
		macro_args = '(%s)' %(','.join(string.uppercase[:func_argn]))

		output += MACRO %(locals())

	return output

def parse_dir (path_dir, path_header, replacement_pair):
	header = ''

	# Parse header files
	for root, dirnames, filenames in os.walk(path_dir):
		for filename in fnmatch.filter(filenames, "*.h"):
			fp = os.path.join (root, filename)
			header += parse_file(fp, replacement_pair)

	# Write target header
	with open(path_header, 'w+') as f:
		f.write(header)
	print '%s: DONE' %(path_header)


def main():
	parse_dir ("libchula", "libchula/chulada.h", ('chula_','chuli_'))
	parse_dir ("libhpack", "libhpack/hpack.h", ('hpack_','hp_'))


if __name__ == "__main__":
	main()

@@ -47,22 +47,23 @@
 ort 
-string
+fnmatch
 %0Aimport 
 fnma
@@ -58,23 +58,24 @@
 %0Aimport 
-fnmatch
+argparse
 %0A%0AMACRO 
@@ -873,16 +873,28 @@
 guments%0A
+%09%09args = %5B%5D%0A
 %09%09func_a
@@ -945,33 +945,99 @@
 %0A%09%09f
-unc_argn = len(func_args)
+or arg in func_args:%0A%09%09%09args += %5Bfilter(lambda x: len(x), re.split(' %7C%5C*%7C%5C&%7C%5C)', arg))%5B-1%5D%5D
 %0A%09%09m
@@ -1070,36 +1070,12 @@
 oin(
-string.uppercase%5B:func_
 arg
-n%5D
+s
 ))%0A%0A
@@ -1481,16 +1481,17 @@
 header)%0A
+%0A
 %09print '
@@ -1498,12 +1498,22 @@
 %25s: 
-DONE
+%25s definitions
 ' %25(
@@ -1527,155 +1527,576 @@
 ader
-)%0A%0A%0Adef main():%0A%09parse_dir (%22libchula%22, %22libchula/chulada.h%22, ('
+, header.count('#define'))%0A%0A%0Adef main():%0A%09# Command Line Args%0A%09parser = argparse.ArgumentParser()%0A%09parser.add_argument ('--path',        action=%22store%22, required=True, help=%22%22)%0A%09parser.add_argument ('--output',      action=%22store%22, required=True, help=%22Output header file%22)%0A%09parser.add_argument ('--replacement', action=%22store%22, required=True, help=%22Name replacement. Eg: 
 chula_
-','
+:
 chuli_
-'))%0A%09parse_dir (%22libhpack%22, %22libhpack/hpack.h%22, ('hpack_','hp_
+%22)%0A%09ns = parser.parse_args()%0A%09if not ns:%0A%09%09print (%22ERROR: Couldn't parse parameters%22)%0A%09%09raise SystemExit%0A%0A%09# Parse headers%0A%09parse_dir (ns.path, ns.output, ns.replacement.split(':
 '))%0A%0A
-%0A
 if _

Use more descriptive var names in the macros