Fixed KeyError bug
More refactoring.