fix bugs, add test and merging

Please add unittest for this change.