Simplified code and added some comments