refactor code and improve timing