Improved code readabilty and fixed minor issues

Sorry for the messy diff. I had to switch to 4 spaces indent.