class SubstringComparator implements Comparator<Substring>, Serializable {

  public int compare(Substring s1, Substring s2) {
    final int s1From = s1.from;
    final int s1To = s1.to;
    final int s2From = s2.from;
    final int s2To = s2.to;

    final int s2Length = s2To - s2From;
    final int s1Length = s1To - s1From;
    if (s1Length != s2Length) {
      return s1Length - s2Length;
    }

    assert s1Length == s2Length;
    for (int i = 0; i < s1Length; i++) {
      final int stemIndex1 = wordsStemIndex[tokensWordIndex[s1From + i]];
      final int stemIndex2 = wordsStemIndex[tokensWordIndex[s2From + i]];
      if (stemIndex1 != stemIndex2) {
        return stemIndex1 - stemIndex2;
      }
    }

    // If the substrings are equal in the inflection-insensitive way, return 0 (equivalence class).
    return 0;
  }

  public  SubstringComparator(int[] tokensWordIndex, int[] wordsStemIndex);

}