#!/usr/bin/env python
import sys
import GeoIP
from optparse import OptionParser


def parserCmd():
    parser = OptionParser()
    parser.add_option("-f", "--fields", dest="fieldsNum", default=0, help="field of IP")
    parser.add_option("-t", "--sep",  dest="sep", default='\t', help="sep")
    parser.add_option("-i", "--inputFile",  dest="filename", default='', help="filename to process")

    (options, args) = parser.parse_args()
    return options


def getCountryCode(ip):
    return gi.country_code_by_addr(ip)



gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
options = parserCmd()
if not options.filename:
    inFile = sys.stdin
else:
    inFile = file(options.filename)
try:
    for line in inFile:
        fields = line.strip().split(options.sep)
        code = getCountryCode(fields[options.fieldsNum])
        print "%s\t%s" %(code, line),
except IOError:
    pass
