Refactored, adjusted begin/rescue blocks, removed unnecessary variables, clarified comments