added proper local scoping, fixed misc bugs, added script support