add some more error checks to be more robust