Added null checks and state checks to easier discover errors.