Code refactored slightly