#!/usr/bin/env python
#
# This script creates a C header file containing the
# OpenCL code from kEMField_kernel.cl
#

import sys, os

# Get input/output filenames
if len(sys.argv) < 3:
	print "Usage:  make_kernel_header.py <input> <output>"
	exit(1)

kernelfile = sys.argv[1]
kernelname = os.path.splitext(os.path.basename(kernelfile))[0]
kernelname_l = kernelname.lower()

headerfile = sys.argv[2]
headername = os.path.splitext(os.path.basename(headerfile))[0]
headername_u = headername.upper()

# Read kernel sourcecode
ifile = open(kernelfile, "r")
kernel = ifile.readlines()
ifile.close()

# Process lines
codebuf = ""
for line in kernel:
	line = line.rstrip()  # remove trailing whitespace
	line = line.replace('"','\\"')  # escape quotes (" -> \")
        line = '"' + line + '\\n"'  # add newline at the end
	codebuf += "\n    " + line

# Create C code
header = """
/**
 * This file was autogenerated by make_kernel_header.py
 * DO NOT EDIT!
 */

#ifndef %(headername_u)s_H
#define %(headername_u)s_H

#include <string>

namespace kemfield {

static const std::string %(kernelname_l)s_source = %(codebuf)s;

}

#endif /* %(headername_u)s */
""" % globals()

# Write header file
ofile = open(headerfile, "w")
ofile.writelines(header)
ofile.close()

# Print message
print "Compiled '%s' into header file '%s' (%d lines)" % (kernelfile, headerfile, len(kernel))
