
import os, subprocess, glob, sys

kinds = sys.argv[1]

srcs = glob.glob("*.c") + glob.glob("*.h")

def sh(args):
    print " ".join(args)
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    o,u = p.communicate()
    if p.poll():
        print "error:"," ".join(args)
    return o.split("\n")

# Syntax highlight all the files
if 0:
 for fn in srcs:
  sh("pygmentize -O full -O anchorlines -O linenos=table -O lineanchors=line -o".split(" ") + ["html/%s.html" % fn,fn] ) 

# Use ctags to find all tags in them
sh(['ctags']+srcs)

# Scan the tag file
ll = [li[:-1].split("\t") for li in open("tags","r") if li and li[0]!="!"]
tbl = {}
for li in open("tags","r"):
  if li and li[0]=="!":
    continue
  fun,decl,_,kind = li[:-1].split("\t")[:4]
  if kinds.find(kind)<0:
    continue
  # New item
  nm = "%s (%s)" % (fun,kind)
  tbl[nm]=[]
  # Grep for its appearances
  for rl in sh(["grep","-nE","([^a-zA-Z0-9_]|^)%s[^a-zA-Z0-9_]" % fun] + srcs):
    ref = rl.split(":")[:2]
    if ref[0]:
      tbl[nm].append(tuple(ref))

tbl = tbl.items()
tbl.sort()

so = sys.stdout
sys.stdout = open("html/index.html","w")
print """
<html>
<head><title>Symbol references</title>
</head><body>
"""
for fun,refs in tbl:
  print "<h2>:: "+fun+"</h2>"
  refs.sort()
  print "<table>"
  ft = None
  for fi,ln in refs:
    if ft != fi:
      ft = fi
      txt = open(fi,"r").readlines()
      print "<tr><th colspan=2>",fi,"</th></tr>"
    hr = "%s.html#line-%s" % (fi,ln)
    print '<tr><td align=right>%s<td><td><a href="%s"><code>%s</code></a></td></tr>' %(ln,hr,txt[int(ln)-1])
  print "</table>"
print "</body></html>"
sys.stdout.close()
sys.stdout = so

