full implementation, added debugging messages