Revert "Revert "Cleaned up the code a bit and made a few bug fixes""

This reverts commit a49e9d012bf52bb85b7a9590d342236b5c5783c7.