refactored script until line 308 - has to be tested!