Handled more errors and cleaned up code