Fixed crash on exit and cleaned up code.