more code improvements and error checks