Cleaned up the code a bit and added some more comments and TODOs.