Refactor more code and fix bugs introduced with the new changes.