Finish remaining tests and refactor code