added some comments and simplified code