Cleaned up the code a bit and added some comments to improve readability