Refactored/rewrote code to be neater and more efficient