Fix NPE and ArrayIndexOutOfBoundsException