Replace base64.encodestring with base64.b64encode.

Also consolidate repetitive code into a single function
Clean up unused code