reorganised the code a bit