refactored and made a bit more robust