Refactors code, adds error handeling, adds more inline documentation