Changed code to be a bit more legible and understandable by using a class to encapsulate some of the more nitty gritty complexities