##
## b64.py -- Base 64 encoding.
##
## Copyleft 1998 Teemu Kalvas <chery@s2.org>,
##          1995-1997 Timo J. Rinne <tri@iki.fi>
##

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

def build_decode_vector():
    v = 256 * [-1]
    l = len(alphabet)
    i = 0
    while i < l:
	v[ord(alphabet[i])] = i
	i = i + 1
    v[ord('=')] = -2
    return v

decode_vector = build_decode_vector()

def encode_string(str):
    l = len(str)
    n = l / 3
    i = 0
    r = ''
    while i < n:
	c0 = ord(str[3 * i])
	c1 = ord(str[3 * i + 1])
	c2 = ord(str[3 * i + 2])
	e0 = c0 >> 2
	e1 = ((c0 << 4) & 63) | (c1 >> 4)
	e2 = ((c1 << 2) & 63) | (c2 >> 6)
	e3 = c2 & 63
	r = r + alphabet[e0] + alphabet[e1] + alphabet[e2] + alphabet[e3]
	i = i + 1
    if l % 3 == 2:
	c0 = ord(str[3 * i])
	c1 = ord(str[3 * i + 1])
	e0 = c0 >> 2
	e1 = ((c0 << 4) & 63) | (c1 >> 4)
	e2 = (c1 << 2) & 63
	r = r + alphabet[e0] + alphabet[e1] + alphabet[e2] + '='
    elif l % 3 == 1:
	c0 = ord(str[3 * i])
	e0 = c0 >> 2
	e1 = (c0 << 4) & 63
	r = r + alphabet[e0] + alphabet[e1] + '=='
    return r

def decode_string(str):
    l = len(str)
    n = l / 4
    i = 0
    r = ''
    while i < n:
	e0 = decode_vector[ord(str[4 * i])]
	e1 = decode_vector[ord(str[4 * i + 1])]
	e2 = decode_vector[ord(str[4 * i + 2])]
	e3 = decode_vector[ord(str[4 * i + 3])]
	if e0 >= 0 and e1 >= 0 and e2 >= 0 and e3 >= 0:
	    c0 = ((e0 << 2) & 255) | (e1 >> 4)
	    c1 = ((e1 << 4) & 255) | (e2 >> 2)
	    c2 = ((e2 << 6) & 255) | e3
	    r = r + chr(c0) + chr(c1) + chr(c2)
	elif e0 >= 0 and e1 >= 0 and e2 >= 0 and e3 == -2:
	    c0 = ((e0 << 2) & 255) | (e1 >> 4)
	    c1 = ((e1 << 4) & 255) | (e2 >> 2)
	    r = r + chr(c0) + chr(c1)
	elif e0 >= 0 and e1 >= 0 and e2 == -2 and e3 == -2:
	    c0 = ((e0 << 2) & 255) | (e1 >> 4)
	    r = r + chr(c0)
	else:
	    return 0
	i = i + 1
    return r

## End. ##
