private static void addToSetIfNecessary(TaxonLabelSet tlSet, Collection<TaxonLabel> labels) {
   Set<TaxonLabel> tlList = new HashSet<TaxonLabel>(tlSet.getTaxonLabelsReadOnly());
   for (TaxonLabel label : labels) {
     if (!tlList.contains(label)) {
       tlList.add(label);
       tlSet.addPhyloTaxonLabel(label);
     }
   }
 }
  public Set<TaxonLabelSet> createTaxonLabelSets(Study s, boolean justTrees, boolean justMatrices) {
    bindSession();

    Set<TaxonLabelSet> newSets = new HashSet<TaxonLabelSet>();
    Set<TaxonLabelSet> oldSets = s.getTaxonLabelSets();
    Hibernate.initialize(oldSets);

    for (Analysis an : s.getAnalyses()) {
      TaxonLabelSet theSet = new TaxonLabelSet();
      theSet.setStudy(s);
      theSet.setTitle(an.getName());
      Collection<TreeBlock> treeBlocks = new LinkedList<TreeBlock>();

      for (AnalysisStep as : an.getAnalysisStepsReadOnly()) {
        for (AnalyzedData ad : as.getDataSetReadOnly()) {
          Matrix m = ad.getMatrixData();
          PhyloTree t = ad.getTreeData();

          if (m != null && !justTrees) {
            addToSetIfNecessary(theSet, m.getAllTaxonLabels());
            m.setTaxa(theSet);
            //						tlService.updateStudyForAllLabels(m, s);
          }
          if (t != null && !justMatrices) {
            addToSetIfNecessary(theSet, t.getAllTaxonLabels());
            //						tlService.updateStudyForAllLabels(t, s);
            treeBlocks.add(t.getTreeBlock());
          }
        }
      }

      ContextManager.getTaxonLabelService().save(theSet);
      for (TreeBlock tb : treeBlocks) {
        tb.setTaxonLabelSet(theSet);
        ContextManager.getTaxonLabelService().save(tb); // XXX Should be treeBlockService
      }
      newSets.add(theSet);
    }

    s.setTaxonLabelSets(newSets);

    unbindSession();
    return newSets;
  }