import sys,os,re,tokenize,cgi
tok = tokenize

def maybe_add_exts(file,*exts):
    for ext in ("",)+exts:
        if os.path.exists(file+ext):
            return file+ext
    raise Exception, "%s not found"%file

class Replacer:
    def __init__(self,dict):
        self.dict = dict
    def replace(self,match):
        return self.dict[match.group(1)]

commandline = re.compile("^@("+tok.Name+") *([^ ]*)(.*)")
option = re.compile(' *('+tok.Name+')="([^"]+)" *')    

def proc(file):
    file = maybe_add_exts(file,".in",".html.in")
    outfile = open(os.path.basename(file[:-3]),'w')
    lines = open(file,'r').read().split("\n")
    dir = os.path.dirname(file)
    for l in lines:
        if l and l[0]=="@":
            _,name,args = commandline.match(l).groups()
            d = {}
            for k,v in option.findall(args):
                d[k]=v
            reptext = open(maybe_add_exts(os.path.join(dir,name),".frag")).read()
            if d.has_key("escape"):
                outfile.write(
                    cgi.escape(reptext))
            else:
                outfile.write(
                    re.sub("{{([A-Za-z0-9_]*)}}",
                           Replacer(d).replace,
                           reptext))
        else:
            outfile.write(l+"\n")

def find_frag(name, curdir):
    candidate = os.path.join(curdir, name)
    if os.path.exists(candidate):
        return candidate
    elif curdir == '/':
        raise ValueError, "can't find frag %s"%name[:-5]
    else:
        return find_frag(name, os.path.dirname(curdir))

def proc1(fromfile,tofile,**init):
    lines = open(fromfile,'r').read().split("\n")
    outfile = open(tofile,'w')
    dir = os.path.dirname(fromfile)
    for l in lines:
        if l and l[0]=="@":
            _,name,args = commandline.match(l).groups()
            d = init.copy()
            for k, v in option.findall(args):
                d[k] = v
            if name[0] == '/':
                reptext = open(name).read()
            else:
                reptext = open(find_frag(name+".frag",dir)).read()
            if d.has_key("escape"):
                outfile.write(
                    cgi.escape(reptext))
            else:
                outfile.write(
                    re.sub("{{([A-Za-z0-9_]*)}}",
                           Replacer(d).replace,
                           reptext))
        else:
            outfile.write(l+"\n")

if __name__=="__main__":
    map(proc,sys.argv[1:])
