#!/usr/bin/python
import urllib
import json
import time
import sys

if len(sys.argv) < 2:
  print "Usage: %s <output_file>" % sys.argv[0]
  raise SystemExit

try:
  conn = urllib.urlopen('https://data.mtgox.com/code/data/ticker.php')
#  conn.request('GET', '/code/data/ticker.php')
#  resp = conn.read()
except Exception as e:
  print "Unable to connect!  ", type(e)
  raise SystemExit

#if str(resp.status)[0] != '2':
 # print "HTTP request failed: ", resp.status, resp.reason
#  raise SystemExit
  
try:
  data = json.load(conn)
except Exception as e:
  print "Unable to parse json!  ", type(e)
  raise SystemExit

try:
  f = open(sys.argv[1], 'w')
  f.write("# at %s\n" % time.strftime('%Y-%m-%d %H:%M:%S'))
  f.write("bitcoin\t\t\t%f USD\n" % data['ticker']['last'])
  f.close()
except Exception as e:
  print "Unable to write data file! ", type(e)
  raise SystemExit
