Better exception handling and other tidying.