Fixed bugs and added conditional debug prints