fix #549 fixed bugs, and add tests