Refactored code into less hideous form