Fixed bugs in Ankit's code, plus some refactoring.