Re-organized code and added some comments