Reorganised code to match program flow