Cleaned up the code a bit and made it a bit more robust.

I've fixed a few bugs that were hiding in the code and cleaned things up a little bit.