Refactored code structure, logic mostly remains as previour version