#!/usr/bin/env python
# KMB 2008-12-30
# TODO automatic map generation

gaz_filename='50kgazsample.txt' # edit this if necessary

import re
import cPickle
from tkinter_app_00 import App,win

if win:
  gaz_path='./'
else:
  gaz_path='/home/kbriggs/OS_50k_Gazetteer-1.0/'

gaz={}
names=[]

def make_pkl():
  try:
    pkl=open('50kgaz.pkl','rb')
    pkl.close()
  except:
    try:
      fn=gaz_path+gaz_filename
      f=open(fn,'r')
    except:
      from gzip import GzipFile
      fn=gaz_path+gaz_filename+'.gz'
      f=GzipFile(fn,'r')
    gaz={}
    for line in f:
      z=line.split(':')
      ng=metres_to_ng(float(z[9]),float(z[8]))
      gaz.setdefault(z[2],[]).append(ng)
    pkl=open('50kgaz.pkl','wb')
    cPickle.dump(gaz,pkl,-1)
    pkl.close()

def init():
  global gaz,names,lcnames
  try:
    pkl=open('50kgaz.pkl','rb')
    gaz=cPickle.load(pkl)
    pkl.close()
    names=gaz.keys()
  except:
    if win:
      raw_input('Could not load 50kgaz.pkl - press any key to quit.')
    return '50kgaz.pkl load failure'

def find(place,cb=False,v=False):
  r={}
  rx=re.compile(('(?i)','')[cb]+place)
  for name in names:
    m=rx.match(name)
    if m: r[name]=gaz[name]
  if v: print r
  s=place+':\n'
  for x in r:
    s+='%s: '%(x,)
    for y in r[x]: s+='%s '%(y,)
    s=s[:-1]+'\n'
  return s,''

if __name__=='__main__':
  make_pkl()
  app=App(title='OS 50k by Keith Briggs',init=init,action=find,checkbutton='case sensitive',help='help is available at http://keithbriggs.info/search_gui.html.')
  app.mainloop()
