Refactored code to better use the Result monad.