Small bug fixes I missed in running script in unclean environment
Added some basic error handling