# > !Currency.py.Rates/py

import pickle
import string
import time
import urllib


def load(cache):
    global _date, _rates
    c = open(cache, 'r')
    _date = pickle.load(c)
    _rates = pickle.load(c)
    c.close()


def update(url, cache, us, dollar):
    global _date, _rates
    rates = [(us, dollar, 1.0)]
    u = urllib.urlopen(url)
    c = open(cache, 'w')
    _date = time.strftime('%d %b %Y')
    while 1:
        l = u.readline()
        if l == '':
            break
        l = l[:-1]
        m = string.split(l, ' ', 1)
        rates.append(('', m[1], eval(m[0])))
    u.close()
    pickle.dump(_date, c, 1)
    _rates = rates
    pickle.dump(_rates, c, 1)
    c.close()


def currencies(format):
    return map(lambda rate, format = format:
               format % {'country': rate[0], 'currency': rate[1], 'rate': rate[2]},
               _rates)


def currency(format, i):
    return format % {'country': _rates[i][0], 'currency': _rates[i][1], 'rate': _rates[i][2]}


def date():
    return _date


def convert(currency, value):
    conversion = []
    base = float(value) / _rates[currency][2]
    for rate in _rates:
        conversion.append(base * rate[2])
    return conversion
