Fixed some bugs and added tests. bugid:112488