Bug 16289: Refactore code and add tests