Cleaned up the code quite a bit. Added comments, and maade it easier to follow