cleaned up the code a bit and added more comments