minimal js refactoring

removal of global variables, and some error handling