refactored code and fixed timing bugs