Added check of length before substring statements to avoid OutOfBoundsException, as well as fixed some length() - 1's that shouldn't have been.