#!/usr/bin/env python
#
# $Source: /home/blais/repos/cvsroot/arubomu/old/bin/fix-tracks,v $
# $Id: fix-tracks,v 1.1 2004/02/07 01:17:06 blais Exp $
#

"""fix-catalogs [<options>] <file>

Fix old catalog format to newer one.

"""
# Used like this:
#
# for i in   */*.xml ; do echo $i ; \
#   b=/tmp/orig/$(basename $i) ; cp $i $b ; \
#   ~/p/arubomu/old/bin/fix-catalogs $b > /tmp/a.xml ; \
#   xmllint-elementtree --format /tmp/a.xml > $i ; \
#   diff -y --suppress-common-lines $b $i ; done

__version__ = "$Revision: 1.1 $"
__author__ = "Martin Blais <blais@furius.ca>"


import sys, os

from elementtree import ElementTree
from elementtree.ElementTree import SubElement


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip(), version=__version__)
    opts, args = parser.parse_args()

    if len(args) != 1:
        raise parser.error("Please specify a single input file.")
    fn = args[0]

    try:
        tree = ElementTree.parse(fn)
        root = tree.getroot()
    except IOError, e:
        raise SystemExit("Error: couldn't read file (%s):" % fn + str(e))

    for missing in tree.findall('//missing-tracks') + \
            tree.findall('//extra-tracks'):
        if missing.text.strip():
            tracks = map(int, missing.text.split(','))
            del missing.text
            for t in tracks:
                el = SubElement(missing, 'track')
                el.set('no', str(t))
    
    tree.write(sys.stdout, encoding='iso-8859-1')
    print

if __name__ == '__main__':
    main()

