added debug lines and added some checks