Added tests and fix bugs