Removed debug code and fixed some bugs