Slightly refactored version