some optimisations (thanks skaro for advice)