Code cleanup: Fixed a few code errors and improved the debug output and comments