make code more testable and fix test cases