#!/usr/bin/env python

"""Usage: nodify.py filename.html

Rewrites Everything2 links into HTML.
The result is printed into standard output. You can use
nodify.py input.html > output.html
to save the result.

This is Free software
originally written by TeknoHog in 2002."""

import os, re, string, sys

text = r"[^\[\]]+?"
href = "http://everything2.org/?node="

# remember to (group) properly
pipelink = re.compile(r'\[(' + text + r')\|(' + text + r')\]')
genlink = re.compile(r'\[(' + text + r')\]')

def Fixlines(match):
    return string.replace(match.group(0), os.linesep, " ")

def Nodify(temp):
    global href, pipelink, hardlink

    # inside [links]: convert newlines to spaces
    temp = genlink.sub(Fixlines, temp)

    temp = pipelink.sub(r'<a href="' + href + r'\1">\2</a>', temp)
    # we're left with hardlinks only at this point
    temp = genlink.sub(r'<a href="' + href + r'\1">\1</a>', temp)

    return temp

filename = sys.argv[1]
file = open(filename, "r+")
temp = file.read()
file.close()
print Nodify(temp)
