Bug fixes, refactoring, and added debugging output