#!/usr/bin/env python
"""
weave - Weave Hypertext from Text
Author: Sean B. Palmer, inamidst.com
"""

import sys, re, optparse

r_link = re.compile(r'(?s)\{([^}]+)[ \t\r\n]([A-Za-z]+:[^}]+)\}')

def warning(msg): 
   print >> sys.stderr, 'weave: warning:', msg

def error(msg): 
   print >> sys.stderr, 'weave: error:', msg
   sys.exit(1)

def weavebytes(bytes): 
   return r_link.sub(r'<a href="\g<2>">\g<1></a>', bytes)

def weave(args, inplace=False): 
   if (not args) and (not inplace): 
      # weave stdin to stdout
      bytes = sys.stdin.read()
      result = weavebytes(bytes)
      sys.stdout.write(result)

   elif args and inplace: 
      # weave each file in place
      for filename in args: 
         try: 
            i = open(filename, 'rb')
            bytes = i.read()
            i.close()

            result = weavebytes(bytes)

            o = open(filename, 'wb')
            o.write(result)
            o.close()
         except Exception, e: 
            warning("Got an exception: " + str(e))

   elif (len(args) == 1) and (not inplace): 
      # weave the file to stdout
      filename = args[0]
      f = open(filename, 'rb')
      bytes = f.read()
      f.close()

      result = weavebytes(bytes)
      sys.stdout.write(result)

def main(argv=None): 
   parser = optparse.OptionParser('%prog [options]')
   parser.add_option('-i', '--inplace', action='store_true', default=False, 
                     help='modify file input in place')
   opts, args = parser.parse_args(argv)

   if (not args) and opts.inplace: 
      error("Can't modify stdin in place!")
   elif (len(args) > 1) and (not opts.inplace): 
      error("Can't weave more than one file to stdout!")

   weave(args, opts.inplace)

if __name__ == '__main__': 
   main()
