Bugs squashed. Code optimized a bit. Script now passes all test cases (see test-results.txt)