Merge pull request #750 from JoesCat/master

more code improvements and error checks