#!/usr/bin/env python

try:
	from sgfpars import Node, Cursor, SGFError, SGFescape
except:
	from sgfparser import Node, Cursor, SGFError, SGFescape

import os, sys, getopt, re
from sys import stdout



def writeheader(rootnode, filename):
	global boardsize
	print 'File', filename
	if (rootnode.has_key('PW')):
		print "White: " + rootnode['PW'][0]
	if (rootnode.has_key('PB')):
		print "Black: " + rootnode['PB'][0]
	if (rootnode.has_key('RE')):
		print "# Result: " + rootnode['RE'][0]
	for el in ['DT', 'EV', 'RO']:
		if (rootnode.has_key(el)):
			print rootnode[el][0]
	print

	if (rootnode.has_key('SZ')):
		try:
			boardsize = int(rootnode['SZ'][0])
		except TypeError:
			print "SGF trouble: Don't understand board size."
			sys.exit(2)

def sgfpos2coord(pos):
	if len(pos) == 0 or pos == 'tt':
		return "PASS"
	elif len(pos) != 2:
		raise SGFError("Couldn't parse coordinate.")
	x, y = ord(pos[0])-ord('a'), ord(pos[1])-ord('a')
	return x, y


def writeposition(cursor, color):
	board = [['.' for x in range(0, boardsize)] for y in range(0, boardsize)]
	nodenum = 0
	while nodenum < movenum and not cursor.atEnd:
		try:
			thisnode = cursor.next()
		except SGFError:
			break
		if thisnode.has_key('AB'):
			for pos in thisnode['AB']:
				x, y = sgfpos2coord(pos)
				board[x][y] = 'X'
		if thisnode.has_key('AW'):
			for pos in thisnode['AW']:
				x, y = sgfpos2coord(pos)
				board[sgfpos2coord(pos)] = 'O'
		if thisnode.has_key('B'):
			x, y = sgfpos2coord(thisnode['B'][0])
			board[x][y] = 'X'
		elif thisnode.has_key('W'):
			x, y = sgfpos2coord(thisnode['W'][0])
			board[x][y] = 'O'
		else:
			continue
		nodenum = nodenum + 1

	stdout.write('{{{#!goban\n+')
	for x in range(0, boardsize):
		stdout.write('-')
	print '+'
	for y in range(boardsize-1, -1, -1):
		stdout.write('|')
		for x in range(0, boardsize):
			stdout.write(board[x][-y-1])
		print '|'
	stdout.write('+')
	for x in range(0, boardsize):
		stdout.write('-')
	print '+\n}}}'


# Main Program.
###############

help_string = """
sgf2gtp.py converts .sgf-files to an ASCII output that is usable for
GNU Go's trac Wiki.
Usage:
sgf2ascii.py --move=<movenum> <file>
"""

color = []
start = 0
to = 100000
boardsize = 19
movenum = 0
maxauto = 300

try:
	opts, args = getopt.getopt(sys.argv[1:], "",
				   ["help", "move="])
except getopt.GetoptError: 
	print "Unrecognized option. Try sgf2gtp.py --help"
	sys.exit(2)


for o, a in opts:
	if (o == "--help"):
		print help_string
		sys.exit()
	if (o == "--move"):
		try:
			movenum = int(a)
		except TypeError:
			print "Cannot convert", a, "into a number."
			sys.exit(2)

if not len(args) == 1:
	print "Error: Need exactly one file as argument."
	sys.exit(2)

filename = args[0]
try:
	file = open(filename)
	sgf = file.read()
	file.close()
	cursor = Cursor(sgf, 1)
	rootnode = cursor.getRootNode(0)
except IOError:
	print "Couldn't read file %s." % filename
	sys.exit(2)
except SGFError, message:
	print "Couldn't parse SGF in file %s: %s" % (filename, message)
	sys.exit(2)


writeheader(rootnode, filename)
writeposition(cursor, color)
