# Copyright (c) 2003 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
Convert the epsg file of proj into a python .proj file.

Call it like:
$ python create_epsg.py > epsg.proj

This tool assumes the original file of proj ('epsg') to
be present in the standard location of a system wide
installation, i.e. in /usr/share/proj/epsg.
If it is somewhere else, just adapt the path in the code
below.

The entries in the source file look like this:

# Anguilla 1957 / British West Indies Grid
<200> +proj=tmerc +lat_0=0.000000000 +lon_0=-62.000000000 +k=0.999500 +x_0=40000 0.000 +y_0=0.000 +ellps=clrk80 +units=m  no_defs <>
"""

__version__ = "$Revision: 1.1 $"

# this function is copied from Thuban/Model/xmlwriter.py
def escape(data):
    """Escape &, \", ', <, and > in a string of data.
    """
    data = data.replace("&", "&amp;")
    data = data.replace("<", "&lt;")
    data = data.replace(">", "&gt;")
    data = data.replace('"', "&quot;")
    data = data.replace("'", "&apos;")
    return data

print '<?xml version="1.0" encoding="UTF-8"?>'
print '<!DOCTYPE projfile SYSTEM "projectionlist.dtd">'
print '<projectionlist>'

epsg = open('/usr/share/proj/epsg', 'r').readlines()

for line in epsg:
    if line[0] == '#':
        title = line[2:-1]
    if line[0] == '<':
        elements = line.split(' ')
        epsg_nr = elements[0][1:-1]
        print '    <projection epsg="%s" name="%s">' % (epsg_nr, escape(title))
        for p in elements[1:-3]:
            print '        <parameter value="%s"/>' % escape(p[1:])
        print '    </projection>'

print '</projectionlist>'
