Fixed various bugs and added unit test cases.