Added tests and fixes some bugs.