Fixed stream usage, improved code quality and added unit test cases.