Added tests and some bug fix