Refactored and optimised