Fixed bugs in code and added tests against the bugs. Simplified if statements.