improved error handling, added some checks