#!/usr/bin/python

#
# Parses a bibtex file, create a wiki-formatted list of bibtex entries
#
# Usage: bibtex2wiki <bibtexfile.bib> [linelists.txt]
#
#

import sys

def bibtex2wiki(infile, outfile):
    try:
        fin = open(infile, 'r')
    except IOError:
        print "File %s could not be found."
        sys.exit()
    try:
        fout = open(outfile, 'w')
    except IOError:
        print "Error opening outfile %s" % outfile
        sys.exit()
        
    outstring = ""    
    block = ""
    blockid = ""
    header = "\n<<Anchor(%s)>>\n{{{\n"
    footer = "}}}"
        
    def format_block(blockid, block):
        return header % blockid + block + footer
        
    for line in fin.xreadlines():
        #print line
        if line.strip().startswith('%'):
            # a bibtex comment
            continue 
        if line.strip().startswith('@'):
            # the start of a new block            
            if block and blockid:
                # close the previous block
                fout.writelines(format_block(blockid, block))
                blockid, block = "", ""                
            try:
                blockid, block = line.split('{', 1)[1].strip().strip(','), line
            except Exception:
                print "ERROR: malformed block header in: '%s'" % line
                sys.exit()
        elif block:
            # keep filling an existing block
            block += line
        else:
            # outside of any block - ignore
            pass
    if block and blockid:
        # handle last entry
        fout.writelines(format_block(blockid, block))
    fin.close()
    fout.close()

if __name__ == "__main__":
    
    argv = sys.argv
    if len(argv) < 2:
        print """
        Usage: bibtex2wiki.py <bibtexfile> [linelistRefs.txt]

        This takes a valid bibtex file as input. It creates a readily formatted
        wiki-page with each bibtex entry as a HTML-linkable entry. Load the output file
        into the wiki using the wiki's Load command (found in the left-hand menu).
        """

        sys.exit()    
    infile = argv[1].strip()
    try:
        fil = open(infile, 'r')
    except IOError:
        print "File %s could not be found." % infile
        sys.exit()
    if len(argv) > 2:
        outfile = argv[2].strip()
    else:
        outfile = "linelistRefs.txt"
    bibtex2wiki(infile, outfile)
    print "... parsed %s. Created output file %s." % (infile, outfile)
