simplified code and fixed bugs