Fixed some bugs and added tests