Fixed bugs in logic