works but produces StringIndexOutOfBoundException in some cases