public static int compareEntities(final RefEntity entity1, final RefEntity entity2) {
    if (entity1 != null && entity2 != null) {
      int cmp = compareEntitiesByName(entity1, entity2);
      if (cmp != 0) return cmp;
    }
    if (entity1 instanceof RefFile && entity2 instanceof RefFile) {
      VirtualFile file1 = ((RefFile)entity1).getPointer().getVirtualFile();
      VirtualFile file2 = ((RefFile)entity2).getPointer().getVirtualFile();
      if (file1 instanceof VirtualFileWithId && file2 instanceof VirtualFileWithId) {
        return Integer.compare(((VirtualFileWithId)file1).getId(), ((VirtualFileWithId)file2).getId());
      }
      int cmp = file1.getName().compareToIgnoreCase(file2.getName());
      if (cmp != 0) return cmp;
      cmp = file1.getPath().compareToIgnoreCase(file2.getPath());
      return cmp;
    }
    if (entity1 instanceof RefElement && entity2 instanceof RefElement) {
      final SmartPsiElementPointer<?> p1 = ((RefElement)entity1).getPointer();
      final SmartPsiElementPointer<?> p2 = ((RefElement)entity2).getPointer();
      if (p1 != null && p2 != null) {
        final VirtualFile file1 = p1.getVirtualFile();
        final VirtualFile file2 = p2.getVirtualFile();

        if (file1 != null && file1.isValid() && file2 != null && file2.isValid()) {
          int cmp = PsiUtilCore.compareElementsByPosition(((RefElement)entity1).getPsiElement(), ((RefElement)entity2).getPsiElement());
          if (cmp != 0) return cmp;
          if (file1 instanceof VirtualFileWithId && file2 instanceof VirtualFileWithId) {
            return Integer.compare(((VirtualFileWithId)file1).getId(), ((VirtualFileWithId)file2).getId());
          }
          return file1.getPath().compareToIgnoreCase(file2.getPath());
        }
        return 0;
      }
      if (p1 != null) return -1;
      if (p2 != null) return 1;
      return 0;
    }
    return entity1 != null ? -1 : entity2 == null ? 0 : 1;
  }
public static int compareEntities(final RefEntity entity1, final RefEntity entity2)