Cleaned up code, added some debug statements