Refactored according to JWs advice.