small optimisation and bug fixes