fix bugs and add tests