code refactored a bit