Fixed several major bugs in the substitution algorithm.