Rewrite huge parts of the library

Took some ideas from the wimpy python library by @tamland.