added logging and improved error detection