fixed critical bugs, added tests