Better exception handling. Some code refactoring.