Fixed some bugs, added some tests