Fix for a substring "endindex is larger than length" error which occurred earlier. Was checking for length in wrong location.