updated with some more error checks