Refactored by using python cookbook