heavy code reorganisation and improvements