tidied script: put functions at start, grouped variables