Splits the library-ish code from the example code

I found your example really useful! Thanks. I rearranged things a bit. Not sure if you care to merge it up or want me to stick with my own fork.