Refine the code and add more unit tests.