Reorganised main function