Refactor script, bugfix