Refine code and add tests