Fixed some bugs and added some debug printings.