added more error controls and debuging messages