Modified Code, subdivided it into more methods, to make it more testable