#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# Time-stamp: <2004-07-11 09:57:54 graham>
#
# © COPYRIGHT
# Togaware 2004 All rights are reserved.
#
# Authors: Graham Williams
#

"""Support for the TeXCatalogue suite of tools."""

import os
import re
from xml.dom.ext.reader.Sax import FromXmlFile

Entries = "./entries"

def commify(amount):
    """Add commas every three digits in a number."""
    return re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', str(amount))

def list_packages(root=Entries):
    """List all the XML files found starting at root."""
    entries = []
    for w in os.walk(root, True, None):
        entries += w[2]
    Xmlre = re.compile("^[a-z][a-zA-Z0-9_\-]*\.xml$")
    entries = map(lambda x: re.sub("\.xml", "", x),filter(Xmlre.match,entries))
    entries.sort()
    return entries

def loadXML(pkg, path=Entries):
    """Open and return an XML file, with error checking."""
    xmlfile = path + "/" + pkg[0] + "/" + pkg + ".xml"
    try:
        doc = FromXmlFile(xmlfile, validate = False)
    except Exception, e:
        estr = str(e)
        #
        # Check for IDREF error, and if so, deal with it manually.
        #
        if "IDREF referred to non-existent ID" in estr:
            id = estr.split()
            id = id[-1]
            id = id[1:-1]
            refile = path + "/" + id[0] + "/" + id + ".xml"
            if os.path.exists(refile):
                # Still need to open the file if it's okay.
                doc = FromXmlFile(xmlfile, validate = False)
            else:
                print "ERROR parsing %s. Skipping this entry.\n%s" % (pkg, e)
                return False
        else:
            print "ERROR parsing %s. Skipping this entry.\n%s" % (pkg, e)
            return False
    return doc
