# Script for converting BNG transverse mercator co-ordinates (eastings northings in km) to OS grid square co-ordinates
#
# Author: Ben Taylor
# Created: 05/06/2008
# Last edit: 05/06/2008
import math
import sys
import alphaconv
if (len(sys.argv) != 3):
print "Usage: python bnglookup.py eastings northings"
sys.exit(1)
# end if
eastings_in = float(sys.argv[1])
northings_in = float(sys.argv[2])
eastings_out = "S0000"
northings_out = "V0000"
firstletter = "S"
secondletter = "V"
subeasting = eastings_in
subnorthing = northings_in
if ((eastings_in < 0) or (eastings_in > 700000) or (northings_in < 0) or (northings_in > 1300000)):
print "One or both co-ordinates are out of range.\nEastings may be 0-700000, northings may be 0-1300000."
sys.exit(1)
# end if
# Check first letter - 500km grid squares
if (northings_in < 500000):
if (eastings_in < 500000):
firstletter = "S"
else:
subeasting = eastings_in - 500000
firstletter = "T"
# end if
else:
if (northings_in < 1000000):
subnorthing = northings_in - 500000
if (eastings_in < 500000):
firstletter = "N"
else:
subeasting = eastings_in - 500000
firstletter = "O"
# end if
else:
subnorthing = northings_in - 1000000
if (eastings_in < 500000):
firstletter = "H"
else:
subeasting = eastings_in - 500000
firstletter = "J"
# end if
# end if
# end if
# Work out grid square we're in
letterconv = (math.ceil(subeasting/100000)) + (5 * (5 - math.ceil(subnorthing/100000)))
# Letter I is skipped in national grid, so add one if we're at or past I
if (letterconv >= 9):
letterconv = letterconv + 1
# end if
secondletter = alphaconv.num2letter(letterconv)
# Subtract the number of hundred thousand metres from each coordinate - that's covered by the grid letter
subgrid_e = int(math.floor(subeasting - (100000 * math.floor(subeasting/100000))))
subgrid_n = int(math.floor(subnorthing - (100000 * math.floor(subnorthing/100000))))
# Get the number of ten thousand metres for each coordinate for the 10km tile
e_10km = (int(10000 * math.floor(subgrid_e/10000)))/10000
n_10km = (int(10000 * math.floor(subgrid_n/10000)))/10000
easting_out = firstletter + str(subgrid_e)
northing_out = secondletter + str(subgrid_n)
print("Grid reference: " + easting_out + " " + northing_out)
print("10km Tile: " + firstletter + secondletter + str(e_10km) + str(n_10km))