fixed some critical bugs, added tests