added some comments and clean up the code