Cleaned up the code a bit, added comments

Also fixed a few issues