reorganised code to improve readibility