#!/usr/local/bin/python

# todo:
#  -- catch cyclic behavior
#  -- sort options in tree.php

from os import listdir, remove
from string import find, lower

err = 0

# open data file
dat = open("data.dat").readlines()

# parse data file into tree
print "Parsing Data into Tree..."
page = []
# page[0] = keyword
# page[1] = list of story [ [p1l1, p1l2 ...], [p2l1, p2l2 ...]  ...]
# page[2] = list of places [ [key1, l1, l2 ...], [key2, l1, l2 ...] ...]
mode = "none"
tree = []
linnum = 0
for i in dat:
    linnum = linnum + 1
    line = i[:-1]
    if len(line) > 0 and line[0] == "[":
        if page != []:
            tree.append(page)
        page = [ lower(line[1:-1]), [], [] ]
        page[0] = line[1:-1]
        mode = "newtext"
    elif len(line) > 0 and line[0] == "*":
        page[2].append([])
        p1 = find(line, "[")
        p2 = find(line, "]")
        if p1 < 0 or p2 < 0:
            print "!! Malformed destination module, line "+str(linnum)
            err = 1
        page[2][-1].append(line[p1+1:p2])
        page[2][-1].append(line[p2+2:])
        mode = "choice"
    elif mode == "text":
        if line == "":
            mode = "newtext"
        else:
            page[1][-1].append(line)
    elif mode == "choice":
        if line == "":
            mode = "newtext"
        else:
            page[2][-1].append(line)
    elif mode == "newtext":
        if line != "":
            page[1].append([line])
            mode = "text"

# check tree
print "Checking tree for validity..."
treekey = 0
index = 0
if err == 0:
    for i in tree:
        key = i[0]
        for j in key:
            if find("0123456789abcdefghijklmnopqrstuvwxyz", j) < 0:
                print "!! Bad Characters in Module Name ["+key+"]"
                err = 1
		break

        for k in i[2]:
	    key2 = k[0]
	    for j in key2:
                if find("0123456789abcdefghijklmnopqrstuvwxyz", j) < 0:
                    print "!! Malformed Module Dest ["+key2\
                        +"] in Module ["+key+"]"
                    err = 1
		    break
        if key == "index":
            index = 1
        if key == "tree":
            treekey = 1

        cnt = 0
        for j in tree:
            if key == j[0]:
                cnt = cnt + 1
        if cnt > 1:
            print "!! Duplicate Module ["+key+"]"
	    err = 1

    if treekey == 1:
        print "!! [tree] module must be renamed"
        err = 1
    if index == 0:
        print "!! No [index] module found"
        err = 1

# check safety
if err == 0:
    foo = open("../safety.txt").readlines()
    if foo != ['csh\n']:
	print "!! Safety non-existent!"
	err = 1

# remove all *.php files
if err == 0:
    print "Removing old php files..."
    foo = listdir("../")
    for i in foo:
        if len(i) > 4 and i[-5:] == ".php":
	    remove("../"+i)

# add php files
if err == 0:
    print "Creating new php files..."
    hdr = open("header.dat").readlines()
    ftr = open("footer.dat").readlines()

    for i in tree:
        file = open("../"+i[0]+".php", "w")
        for j in hdr:
            file.write(j)

        for j in i[1]:
	    file.write("<p>");
	    for k in j[:-1]:
		file.write(k + "\n")
	    file.write(j[-1] + "</p>\n\n")

        if i[2] != []:
            file.write("<p>")
            for j in i[2]:
                file.write("* <a href=\""+j[0]+".php\">")
                for k in j[1:-1]:
		    file.write(k+"\n")
                file.write(j[-1]+"</a><br>\n")
	    file.write("</p>\n")

        for j in ftr:
            file.write(j)
        file.close()

# build tree
if err == 0:
    # create flag list
    treedict = {}
    treelist = []
    backtree = {}
    for i in tree:
        backtree[i[0]] = []
    for i in tree:
        treedict[i[0]] = []
        for j in i[2]:
            treedict[i[0]].append( j[0] )
	    if not backtree.has_key(j[0]):
		backtree[j[0]] = []
	    backtree[j[0]].append( i[0] )
        treelist.append(i[0])

    file = open("../tree.php", "w")
    for j in hdr:
        file.write(j)

    file.write("<p>Modules called but not found:<br>\n")
    cnt = 0
    for i in treelist:
	for j in treedict[i]:
	    if not treedict.has_key(j):
	        file.write("&nbsp;&nbsp;&nbsp;&nbsp;<a href=\""+i+".php\">["\
                    +i+"]</a> calls ["+j+"]<br>\n")
                cnt = cnt + 1
    if cnt == 0:
        file.write("&nbsp;&nbsp;&nbsp;&nbsp;(none -- all modules exist)\n");
    else:
        print str(cnt)+" modules not found"
    file.write("</p>\n\n")

    allused = 0
    maxcnt = 0
    prn = []
    prndict = {}
    while allused == 0:
        # find parent
        key = ""
        for i in range(len(treelist)):
	    if treelist[i] != "" and backtree[treelist[i]] == []:
		key = treelist[i]
		treelist[i] = ""
		break;

	if key == "":
	    allused = 1
	else:
	    fill = [[key, 0, 0]]
	    while len(fill) > 0:
		curr = fill[0][0]
		cnt = fill[0][1]
		flg = fill[0][2]
		fill = fill[1:]
		if prndict.has_key(curr):
		    org = 0
		else:
		    org = 1
		    prndict[curr] = 0
		prn.append([curr,cnt,flg, org])
		if org == 1:
		    if treedict.has_key(curr):
		        if len(treedict[curr]) > 0:
			    fill[0:0] = [[treedict[curr][0],cnt+1,1]]
		            for i in treedict[curr][1:]:
		                fill[0:0] = [[i,cnt+1,0]]
		if maxcnt < cnt:
		    maxcnt = cnt

    gblflg = []
    for i in range(maxcnt+2):
	gblflg.append(0)
    file.write("<table cellspacing=0 cellpadding=0>\n")
    for i in prn:
	curr = i[0]
	cnt = i[1]
	flg = i[2]
	org = i[3]
	if cnt == 0:
	    file.write("<tr><td>&nbsp;</td></tr>\n")
        file.write("<tr>\n")
	for j in range(1, cnt):
            if gblflg[j] == 0:
	        file.write("  <td><tt>&nbsp;|&nbsp;</tt></td>\n")
            else:
	        file.write("  <td><tt>&nbsp;&nbsp;&nbsp;</tt></td>\n")
	if cnt > 0:
	    if flg == 0:
	        file.write("  <td><tt>&nbsp;|-</tt></td>\n")
	    else:
	        file.write("  <td><tt>&nbsp;\-</tt></td>\n")
		gblflg[cnt] = 1
	gblflg[cnt+1] = 0
        if not treedict.has_key(curr):
	    file.write("  <td colspan="+str(maxcnt-cnt + 1)+">["+curr\
                +"]</td>\n")
        elif org == 0:
	    file.write("  <td colspan="+str(maxcnt-cnt + 1)+"><a href=\""+curr\
                +".php\"><font color=\"1faf1f\">["+curr+"]</font></a></td>\n")
        elif treedict[curr] == []:
	    file.write("  <td colspan="+str(maxcnt-cnt + 1)+"><a href=\""+curr\
                +".php\"><font color=\"ff3f3f\">["+curr+"]</font></a></td>\n")
        else:
	    file.write("  <td colspan="+str(maxcnt-cnt + 1)+"><a href=\""+curr\
                +".php\">["+curr+"]</a></td>\n")
	file.write("</tr>\n")
    file.write("</table>\n\n")

    for j in ftr:
        file.write(j)

if err == 1:
    print "Operation aborted!"
else:
    print "Done."
    print "See tree.php for details."


