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

This reverts commit 255ab4a350bae585bafab77cb2bf7e45aad6ed83.
Revert "Revert "Cleaned up the code a bit and made a few bug fixes""

This reverts commit a49e9d012bf52bb85b7a9590d342236b5c5783c7.
Revert "Revert "Revert "Cleaned up the code a bit and made a few bug fixes"""

This reverts commit 387b53a73df5344c25cf6ed32fc95f52a94912fb.