some refactoring, slightly more robust
last tidying