#! /usr/bin/env python

# (C) Copyright 2003 Rob Blackwell
#   All rights reserved.

# Convert Mapgen files such as those available at http://rimmer.ngdc.noaa.gov/coast/
# into SVG XML files suitable for use with the Adobe SVG Viewer

# Mapgen is an ASCII flat file with two columns containing longitude and latitude in
# decimal degrees (west negative). The default MAPGEN format is lon,lat with new segments
# separated by a line containing the characters "# -b".

# Released under the GNU General Public License

import string, sys

# Work out the bounding box around the map so that a viewbox can be set up
def getExtents(filename):
    file = open(filename,"r")
    firstTime = True
    while 1:
        line= file.readline()
        if not line:
            break
        if line[0] != '#':
            line = line.split()
            x = float(line[0])
            y = float(line[1])
            if firstTime:
                firstTime = False
                minx = maxx = x
                miny = maxy = y
            else:
                if x > maxx:
                    maxx=x
                if x < minx:
                    minx=x
                if y > maxy:
                    maxy=y
                if y < miny:
                    miny=y

    # y axis scale is positive up for mapgen and positive down for SVG                
    return (minx, maxy, maxx - minx, maxy - miny)
                
                

def mapgen2svg(filename, extents):
    file = open(filename,"r")
    flag = False
    firstPoint = False

    print '<svg width="800px" height="600px" viewBox="%s -%s %s %s">' % extents
    print '<desc> Converted from %s </desc>' % filename
    print '<g transform="scale(1,-1)" style="stroke: black; stroke-width: 0.0001; fill:none;" >'

    while 1:
        line = file.readline()
        if not line:
            break

        if line[0] == '#':
            if flag:
                print '" />'
            flag = True
            firstPoint = True
            print '<polyline points="',
        else:
            if not firstPoint :
                print ', ',
            line = line.split()
            x = line[0]
            y = line[1]
            print line[0] + ' ' + line[1],
            
            firstPoint = False

    if flag:
        print '" />'

    print '</g></svg>'

if __name__ == '__main__':
    if (len(sys.argv) <> 2):
        sys.stderr.write("Usage:\n")
        sys.stderr.write("mapgen2.csv.py  <mapgen.dat> > <svgfile.svg>\n")
        sys.exit(-1)

    mapgen2svg(sys.argv[1], getExtents(sys.argv[1]))

