Refactored Code, More error Handling