partial script rewrite by Martijn