added tests and fixed a few logic errors