Refine the code and add the unit tests