#!/usr/bin/python

# Author: Peter Schwabe
# Date: 2009-03-19
# Public domain

import os
import sys
import re
from consts import *

def expandfile(fh):
    mstr = "@[^\ \(\\\\]*"
    mexpr = re.compile(mstr)
    for line in fh.readlines():
        line = re.sub(";(?![\ \t]*\\\\)",semstr, line)
        exp = mexpr.search(line)
        if exp:
            if not exp.group() in supported:
                sys.stderr.write("Error: Preprocessor directive "+exp.group()+" unsupported\n")
                sys.exit(1)
        if re.match("@include", line):
            path = re.sub("@include", "", line)
            path = re.sub("[\"\ \t\n]", "", path)
            path = os.path.realpath(path)
            if path in files:
                sys.stderr.write("Error: circular includes")
                sys.exit(1)
            if not os.access(path ,os.R_OK):
                sys.stderr.write("The file "+path+", included from "+fh.name+" is not existent or not readable\n")
                sys.exit(1)
            else:
                files.append(path)
                ifh = open(path, 'r')
                expandfile(ifh)
        else:
            print line,


files = []

if len(sys.argv) < 2:
    sys.stderr.write("Error: No input file given\n")
    sys.exit(1)

if len(sys.argv) >2:
    sys.stderr.write("Error: More than one input file\n")
    sys.exit(1)

if not os.access(sys.argv[1] ,os.R_OK):
    sys.stderr.write("The file "+sys.argv[1]+" is not existent or not readable\n")
    sys.exit(1)

path = os.path.realpath(sys.argv[1])
files.append(path)
fh = open(path, 'r')
expandfile(fh)



