/*  $Id: phylo_tree_ds.cpp 47479 2023-05-02 13:24:02Z ucko $
 * ===========================================================================
 *
 *                            PUBLIC DOMAIN NOTICE
 *               National Center for Biotechnology Information
 *
 *  This software/database is a "United States Government Work" under the
 *  terms of the United States Copyright Act.  It was written as part of
 *  the author's official duties as a United States Government employee and
 *  thus cannot be copyrighted.  This software/database is freely available
 *  to the public for use. The National Library of Medicine and the U.S.
 *  Government have not placed any restriction on its use or reproduction.
 *
 *  Although all reasonable efforts have been taken to ensure the accuracy
 *  and reliability of the software and data, the NLM and the U.S.
 *  Government do not and cannot warrant the performance or results that
 *  may be obtained by using this software or data. The NLM and the U.S.
 *  Government disclaim all warranties, express or implied, including
 *  warranties of performance, merchantability or fitness for any particular
 *  purpose.
 *
 *  Please cite the author in any work or product based on this material.
 *
 * ===========================================================================
 *
 * Authors:  Bob Falk
 *
 * File Description:
 *
 */

#include <ncbi_pch.hpp>
#include <gui/widgets/phylo_tree/phylo_tree_ds.hpp>

#include <gui/widgets/phylo_tree/phylo_selection_set.hpp>

#include <objects/general/User_object.hpp>
#include <objects/general/User_field.hpp>
#include <objects/general/Object_id.hpp>
#include <objects/biotree/FeatureDictSet.hpp>
#include <objects/biotree/FeatureDescr.hpp>
#include <objects/biotree/NodeSet.hpp>
#include <objects/biotree/Node.hpp>
#include <objects/biotree/NodeFeatureSet.hpp>
#include <objects/biotree/NodeFeature.hpp>

#include <util/xregexp/regexp.hpp>


BEGIN_NCBI_SCOPE


void CTreeLabel::InitializeFromUserObject(const CBioTreeContainer_Base::TUser& uo)
{
    if (uo.HasField("view-label") &&
        uo.GetField("view-label").GetData().IsObject()) {

            const CUser_field::C_Data::TObject& label_obj = uo.GetField("view-label").GetData().GetObject();

            if (label_obj.HasField("label") &&
                label_obj.GetField("label").GetData().IsStr()) {
                   m_Label = label_obj.GetField("label").GetData().GetStr();
            }

            if (label_obj.HasField("font-name") &&
                label_obj.GetField("font-name").GetData().IsStr()) {
                    m_FontName = label_obj.GetField("font-name").GetData().GetStr();
            }

            if (label_obj.HasField("font-size") &&
                label_obj.GetField("font-size").GetData().IsInt()) {
                    m_FontSize = label_obj.GetField("font-size").GetData().GetInt();
            }

            if (label_obj.HasField("posx") &&
                label_obj.GetField("posx").GetData().IsInt()) {
                    m_XPos = label_obj.GetField("posx").GetData().GetInt();
            }

            if (label_obj.HasField("posy") &&
                label_obj.GetField("posy").GetData().IsInt()) {
                    m_YPos = label_obj.GetField("posy").GetData().GetInt();
            }

            if (label_obj.HasField("color") &&
                label_obj.GetField("color").GetData().IsStr()) {
                    m_Color.FromString(label_obj.GetField("color").GetData().GetStr());
            }
    }
}

void CTreeLabel::SaveToUserObject(CBioTreeContainer_Base::TUser& uo)
{
    CRef<CUser_field::C_Data::TObject>  label_object;

    if (uo.HasField("view-label") && 
        uo.GetField("view-label").GetData().IsObject()) {
            label_object.Reset(&(uo.SetField("view-label").SetData().SetObject()));               
    }
    else {                      
        CUser_object* label_uo = new CUser_object();
        CRef<CObject_id> uo_id;
        uo_id.Reset(new CObject_id());
        uo_id->SetStr("label-parameters");
        label_uo->SetType(*uo_id);

        label_object.Reset(label_uo);
        uo.AddField("view-label", *label_uo);
    }    

    if (label_object->HasField("label") && 
        label_object->GetField("label").GetData().IsStr()) {
            label_object->SetField("label").SetData().SetStr(m_Label);
    }
    else {
        label_object->AddField("label", m_Label);
    }  

    if (label_object->HasField("font-name") && 
        label_object->GetField("font-name").GetData().IsStr()) {
            label_object->SetField("font-name").SetData().SetStr(m_FontName);
    }
    else {
        label_object->AddField("font-name", m_FontName);
    }  

    if (label_object->HasField("font-size") && 
        label_object->GetField("font-size").GetData().IsInt()) {
            label_object->SetField("font-size").SetData().SetInt(m_FontSize);
    }
    else {
        label_object->AddField("font-size", m_FontSize);
    } 

    if (label_object->HasField("posx") && 
        label_object->GetField("posx").GetData().IsInt()) {
            label_object->SetField("posx").SetData().SetInt(m_XPos);
    }
    else {
        label_object->AddField("posx", m_XPos);
    }  

    if (label_object->HasField("posy") && 
        label_object->GetField("posy").GetData().IsInt()) {
            label_object->SetField("posy").SetData().SetInt(m_YPos); 
    }
    else {
        label_object->AddField("posy", m_YPos);
    } 

    if (label_object->HasField("color") && 
        label_object->GetField("color").GetData().IsStr()) {
            label_object->SetField("color").SetData().SetStr(m_Color.ToString());
    }
    else {
        label_object->AddField("color", m_Color.ToString());
    }
}

CPhyloTree CPhyloTreeDataSource::m_sTreeClipboard;

//////////////////////////////////////////////////////////////////////
// 
//////////////////////////////////////////////////////////////////////
CPhyloTreeDataSource::CPhyloTreeDataSource(const objects::CBioTreeContainer& tree, 
                                           objects::CScope& scope,
                                           bool expand_all)
: m_Calc(NULL)
{
    Init(tree, scope, expand_all);
}

CPhyloTreeDataSource::~CPhyloTreeDataSource()
{
    delete m_Calc;
    m_Calc = NULL;
}

void CPhyloTreeDataSource::Init(const objects::CBioTreeContainer& tree, 
                                objects::CScope& scope,
                                bool expand_all)
{
    // Make sure we have a valid container - it can't be empty.
    if (tree.GetNodeCount() == 0 ) {
        NCBI_THROW(CException, eUnknown, "Cannot initialize CPhyloTreeDataSource with an empty tree");
    }

    if (!m_TreeModel.IsNull())
        m_TreeModel->Clear();
    else
        m_TreeModel.Reset(new CPhyloTree());


    m_Scope.Reset(&scope);

    BioTreeConvertContainer2Tree(m_TreeModel.GetNCObject(), tree, &m_TreeModel->GetFeatureDict(), true, expand_all);
    m_TreeModel->UpdateNodesMapping();

    if (tree.IsSetUser()) {
        const CBioTreeContainer_Base::TUser& uo = tree.GetUser();
        m_TreeLabel.InitializeFromUserObject(uo);

        m_TreeModel->GetSelectionSets().Clear();
        m_TreeModel->GetSelectionSets().InitFromUserObject(m_TreeModel.GetPointer(), uo);
    }

    TreeDepthFirst(m_TreeModel.GetNCObject(), 
        visitor_read_properties(m_TreeModel->GetColorTable()));

    MeasureTree();
    m_Calc->DumpStats();
}

void CPhyloTreeDataSource::Clear() 
{
    m_TreeModel->Clear();

    m_SearchCurrentNode = CPhyloTree::Null();
}

void CPhyloTreeDataSource::SetColorIndices(CPhyloTreeScheme* scheme)
{
    if (scheme != NULL)
        scheme->UpdateColorTable(m_TreeModel->GetColorTable());

    m_TreeModel->GetColorTable()->LoadTexture();
}

float CPhyloTreeDataSource::GetClosestLen(float pct) const
{ 
    size_t idx = (size_t)(pct*float(m_LenDistribution.size()));
    return m_LenDistribution[std::min(idx, m_LenDistribution.size() - 1)];
}

void CPhyloTreeDataSource::MeasureTree(TTreeIdx node)
{
    if (!m_Calc)
        m_Calc = new CPhyloTreeCalculator(m_TreeModel.GetPointer(), m_TreeModel->GetColorTable());
    m_Calc->Init(m_TreeModel->GetColorTable());
    *m_Calc = TreeDepthFirst(m_TreeModel.GetNCObject(), node, *m_Calc);

    // Force lengths to be recomputed if tree changed (but do not compute by 
    // default since they are not always needed).
    m_LenDistribution.clear();
}

void CPhyloTreeDataSource::ComputeLengthsFromRoot()
{
    // Can't compute lengths without distance parameter.
    if (!m_TreeModel->GetFeatureDict().HasFeature("dist"))
        return;

    // The array is only needed for visualization based on edge length of 
    // large trees. Only compute if needed. If tree changes, MeasureTree()
    // clears the array so we know its needed.
    if (m_LenDistribution.size() != 0)
        return;

    CPhyloTreeMaxChildDist child_dist =
        TreeDepthFirst(m_TreeModel.GetNCObject(),
        m_TreeModel->GetRootIdx(),
        CPhyloTreeMaxChildDist(m_TreeModel.GetNCPointer()));

    float min_dist = child_dist.GetMinDist();
    float max_dist = child_dist.GetMaxDist();

    float dist_scaler = 1.0f / (max_dist - min_dist);
    m_LenDistribution.swap(child_dist.GetDistances());
    for (size_t i = 0; i<m_LenDistribution.size(); ++i) {
        m_LenDistribution[i] = (m_LenDistribution[i] - min_dist)*dist_scaler;
        m_TreeModel->GetNode(i)->SetEdgeScore(m_LenDistribution[i]);
    }

    std::sort(m_LenDistribution.begin(), m_LenDistribution.end());
}

void CPhyloTreeDataSource::MeasureTree()
{
    MeasureTree(m_TreeModel->GetRootIdx());
}

string CPhyloTreeDataSource::GenerateTooltipFormat()
{
    string ttf = "";
    
    if (!m_TreeModel.IsNull()) {
        CBioTreeFeatureDictionary dict = m_TreeModel->GetFeatureDict();
        
        ITERATE(CBioTreeFeatureDictionary::TFeatureDict, it, dict.GetFeatureDict()) {
            string sName = it->second;
            string sKey  = "$(" + it->second + ")";
           
            ttf += ttf.empty()?"" : "\n";
            ttf += (sName + ": " + sKey);            
        }
    }

    return ttf.empty()?"Tree Node":ttf;
}


void CPhyloTreeDataSource::ApplyAttributes(CBioTreeAttrReader::TAttrTable & attrs,
                                           CPhyloTreeScheme* scheme,
                                           const string& labelfmt)
{
    m_Calc->Init(m_TreeModel->GetColorTable());
    m_Calc->SetAttrTable(attrs);
    if (!labelfmt.empty())
        m_Calc->SetLabelFormat(labelfmt);
    *m_Calc = TreeDepthFirst(m_TreeModel.GetNCObject(), m_TreeModel->GetRootIdx(), *m_Calc);
    m_Calc->ClearAttrTable();


    
    // Update all colors in the color table (scheme colors, colors attached to nodes
    // and cluster colors)
    m_TreeModel->GetColorTable()->ClearColors();

    TreeDepthFirst(m_TreeModel.GetNCObject(), visitor_read_properties(m_TreeModel->GetColorTable()));

    Clusterize(scheme);  
}

// clusters check
bool CPhyloTreeDataSource::HasClusters()
{
    return (m_Calc != NULL && !m_Calc->GetClusters().empty()); 
}


// clusterizing with colors
void CPhyloTreeDataSource::Clusterize(CPhyloTreeScheme* scheme)
{   
    if (!m_Calc)
        return;

    // seed color
    CRgbaColor          color(204, 153, 102);
    CRgbaColor          white(255,255,255,255);

    size_t color_idx;
    if (!m_TreeModel->GetColorTable()->FindColor(color, color_idx)) {
        color_idx = m_TreeModel->GetColorTable()->AddColor(color);                                            
    }

    m_ClusterToColorMap.clear();

    // COLOR 'STEP'
    int   nmbClusters = static_cast<int>(m_Calc->GetClusters().size());
    float colorStep = nmbClusters? (180.0 / nmbClusters): 0;
    //unsigned contrast = 1;
    // for narrow color angle we will try an alternative color assignment 
    bool narrow_angle = colorStep < 5.0; 

    // Get cluster ids from selection sets -these have their own assigned colors so
    // we should not generate them. Only active (selected) selection sets need to
    // be considered here.
    map<int, size_t>  cluster_id_to_selection_map = m_TreeModel->GetSelectionSets().GetClusterToSelectionMap();


    // Find colors for each cluster
    ITERATE (CPhyloTreeCalculator::TClusterHash, cl, m_Calc->GetClusters()) {
        int cluster_id = cl->first;

        // Get color from table of selected node sets OR generate it for the cluster.
        // We generate a new color each time though the loop even if not all are used
        // because we want to not change cluster colors when selection changes. (disconcerting
        // for user)
        CRgbaColor cluster_color = color;
        if (cluster_id_to_selection_map.find(cluster_id) != cluster_id_to_selection_map.end()) {
            size_t select_set_idx = cluster_id_to_selection_map[cluster_id];
            cluster_color = m_TreeModel->GetSelectionSets().GetSets()[select_set_idx].GetColor();
        }
        else {
            // This code is to protect us from colors too bright (almost white)           
            float c_dist = CRgbaColor::ColorDistance(white, cluster_color);
            while (c_dist < 0.2f) {
                cluster_color.Darken(0.15f);
                c_dist = CRgbaColor::ColorDistance(white, cluster_color);
            }
        }

        if (!m_TreeModel->GetColorTable()->FindColor(cluster_color, color_idx)) {
            size_t closest_idx;
            float dist = m_TreeModel->GetColorTable()->FindClosestColor(cluster_color, closest_idx);            

            if (dist > 0.01f) {
                // Add a new color to the color table
                color_idx = m_TreeModel->GetColorTable()->AddColor(cluster_color);
            }
            else {
                // Use an existing color (to avoid letting the table get large - since it's stored in a texture
                // max size may be 4096 or 8192.
                color_idx = closest_idx;
            }
        }

        m_ClusterToColorMap[cluster_id] = color_idx;

        float rotate_angle = colorStep + (narrow_angle ? 90.0 : 180.0);
        color = CRgbaColor::RotateColor(color, rotate_angle); 
    } // ITERATE


    // propagate colors
    const CPhyloTreeCalculator::TClusterHash& cluster_map = m_Calc->GetClusters();
    ITERATE(CPhyloTreeCalculator::TClusterHash, cl, cluster_map) {
        // getting min x of each cluster
        int minX = m_Calc->GetWidth();       

        ITERATE (vector<TTreeIdx>, node_iter, cl->second) {
            if ((*m_TreeModel)[*node_iter].HasParent()) {
                CPhyloTreeNode& parent = m_TreeModel->GetParent((*m_TreeModel)[*node_iter]);

                if ((*parent).IDX().first < minX) {
                    minX = (*parent).IDX().first;    
                }
            }
        }

        color_idx = m_ClusterToColorMap[cl->first];
        bool selection_cluster = (cluster_id_to_selection_map.find(cl->first) != cluster_id_to_selection_map.end());

        // Selection clusters propogate all the way to the root.  Standard clusters
        // (cluster-id property) propogate to nearest common ancester.  Also standard clusters
        // are only seen when coloration mode is 'cluster'
        if (selection_cluster) 
            minX = 0;
        else if (scheme->GetColoration()!=CPhyloTreeScheme::eClusters)
            continue;

        ITERATE (vector<TTreeIdx>, node_iter, cl->second) {          
            TTreeIdx parent_idx = *node_iter;

            // if it is not lowest common node, mark parents       
            for (; (*m_TreeModel)[parent_idx].HasParent(); 
                parent_idx = (*m_TreeModel)[parent_idx].GetParent()) {

                    CPhyloTreeNode& cursor = ((*m_TreeModel)[parent_idx]);
                    if ((*cursor).IDX().first > minX) {

                        // If its the primary cluster-id, update cluster colors.
                        // If there are multiple cluster id's in the node add a marker
                        // if were are visiting parents for > 1 time... ignore.  Only multi-mark
                        // the selected nodes themselves, and only visit parents of dominant
                        // color. (first sel color or, if none, cluster-id).
                        int primary_cluster_id = (*cursor).GetPrimaryCluster();                        
                        if (parent_idx == *node_iter) {                            
                            if (primary_cluster_id == cl->first) {
                                (*cursor).SetClusterColorIdx(color_idx);                          
                            }
                            if (cursor.IsLeaf() && (*cursor).GetNumClusters() > 1) {
                                // only include selection colors in the set of colors for
                                // markers, and only apply markers to leaf nodes.
                                if (selection_cluster) {
                                    // Marker size is a multiple of node size, so just use 2 here (double node size):
                                    (*cursor).SetMarkerSize(2.0f);
                                    (*cursor).GetMarkerColors().push_back(
                                         m_TreeModel->GetColorTable()->GetColor(color_idx));
                                 }
                            }
                        }
                        else {
                            (*cursor).SetClusterColorIdx(color_idx);                          
                        }
                    }
                    else {                     
                        break;
                    }
            }
        }
    }

    SetColorIndices(scheme); 
}

void CPhyloTreeDataSource::ReRoot(TTreeIdx root_idx)
{
    m_TreeModel->ReRoot(root_idx);

    // root node has 0 distance since it has no parent (and distance stored in a node is
    // the node's distance from it's parent)
    m_TreeModel->GetNode(root_idx).GetValue().SetDistance(0.0f);
    m_TreeModel->GetNode(root_idx).SetParent(CPhyloTree::Null());
    m_TreeModel->GetNode(root_idx).GetValue().Sync(m_TreeModel->GetFeatureDict());
}

void CPhyloTreeDataSource::ReRootEdge(TTreeIdx edge_child_node)
{
    // We can still re-root if there is not distance attribute. But
    // if there is, we need to update it and split the distance 50%
    // on either side of the new node.
    float dist = 0.0f;
    if (m_TreeModel->GetFeatureDict().HasFeature("dist"))
        dist = m_TreeModel->GetNode(edge_child_node).GetValue().GetDistance();
    
    // Create the new node to be the root:
    m_TreeModel->SetCurrentNode(edge_child_node);
    TTreeIdx new_node_idx = NewNode(false);

    // If there is a distance attribute, allocate 1/2 the distance from the child
    // to the new node, and the other half from the new node to the child's parent
    if (m_TreeModel->GetFeatureDict().HasFeature("dist")) {
        m_TreeModel->GetNode(new_node_idx).GetValue().SetDistance(dist/2.0f);
        m_TreeModel->GetNode(new_node_idx).GetValue().Sync(m_TreeModel->GetFeatureDict());
        m_TreeModel->GetNode(edge_child_node).GetValue().SetDistance(dist/2.0f);
        m_TreeModel->GetNode(edge_child_node).GetValue().Sync(m_TreeModel->GetFeatureDict());
    }
    ReRoot(new_node_idx);
    m_TreeModel->SetCurrentNode(CPhyloTree::Null());
}

void CPhyloTreeDataSource::ReRootMidpoint()
{
    if (!m_TreeModel->GetFeatureDict().HasFeature("dist"))
        return;

    CPhyloTreeDistFromRoot child_dist = TreeDepthFirst(
            m_TreeModel.GetNCObject(),
            m_TreeModel->GetRootIdx(),
            CPhyloTreeDistFromRoot(m_TreeModel.GetNCPointer()));

    CPhyloTreeMidpointDist midpoint_dist = TreeDepthFirst(m_TreeModel.GetNCObject(),
        m_TreeModel->GetRootIdx(),
        CPhyloTreeMidpointDist(m_TreeModel.GetNCPointer(), 
                               child_dist.GetDistances(),
                               child_dist.GetMaxDistNode()));

    float dist;
    std::vector<CPhyloTree::TTreeIdx> path;

    midpoint_dist.GetLongest(path, dist);
    float midpoint = dist / 2.0f;
    float d = 0.0f;

    if (path.size() > 1) {
        TTreeIdx midpoint_parent = CPhyloTree::Null();        
        TTreeIdx midpoint_child = CPhyloTree::Null();
        float dist_from_parent = 0.0f;
        float dist_from_child = 0.0f;

        for (size_t i=0; i < path.size(); ++i) {
            TNodeType& node = m_TreeModel->GetNode(path[i]);

            // Find middle of path, based on distances. Distances are stored in the child node as distance 
            // to the parent, so we have to check at each node along the path which is parent and which is 
            // child since it switches at the least common ancestor - the highest node in the tree that
            // the two leaves at either end of 'path' have in common.  Once we identify the midpoint,
            // we may stop this loop. (but we run to the end to highlight nodes for debugging)
            if (i < path.size() - 1 && midpoint_child == CPhyloTree::Null()) {

                TNodeType& next_node = m_TreeModel->GetNode(path[i + 1]);

                // If next node is parent of this node, distance is in this node.
                if (node.GetParent() == path[i + 1]) {
                    d += node.GetValue().GetDistance();

                    if (d >= midpoint) {
                        midpoint_child = path[i];
                        midpoint_parent = path[i + 1];

                        float base_distance = d - node.GetValue().GetDistance();
                        dist_from_parent = d - midpoint;
                        dist_from_child = midpoint - base_distance;
                    }
                }
                // If this node is parent of the next node, distance is in the next node
                else if (next_node.GetParent() == path[i]) {
                    d += next_node.GetValue().GetDistance();

                    if (d >= midpoint) {
                        midpoint_parent = path[i];
                        midpoint_child = path[i + 1];

                        float base_distance = d - next_node.GetValue().GetDistance();
                        dist_from_parent = midpoint - base_distance;
                        dist_from_child = d - midpoint;
                    }
                }
                else {
                    /// Error - either one or the other is a parent
                    _ASSERT(0);
                }
            }

            /*  For debugging: highlight the path we found
            node.GetValue().SetFeature(
                m_TreeModel->GetFeatureDict(), "$NODE_COLOR", "[255 0 0 255]");
            node.GetValue().InitFeatures(
                m_TreeModel->GetFeatureDict(), m_TreeModel->GetColorTable());
            */
        }


        if (midpoint_child != CPhyloTree::Null()) {
            // It is possible the tree is already mid-point rooted. If the 
            // midpoint is 'close' to an existing node, make
            // that the root if it is not already (and write info message)
            // Now that node has at least 2 children by definition. If it
            // has more I think we accept that - it is possible to have
            // the midpoint lie at an n-node intersection
            
            // What is a 'close'? Let's say 1/100 of average edge length. 
            // Since we now know the maximum distance between 2 leaves and the
            // number of edges between them, we could set 'close' to be 1/100
            // of the length of an average edge, i.e. given 10 edges in the path
            // and the total path length of 0.7, 'small' is < (0.7/10)/100
            float close = (dist/float(path.size() - 1))/100.0f;
            TTreeIdx close_idx = CPhyloTree::Null();
            if (dist_from_parent <= close)
                close_idx = midpoint_parent;
            else if (dist_from_child <= close)
                close_idx = midpoint_child;

            if (close_idx != CPhyloTree::Null()) {
                TNodeType& midpoint = m_TreeModel->GetNode(close_idx);
                if (!midpoint.HasParent()) {
                    LOG_POST(Info << "Tree already rooted at midpoint");
                    return;
                }
                else {
                    ReRoot(close_idx);
                    LOG_POST(Info << "Re-rooted tree at existing midpoint");
                    return;
                }
            }
            else {
                // Set current node to child node (midpoint child)
                // Call newnode with false to insert between parent and child
                // set new nodes distance to dist_from_parent
                // set midpoint_child's distance to dist_from_child
                // Re-root tree at new node.
                m_TreeModel->SetCurrentNode(midpoint_child);
                TTreeIdx new_node_idx = NewNode(false);
                m_TreeModel->GetNode(new_node_idx).GetValue().SetDistance(dist_from_parent);
                m_TreeModel->GetNode(new_node_idx).GetValue().Sync(m_TreeModel->GetFeatureDict());
                m_TreeModel->GetNode(midpoint_child).GetValue().SetDistance(dist_from_child);
                // This also can be done via  CPhyloNodeData::Sync(feature_dict) but we don't want to sync the
                // label which may or may not be initialized at this point
                string str_dist;
                NStr::DoubleToString(str_dist, dist_from_child);
                m_TreeModel->GetNode(midpoint_child).GetValue().SetFeature(m_TreeModel->GetFeatureDict(), "dist", str_dist);
                ReRoot(new_node_idx);
                m_TreeModel->SetCurrentNode(CPhyloTree::Null());
            }
        }
    }

}

/// Collapse, based on distance, enough nodes in the tree to get the total
/// number of leaves down to the requested number. (or just over if exact 
/// match is not possible).  We do not expand nodes that may already be
/// collapsed.
set<CPhyloNodeData::TID> 
CPhyloTreeDataSource::CollapseByDistance(int leaf_count_target, SCollapsable* collapse_func)
{
    set<CPhyloNodeData::TID> collapsed_nodes;

    if (!m_TreeModel->GetFeatureDict().HasFeature("dist"))
        return collapsed_nodes;

    // Get distance of each node from root to determine which should be collapsed.
    // distance here is max distance of any direct child of the node from root
    CPhyloTreeMaxDirectChildDist child_dist =
        TreeDepthFirst(m_TreeModel.GetNCObject(),
        m_TreeModel->GetRootIdx(),
        CPhyloTreeMaxDirectChildDist(m_TreeModel.GetNCPointer(), collapse_func));

    vector<SChildMaxDist> distances = child_dist.GetDistances();

    // sort by distance (least to greatest)
    std::sort(distances.begin(), distances.end());
    int current_leaf_count = m_TreeModel->GetRoot()->GetNumLeavesEx();

    // 
    while (current_leaf_count > leaf_count_target) {
        vector<SChildMaxDist>::reverse_iterator riter = distances.rbegin();

        // pick the node with the most distant direct child (exclude any nodes
        // with subtrees).
        for (; riter != distances.rend(); ++riter) {
            TNodeType& n = m_TreeModel->GetNode((*riter).m_NodeIdx);

            bool has_subtree = false;
            // make sure node only has direct children (leaf nodes or collapsed nodes)
            // and do not include the root node.
            for (size_t i = 0; i < n.GetChildren().size(); ++i) {
                TNodeType& child_node = m_TreeModel->GetNode(n.GetChildren()[i]);
                if (child_node.IsLeafEx())
                    continue;
                else if (collapsed_nodes.find(child_node->GetId()) == collapsed_nodes.end()) {
                    has_subtree = true;
                    break;
                }
            }
            if (!has_subtree)
                break;
        }

        if (riter == distances.rend())
            break;

        TNodeType& n = m_TreeModel->GetNode((*riter).m_NodeIdx);

        // Collapse nodes in order of most distant to least.  Distance is based on
        // the maximum distance of any of the nodes immediate children (whether or
        // not they are leaves).  Using this approach, we should never collapse 
        // a node that has a non-leaf child that is not already collapsed.
        if (n.CanExpandCollapse(CPhyloNodeData::eHideChildren)) {
            // We only want to show top-level nodes as collapsed, so remove
            // from the set of collapsed nodes any children of the node
            // we have chosen to collapse.
            for (size_t i = 0; i < n.GetChildren().size(); ++i) {
                TNodeType& child_node = m_TreeModel->GetNode(n.GetChildren()[i]);

                set<CPhyloNodeData::TID>::iterator iter;
                iter = collapsed_nodes.find(child_node->GetId());
                if (iter != collapsed_nodes.end()) {
                    collapsed_nodes.erase(iter);
                }
            }

            collapsed_nodes.insert(n->GetId());

            // When you collapse a node that only has leaves or collapsed nodes as children,
            // You reduce the number of leaves by the number of its leaves-1 because it
            // is now a leaf.
            current_leaf_count -= n.GetChildren().size() - 1;
        }

        distances.erase(--riter.base());
    }

    return collapsed_nodes;
}

void CPhyloTreeDataSource::Relabel(CPhyloTreeScheme* scheme, 
                                   string labelFmt)
{
    m_Calc->Init(m_TreeModel->GetColorTable());
    m_Calc->SetLabelFormat(labelFmt);
    *m_Calc = TreeDepthFirst(m_TreeModel.GetNCObject(), m_TreeModel->GetRootIdx(), *m_Calc);
    m_TreeModel->SetNumNodes(m_Calc->GetNumNodes());

    Clusterize(scheme);

    int max_children = std::max(10, m_Calc->GetHeight() / 2);
    scheme->SetMaxNumChildren(GLdouble(max_children));
    scheme->SetMaxBranchDist(m_Calc->GetMaxDistance());
}

void CPhyloTreeDataSource::Sort(bool ascending)
{
    TreeDepthFirst(m_TreeModel.GetNCObject(), 
        m_TreeModel->GetRootIdx(), 
        CPhyloTreeSorter(m_TreeModel.GetPointer(), ascending));

    MeasureTree();
}

void CPhyloTreeDataSource::SortDist(bool ascending)
{
    if (!m_TreeModel->GetFeatureDict().HasFeature("dist"))
        return;

    CPhyloTreeMaxChildDist child_dist = 
        TreeDepthFirst(m_TreeModel.GetNCObject(), 
                       m_TreeModel->GetRootIdx(), 
                       CPhyloTreeMaxChildDist(m_TreeModel.GetNCPointer()));

    TreeDepthFirst(m_TreeModel.GetNCObject(), 
        m_TreeModel->GetRootIdx(), 
        CPhyloTreeSorterSubtreeDist(m_TreeModel.GetNCPointer(), child_dist.GetDistances(), ascending));

    MeasureTree();
}

void CPhyloTreeDataSource::SortLabel(bool ascending)
{
    TreeDepthFirst(m_TreeModel.GetNCObject(), 
        m_TreeModel->GetRootIdx(), 
        CPhyloTreeSorterLabel(m_TreeModel.GetNCPointer(), ascending));

    MeasureTree();
}

void CPhyloTreeDataSource::SortLabelRange(bool ascending)
{
    CPhyloTreeLabelRange label_ranges = 
        TreeDepthFirst(m_TreeModel.GetNCObject(), 
                       m_TreeModel->GetRootIdx(), 
                       CPhyloTreeLabelRange(m_TreeModel.GetNCPointer(), ascending));

    TreeDepthFirst(m_TreeModel.GetNCObject(), 
        m_TreeModel->GetRootIdx(), 
        CPhyloTreeSorterLabelRange(m_TreeModel.GetNCPointer(), label_ranges.GetLabelRanges(), ascending));

    MeasureTree();
}

TModelRect CPhyloTreeDataSource::GetBoundRect(void)
{
    // rectangle calculator
    CPhyloTreeRectCalculator rect_calc(m_TreeModel);
    rect_calc.Init();
    rect_calc = TreeDepthFirst(m_TreeModel.GetNCObject(), m_TreeModel->GetRootIdx(), rect_calc);
    return rect_calc.GetRect();
}

void CPhyloTreeDataSource::Clean()
{
    // Convert to biocontainer to get user data
    CRef<objects::CBioTreeContainer> btc(new objects::CBioTreeContainer());
    CRef<objects::CBioTreeContainer> new_container(new CBioTreeContainer());
    TreeConvert2Container(*new_container, *GetTree());

    // Now convert tree datastructure to biotreecontainer, skipping over any
    // single child nodes
    TreeConvertNonSingleChild2Container(*btc, *GetTree(), GetTree()->GetRootIdx());

    // Add user data to new biotreecontainer
    if (new_container->IsSetUser()) {
        btc->SetUser().Assign(new_container->GetUser());
    }

    // Initialize tree with new biotreecontainer
    Init(*btc, *m_Scope, false);
    GetModel().GetCollisionData().Clear();
}

void CPhyloTreeDataSource::Filter()
{
    // not currently hooked up to UI (and would have problems - needs to fix child pointers..)
    CPhyloTreeFilter_Selector selector(m_TreeModel.GetNCPointer());
    selector = TreeDepthFirstInvarient(m_TreeModel.GetNCObject(), m_TreeModel->GetRootIdx(), selector);

    MeasureTree();
}


void CPhyloTreeDataSource::FilterDistances(double x_dist)
{
    // not currently hooked up to UI (and would have problems - needs to fix child pointers..)
    CPhyloTreeFilter_Distance dfilter(m_TreeModel.GetNCPointer(), x_dist);
    dfilter = TreeDepthFirstInvarient(m_TreeModel.GetNCObject(), m_TreeModel->GetRootIdx(), dfilter);

    MeasureTree();
}



string CPhyloTreeDataSource::GetColumnLabel(size_t col) const
{ 
    const CBioTreeFeatureDictionary:: TFeatureDict& fdict = 
        m_TreeModel->GetFeatureDict().GetFeatureDict();
    CBioTreeFeatureDictionary::TFeatureDict::const_iterator fiter;

    size_t count = 0;
    for (fiter=fdict.begin(); fiter != fdict.end(); ++fiter, ++count) {
        if (count == col) {
            return (*fiter).second; 
        }
    }

    return "";
}

size_t CPhyloTreeDataSource::GetColsCount() const  
{ 
    return m_TreeModel->GetFeatureDict().GetFeatureDict().size(); 
}

CMacroQueryExec* CPhyloTreeDataSource::GetQueryExec(bool casesensitive, CStringMatching::EStringMatching matching)
{
    CTreeQueryExec* qexec = new CTreeQueryExec(&(this->GetDictionary()));
       
    qexec->SetTree(this->GetTree());

    // Logical operators:
    qexec->AddFunc(CQueryParseNode::eAnd,
            new CQueryFuncPromoteAndOr());
    qexec->AddFunc(CQueryParseNode::eOr,
            new CQueryFuncPromoteAndOr());
    qexec->AddFunc(CQueryParseNode::eSub,
            new CQueryFuncPromoteLogic());
    qexec->AddFunc(CQueryParseNode::eXor,
            new CQueryFuncPromoteLogic());
    qexec->AddFunc(CQueryParseNode::eNot,
            new CQueryFuncPromoteLogic());

    // Constants:
    qexec->AddFunc(CQueryParseNode::eIntConst,
            new CQueryFuncPromoteValue());
    qexec->AddFunc(CQueryParseNode::eFloatConst,
            new CQueryFuncPromoteValue());
    qexec->AddFunc(CQueryParseNode::eBoolConst,
            new CQueryFuncPromoteValue());
    qexec->AddFunc(CQueryParseNode::eString,
            new CQueryFuncPromoteValue());

    NStr::ECase cs = casesensitive ? NStr::eCase  : NStr::eNocase;

    // Comparison operators:
    qexec->AddFunc(CQueryParseNode::eEQ,
            new CQueryFuncPromoteEq(cs, matching));
    qexec->AddFunc(CQueryParseNode::eGT,
            new CQueryFuncPromoteGtLt(CQueryParseNode::eGT, cs));
    qexec->AddFunc(CQueryParseNode::eGE,
            new CQueryFuncPromoteGtLt(CQueryParseNode::eGE, cs));
    qexec->AddFunc(CQueryParseNode::eLT,
            new CQueryFuncPromoteGtLt(CQueryParseNode::eLT, cs));
    qexec->AddFunc(CQueryParseNode::eLE,
            new CQueryFuncPromoteGtLt(CQueryParseNode::eLE, cs));
    qexec->AddFunc(CQueryParseNode::eIn,
            new CQueryFuncPromoteIn(cs, matching));
    qexec->AddFunc(CQueryParseNode::eBetween,
            new CQueryFuncPromoteBetween(cs));
    qexec->AddFunc(CQueryParseNode::eLike,
            new CQueryFuncLike(cs));

    // Functions
    qexec->AddFunc(CQueryParseNode::eFunction,
            new CQueryFuncFunction());
    qexec->AddFunc(CQueryParseNode::eIdentifier,
        new CQueryFuncPromoteIdentifier());
    // Unusual mapping: Run time vars ->  CQueryParseNode::eSelect
    // This is done to preserve CQueryParseNode from modification.
    qexec->AddFunc(CQueryParseNode::eSelect,  // RT Variable
            new CQueryFuncRTVar());
    qexec->AddFunc(CQueryParseNode::eFrom,   // Assignment operator
            new CQueryFuncAssignment());

    return qexec;
}

void CPhyloTreeDataSource::SetQueryResults(CMacroQueryExec* q)
{
    CTreeQueryExec *e = dynamic_cast<CTreeQueryExec*>(q);

    ClearQueryResults();
    m_TreeModel->ClearSelection();
    m_TreeModel->SetSelection(e->GetTreeSelected(), false, true);
}

void CPhyloTreeDataSource::ClearQueryResults()
{ 
    m_SearchCurrentNode = CPhyloTree::Null(); 
}

void CPhyloTreeDataSource::ExecuteStringQuery(const string &query, 
                                              size_t& num_selected, 
                                              size_t& num_queried, 
                                              CStringMatching::EStringMatching string_matching, 
                                              NStr::ECase use_case)
{
    // Re-run the query if options that can change query results have changed
    m_SearchCurrentNode = CPhyloTree::Null();
    num_queried = 0;
    num_selected = 0;

    m_StringQueryIDs.clear();
        
    // simple string queries are completed synchronously since
    // they can never get hung up in network access.
    if (query != "") {
        vector<TTreeIdx> sel = FindNodes(query, num_queried, string_matching, use_case);
        m_TreeModel->ClearSelection();

        // Because of selecting parents this can lose the fact that some
        // non leaf nodes were selected.
        m_TreeModel->SetSelection(sel, false, true);
        num_selected = sel.size();

        // Be a bit more efficient to get these during query if we decide we have to keep this.
        m_StringQueryIDs.reserve(sel.size());
        for (auto iter=sel.begin(); iter!=sel.end(); ++iter) {
            m_StringQueryIDs.push_back(m_TreeModel->GetNode(*iter).GetValue().GetId());
        }

        LOG_POST(Info << "String Query: " << query << " Num selected: " << sel.size());
    }
}

class visitor_stringmatch_query
{
public:
    typedef CPhyloTree::TTreeIdx TTreeIdx;

public:
    visitor_stringmatch_query(CStringMatching  &stringMatching, vector<TTreeIdx> &selNodes, size_t &numQueried) :  
        m_StringMatching(stringMatching),
        m_SelNodes(selNodes),
        m_NumQueried(numQueried)
    {}
    ETreeTraverseCode operator()(CPhyloTree& tree, 
                                 TTreeIdx node, int delta)
    {
        if (delta==1 || delta==0){
            ++m_NumQueried;
            CBioTreeFeatureList::TFeatureList f_list = 
                tree[node]->GetBioTreeFeatureList().GetFeatureList();


            ITERATE(CBioTreeFeatureList::TFeatureList, it, f_list) {
                if (m_StringMatching.MatchString(it->value)) {
                    m_SelNodes.push_back(node);
                    break;
                }                     
            }    
        }
        return eTreeTraverse;
    }

private:
    CStringMatching  &m_StringMatching;
    vector<TTreeIdx> &m_SelNodes;
    size_t           &m_NumQueried;
};

vector<CPhyloTree::TTreeIdx> 
CPhyloTreeDataSource::FindNodes(const string &query, size_t& num_queried, CStringMatching::EStringMatching string_matching, NStr::ECase use_case) const
{
    vector<TTreeIdx> selNodes;
    CStringMatching stringMatching(query, string_matching, use_case);
    visitor_stringmatch_query finder(stringMatching, selNodes, num_queried);
    TreeDepthFirst(m_TreeModel.GetNCObject(), finder);
    return selNodes;
}

// This sorts nodes by their position (depth-first order) in the tree using
// the node index which represents the position of the node relative to other 
// nodes.
struct NodeIdxSort {
    NodeIdxSort(const CPhyloTree& t) : m_Tree(t) {};
    bool operator()(CPhyloTree::TTreeIdx lhs, CPhyloTree::TTreeIdx rhs) const {
        const CPhyloTree::TNodeType& n1 = m_Tree[lhs];
        const CPhyloTree::TNodeType& n2 = m_Tree[rhs];

        if (n1.GetValue().IDX().second < n2.GetValue().IDX().second)
            return true;
        else if (n1.GetValue().IDX().second > n2.GetValue().IDX().second)
            return false;
        // first value was equal:
        else if (n1.GetValue().IDX().first < n2.GetValue().IDX().first)
            return true;
        else return false;
    }

protected:
    const CPhyloTree& m_Tree;
};

CPhyloTree::TTreeIdx 
CPhyloTreeDataSource::IterateOverSelNodes(int direction, bool highlight)
{
    // highlight
    if (m_TreeModel->GetRootIdx() == CPhyloTree::Null())
        return CPhyloTree::Null();

    // Get all nodes user 'explicitly' selected - so either the user clicked on
    // them directly (does not count if they are the child of a selected node) or
    // the node was directly selected by a query
    vector<TTreeIdx> search_cache;
    m_TreeModel->GetExplicitlySelectedAndNotCollapsed(search_cache);

    // Sort the nodes into depth-first order
    std::sort(search_cache.begin(), search_cache.end(), NodeIdxSort(m_TreeModel.GetObject()));

    if (search_cache.empty())
        return CPhyloTree::Null(); 

    // cursor
    if (direction==0) {
        if (m_SearchCurrentNode == CPhyloTree::Null()) {
            m_SearchCurrentNode = (*search_cache.begin());
        }
    }
    else if (direction>0) {
        if (m_SearchCurrentNode == CPhyloTree::Null()) {
            m_SearchCurrentNode = (*search_cache.begin());
        }
        else {
            vector<TTreeIdx>::iterator itt = 
                find(search_cache.begin(), search_cache.end(), m_SearchCurrentNode);

            // If not found (unexpected) set cursor to beginning.
            if (itt == search_cache.end()) {
                m_SearchCurrentNode = (*search_cache.begin());
            }
            // else increment unless we are already at the end.
            else {
                ++itt;
                if (itt != search_cache.end())
                    m_SearchCurrentNode = *itt;
                else // wrap around to the beginning
                    m_SearchCurrentNode = (*search_cache.begin());
            }
        }
    }
    else {
        if (m_SearchCurrentNode == CPhyloTree::Null()) {
            m_SearchCurrentNode = *(search_cache.begin() + (search_cache.size() - 1));
        }
        else {
            vector<TTreeIdx>::iterator itt = 
                find(search_cache.begin(), search_cache.end(), m_SearchCurrentNode);

            // If not found (unexpected) set cursor to the end
            if (itt == search_cache.end()) {
                m_SearchCurrentNode = *(search_cache.begin() + (search_cache.size() - 1));
            }
            // else decrement cursor if not already at the beginning
            else {                
                if (itt != search_cache.begin())
                    m_SearchCurrentNode = *(--itt);
                else // wrap around to the end
                    m_SearchCurrentNode = search_cache[search_cache.size() - 1];                
            }
        }
    }

    // Make the node we have iterated to the current node -this will give it
    // a small visual marker (square) around the node so user knows where they are.
    if (m_SearchCurrentNode)
        m_TreeModel->SetCurrentNode(m_SearchCurrentNode);

    return m_SearchCurrentNode;
}

void CPhyloTreeDataSource::UpdateSelectionSets(CPhyloTreeScheme* scheme)
{
    // renumber selection cluster IDs in set to make sure the selection cluster IDs
    // don't overlap regular cluster IDs:
    // pick cluster id larger than existing ids:
    CPhyloTree::TClusterID max_id =
        GetMaxClusterID() + TClusterID(500 + m_TreeModel->GetSelectionSets().GetSets().size());
    // set ids, first highest then lower.
    GetSelectionSets().RenumberClusterIDs(max_id);

    m_TreeModel->GetSelectionSets().SetSelectionSetProperty(m_TreeModel.GetPointer());
    MeasureTree();

    // Check max-id one more time. We do this because MeasureTree() updates the value
    // returned by GetMaxClusterID() and there is a small chance that this value has
    // increased since the tree was created. (change would be via editing of node properties)
    if (GetMaxClusterID() >= max_id - TClusterID(m_TreeModel->GetSelectionSets().GetSets().size())) {
        GetSelectionSets().RenumberClusterIDs(GetMaxClusterID() + 500 + static_cast<int>(m_TreeModel->GetSelectionSets().GetSets().size()));
        m_TreeModel->GetSelectionSets().SetSelectionSetProperty(m_TreeModel.GetPointer());
        MeasureTree();
    }

    Clusterize(scheme);
}

class visitor_detach_subtree
{
public:
    visitor_detach_subtree(){}
    ETreeTraverseCode operator()(CPhyloTree&  tree, CPhyloTree::TTreeIdx node, int delta)
    {
        if (delta==1 || delta==0){
            tree[node].GetValue().SetId(CPhyloNodeData::TID(-1));
        }
        return eTreeTraverse;
    }
};

class visitor_copy_subtree
{
public:
    typedef CPhyloTree TTreeType;
    typedef CPhyloTree::TTreeIdx TTreeIdx;
    typedef CPhyloTree::TNodeType TNodeType;

public:
    visitor_copy_subtree(CPhyloTree& tree, CPhyloTree& target)
    : m_Target(target)
    {
        m_Target.GetFeatureDict() = tree.GetFeatureDict();
        m_Target.SetRootIdx(0);
    }
    ETreeTraverseCode operator()(CPhyloTree& tree, 
                                 CPhyloTree::TTreeIdx node_idx, 
                                 int delta)
    {
        if (delta < 0) {
            return eTreeTraverse;
        }

        TNodeType& node = tree[node_idx];
        CPhyloNodeData::TID id = node.GetValue().GetId();
        
        // Make sure not already in tree (but traversal should guarantee)
        TTreeIdx idx = m_Target.FindNodeById(id);
        if (idx != CPhyloTreeNode::Null()) {
            return eTreeTraverse;
        }

        // Adds a copy of node.  Need to update indices to match the target tree
        TTreeIdx new_node_idx = m_Target.AddNode(node);
        TNodeType& new_node = m_Target[new_node_idx];
        new_node.ClearConnections();
        
        // Look up the parent index of the new node using the 
        // node id
        CPhyloNodeData::TID parent_id = tree[node.GetParent()]->GetId();
        TTreeIdx parent_idx = m_Target.FindNodeById(parent_id);
        
        // This will only happen for the top (first) node of the 
        // subtree being cut since its parent won't be in the subtree
        if (parent_idx == CPhyloTreeNode::Null()) {            
            return eTreeTraverse;
        }
        m_Target.AddChild(parent_idx, new_node_idx);

        return eTreeTraverse;
    }

    CPhyloTree& m_Target;
};

class visitor_paste_subtree
{
public:
    typedef CPhyloTree TTreeType;
    typedef CPhyloTree::TTreeIdx TTreeIdx;
    typedef CPhyloTree::TNodeType TNodeType;

public:
    visitor_paste_subtree(CPhyloTree& source, CPhyloTree& target, TTreeIdx target_idx)
    : m_Target(target)
    , m_Source(source)
    , m_TargetIdx(target_idx)
    {
        CPhyloTreeMaxIdCalculator next_id(&m_Target);
        next_id = TreeDepthFirst(m_Target, next_id);
        m_TargetMaxId = next_id.GetMaxId();
    }
    // This is iterating over the source tree adding each 
    // element to the target tree (m_Target)
    ETreeTraverseCode operator()(CPhyloTree& tree, 
                                 CPhyloTree::TTreeIdx node_idx, 
                                 int delta)
    {
        if (delta < 0) {
            return eTreeTraverse;
        }

        // Node from source tree (the tree we are copying into the target tree)
        TNodeType& node = tree[node_idx];
        CPhyloNodeData::TID source_id = node.GetValue().GetId();

        // Adds a copy of node.  Need to update indices to match the target tree
        TTreeIdx new_node_idx = m_Target.AddNode(node);
        TNodeType& new_node = m_Target[new_node_idx];
        new_node.ClearConnections();  

        CPhyloNodeData::TID target_id = ++m_TargetMaxId;
        m_IdMap[source_id] = target_id;

        new_node->SetId(target_id);
        new_node.GetValue().GetBioTreeFeatureList() = CBioTreeFeatureList();

        // Add any features in in dictionary of source but not target to target.
        // Get the id for the name each time too since ids between the two
        // trees may not match.
        ITERATE(CBioTreeFeatureList::TFeatureList, it,
                node->GetBioTreeFeatureList().GetFeatureList()) {
            // Use the id for the feature to get the feature name     
            string feature_name = m_Source.GetFeatureDict().GetName(it->id);
            TBioTreeFeatureId id = m_Target.GetFeatureDict().Register(feature_name);
            new_node.GetValue().GetBioTreeFeatureList().SetFeature(id, it->value);
        }

        // If this is the root of the source tree, attach it to the node
        // m_TargetIdx in the target tree. Otherwise attach it to the
        // corresponding node copied from the source tree using the id-to-id map
        if (node.GetParent() == CPhyloTreeNode::Null()) {
            m_Target.AddChild(m_TargetIdx, new_node_idx);
        }
        else {
            CPhyloNodeData::TID parent_id = tree[node.GetParent()]->GetId();
            CPhyloNodeData::TID target_tree_parent_id = m_IdMap[parent_id];
            TTreeIdx parent_idx = m_Target.FindNodeById(target_tree_parent_id);

            if (parent_idx != CPhyloTreeNode::Null()) {
                m_Target.AddChild(parent_idx, new_node_idx);
            }
            else {
                LOG_POST(Info << "Error - did not find parent node as expected.");
            }
        }        
        
        return eTreeTraverse;
    }

    CPhyloTree& m_Target;
    CPhyloTree& m_Source;
    TTreeIdx m_TargetIdx;

    /// mapping from Ids in source tree to target tree
    map<CPhyloNodeData::TID, CPhyloNodeData::TID> m_IdMap;

    CPhyloNodeData::TID m_TargetMaxId;
};



void CPhyloTreeDataSource::Cut()
{
    TTreeIdx node_idx = m_TreeModel->GetCurrentNodeIdx();

    if (node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::Cut - Nothing is selected");
        return;
    }

    if (node_idx == m_TreeModel->GetRootIdx()) {
        _TRACE("CPhyloTreeDataSource::Cut - Removing root item is illegal");
        return;
    }
    
    m_sTreeClipboard.Clear();   

    CPhyloTree::TNodeType& n = m_TreeModel->GetCurrentNode();

    m_TreeModel->SetSelection(n.GetParent(), true, true);

    TreeDepthFirst(m_TreeModel.GetNCObject(), node_idx, 
        visitor_copy_subtree(m_TreeModel.GetNCObject(), m_sTreeClipboard));

    m_TreeModel->ClearSelection();
    m_TreeModel->RemoveChild(n.GetParent(), node_idx);      

    m_TreeModel->UpdateNodesMapping();
    MeasureTree();   
}

void CPhyloTreeDataSource::Paste(void)
{
    TTreeIdx node_idx = m_TreeModel->GetCurrentNodeIdx();

    if (node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::Paste - Nothing is selected");
        return;
    }

    if (m_sTreeClipboard.GetRootIdx() == CPhyloTreeNode::Null()) {
        _TRACE("CPhyloTreeDataSource::Paste - Clipboard is empty");
        return;
    }

    TreeDepthFirst( m_sTreeClipboard,
        visitor_paste_subtree(m_sTreeClipboard, m_TreeModel.GetNCObject(), node_idx));

    m_TreeModel->UpdateNodesMapping();
    MeasureTree();
}

TTreeIdx CPhyloTreeDataSource::NewNode(bool after)
{
    TTreeIdx current_node_idx = m_TreeModel->GetCurrentNodeIdx();

    if (current_node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::NewNode - Nothing is selected");
        return CPhyloTree::Null();
    }

    TTreeIdx parent_node_idx = m_TreeModel->GetNode(current_node_idx).GetParent();

    if (!after && parent_node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::NewNode - New root cannot be added");
        return CPhyloTree::Null();
    }

    TTreeIdx new_node_idx = m_TreeModel->AddNode();
    TNodeType& new_node = m_TreeModel->GetNode(new_node_idx);

    // Set node id to current maximim node id value +1.  IDs needed during export.
    CPhyloTreeMaxIdCalculator next_id(m_TreeModel);
    next_id = TreeDepthFirst(m_TreeModel.GetNCObject(), next_id);
    new_node->SetId(next_id.GetMaxId() + 1);    

    if (after) { // insert as a child
        TNodeType& current_node = m_TreeModel->GetCurrentNode();
        current_node.GetChildren().insert(current_node.SubNodeBegin(), new_node_idx);
        new_node.SetParent(m_TreeModel->GetCurrentNodeIdx());
    }
    else {
        m_TreeModel->RemoveChild(parent_node_idx, current_node_idx);
        m_TreeModel->AddChild(parent_node_idx, new_node_idx);
        m_TreeModel->AddChild(new_node_idx, current_node_idx);
    }
    
    // Set dictionary and a blank feature table with all values from dictionary.
    //new_node.GetValue().SetDictionaryPtr(&(m_TreeModel->GetFeatureDict()));
    // Do we need this - I don't see why... maybe dist?
    ITERATE(CBioTreeFeatureDictionary::TFeatureDict, it,
            m_TreeModel->GetFeatureDict().GetFeatureDict()) {
        new_node.GetValue().SetFeature(m_TreeModel->GetFeatureDict(), it->second, "");
    }

    new_node->Init(m_TreeModel->GetFeatureDict(), m_TreeModel->GetColorTable());

    m_TreeModel->UpdateNodesMapping();
    MeasureTree();
   
    return new_node_idx;
}


void CPhyloTreeDataSource::Remove(bool subtree)
{
    TTreeIdx current_node_idx = m_TreeModel->GetCurrentNodeIdx();
    if (current_node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::Remove - Nothing is selected");
        return;
    }

    TTreeIdx parent_node_idx = m_TreeModel->GetNode(current_node_idx).GetParent();
    if (parent_node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::Remove - The root node can't be removed");
        return;
    }

    m_TreeModel->ClearSelection();
    
    if (subtree) {
        // Remove the node and all it's subnodes
        TreeDepthFirst(m_TreeModel.GetNCObject(), current_node_idx, visitor_detach_subtree());
        m_TreeModel->RemoveChild(parent_node_idx, current_node_idx);      
    }
    else {
        // Remove the node and add all its children to its parent
        TNodeType& current_node = m_TreeModel->GetNode(current_node_idx);

        for(TNodeType::TNodeList_I  it = current_node.SubNodeBegin();
                                    it != current_node.SubNodeEnd(); it++ )  {
            m_TreeModel->AddChild(parent_node_idx, *it);
        }

        current_node.ClearConnections();
        m_TreeModel->RemoveChild(parent_node_idx, current_node_idx);
        current_node.GetValue().SetId(CPhyloNodeData::TID(-1));  
    }

    m_TreeModel->UpdateNodesMapping();
    MeasureTree(); 
}

void CPhyloTreeDataSource::RemoveSelected()
{
    vector<CPhyloNodeData::TID> sel;
    m_TreeModel->GetExplicitlySelectedIDs(sel);

    if (sel.size() == 0) {
        _TRACE("CPhyloTreeDataSource::RemoveSelected() - Nothing is selected");
        return;
    }

    // Make sure root node is not selected
    for (size_t i = 0; i < sel.size(); ++i) {
        CPhyloTree::TTreeIdx node_idx = m_TreeModel->FindNodeById(sel[i]);
        if (node_idx != CPhyloTree::Null()) {
            TTreeIdx parent_node_idx = m_TreeModel->GetNode(node_idx).GetParent();
            if (parent_node_idx == CPhyloTree::Null()) {
                _TRACE("CPhyloTreeDataSource::Remove - The root node can't be removed");
                return;
            }
        }
    }

    m_TreeModel->ClearSelection();

    // Delete nodes one at a time based on ID since indices may change in deletion
    // process.  Also, a node may disappear if it is the child of a node that has 
    // already been deleted.
    for (size_t i = 0; i < sel.size(); ++i)
    {
        CPhyloTree::TTreeIdx node_idx = m_TreeModel->FindNodeById(sel[i]);
        if (node_idx != CPhyloTree::Null()) {
            TTreeIdx parent_node_idx = m_TreeModel->GetNode(node_idx).GetParent();            
            TreeDepthFirst(m_TreeModel.GetNCObject(), node_idx, visitor_detach_subtree());
            m_TreeModel->RemoveChild(parent_node_idx, node_idx);
        }
    }

    m_TreeModel->UpdateNodesMapping();
    MeasureTree();
}

void CPhyloTreeDataSource::SetCollapsedLabel(CPhyloTree::TTreeIdx idx)
{
    /*  We update labels for nodes being collapsed only if the tree
    *  support the $PRIORITY (integer) parameter. In this case, we find the
    *  subnode with the highest $PRIORITY value and assign its label to
    *  the collapsed node. In the case that multiple sub-nodes have the same
    *  (highest) value for $PRIORITY, we pick the label of the subnode
    *  closest to the center of the subtree (center being the middle leaf node)
    */
    if (!m_TreeModel->GetFeatureDict().HasFeature("$PRIORITY") ||
        !m_TreeModel->GetFeatureDict().HasFeature("label"))
        return;

    if (idx != CPhyloTree::Null()) {
        CPhyloTree::TNodeType& current = m_TreeModel->GetNode(idx);

        if (current.CanExpandCollapse(CPhyloNodeData::eHideChildren)) {
            CBioTreeFeatureList& features = (*current).GetBioTreeFeatureList();
            TBioTreeFeatureId label_feat_id = m_TreeModel->GetFeatureDict().GetId("label");
            // We do not update labels here.  Only set the label if it is not already set
            if (features.GetFeatureValue(label_feat_id) != "")
                return;

            CPhyloTreePriorityNode  pnode(m_TreeModel, idx);
            pnode = TreeDepthFirst(*m_TreeModel, idx, pnode);
            if (pnode.GetMaxPriorityNode() != CPhyloTree::Null())
            {                
                CBioTreeFeatureList& priority_node_features = 
                    m_TreeModel->GetNode(pnode.GetMaxPriorityNode())->GetBioTreeFeatureList();

                string priority_label = priority_node_features.GetFeatureValue(label_feat_id);
                current->SetLabel(priority_label);

                if (m_TreeModel->GetFeatureDict().HasFeature("label")) {                                        
                    features.SetFeature(label_feat_id, priority_label);
                }
            }
        }
    }
}

void CPhyloTreeDataSource::SetCollapsedLabels(const vector<CPhyloNodeData::TID>& node_ids)
{
    for (size_t i = 0; i < node_ids.size(); ++i) {
        CPhyloTree::TTreeIdx idx = m_TreeModel->FindNodeById(node_ids[i]);
        if (idx != CPhyloTree::Null()) {
            CPhyloTree::TNodeType& current =
                m_TreeModel->GetNode(idx);

            if (current.CanExpandCollapse(CPhyloNodeData::eHideChildren)) {
                SetCollapsedLabel(idx);
            }
        }
    }
}

void CPhyloTreeDataSource::CollapseSelected()
{
    vector<TTreeIdx> sel;
    m_TreeModel->GetExplicitlySelected(sel);
    TTreeIdx root_idx = m_TreeModel->GetRootIdx();

    if (sel.size() == 0) {
        _TRACE("CPhyloTreeDataSource::RemoveSelected() - Nothing is selected");
        return;
    }
   
    // Collapse all  selected nodes.  Do not collapse nodes if they
    // have a collapsed parent or a parent in 'sel' which is also going to be
    // collapsed.
    for (size_t i = 0; i < sel.size(); ++i)
    {
        CPhyloTree::TTreeIdx node_idx = sel[i];
        bool collapse_node = true;

        if (m_TreeModel->GetNode(node_idx).CanExpandCollapse(CPhyloNodeData::eHideChildren)) {
            TTreeIdx parent_node_idx = m_TreeModel->GetNode(node_idx).GetParent();
            while (parent_node_idx != root_idx) {
                // If parent node is already collapsed:
                if (!m_TreeModel->GetNode(parent_node_idx).CanExpandCollapse(CPhyloNodeData::eHideChildren)) {
                    collapse_node = false;
                    break;
                }
                
                // if parent node is also in the list, sel, of nodes to be collapsed:
                if (std::find(sel.begin(), sel.end(), parent_node_idx) != sel.end()) {
                    collapse_node = false;
                    break;
                }

                parent_node_idx = m_TreeModel->GetNode(parent_node_idx).GetParent();
            }

            // no parent nodes were already collapsed, so this node can be collapsed:
            if (collapse_node) {
                SetCollapsedLabel(node_idx);
                m_TreeModel->GetNode(node_idx).ExpandCollapse(m_TreeModel->GetFeatureDict(),
                    CPhyloNodeData::eHideChildren);
            }
        }
    }

    MeasureTree();
}

void CPhyloTreeDataSource::MoveNode(bool up)
{
    TTreeIdx current_node_idx = m_TreeModel->GetCurrentNodeIdx();

    if (current_node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::MoveNode - Nothing is selected");
        return;
    }

    TTreeIdx parent_node_idx = m_TreeModel->GetNode(current_node_idx).GetParent();

    if (parent_node_idx == CPhyloTree::Null()) {
        _TRACE("CPhyloTreeDataSource::MoveNode - The root node can't be moved");
        return;
    }

    TNodeType& parent = m_TreeModel->GetNode(parent_node_idx);

    for(TNodeType::TNodeList_I  it = parent.SubNodeBegin();
                                it != parent.SubNodeEnd(); it++ )  {
        if (*it == current_node_idx) {
            if (up && (it!=parent.SubNodeBegin())) {
                TNodeType::TNodeList_I pre = it--;
                swap(*pre, *it);
                break;
            }
            else {
                TNodeType::TNodeList_I last = parent.SubNodeEnd(); last--;
                if (it != last) {
                    TNodeType::TNodeList_I pst = it++;
                    swap(*pst, *it);
                    break;
                }
            }
        }
    }
}



END_NCBI_SCOPE
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080
0081
0082
0083
0084
0085
0086
0087
0088
0089
0090
0091
0092
0093
0094
0095
0096
0097
0098
0099
0100
0101
0102
0103
0104
0105
0106
0107
0108
0109
0110
0111
0112
0113
0114
0115
0116
0117
0118
0119
0120
0121
0122
0123
0124
0125
0126
0127
0128
0129
0130
0131
0132
0133
0134
0135
0136
0137
0138
0139
0140
0141
0142
0143
0144
0145
0146
0147
0148
0149
0150
0151
0152
0153
0154
0155
0156
0157
0158
0159
0160
0161
0162
0163
0164
0165
0166
0167
0168
0169
0170
0171
0172
0173
0174
0175
0176
0177
0178
0179
0180
0181
0182
0183
0184
0185
0186
0187
0188
0189
0190
0191
0192
0193
0194
0195
0196
0197
0198
0199
0200
0201
0202
0203
0204
0205
0206
0207
0208
0209
0210
0211
0212
0213
0214
0215
0216
0217
0218
0219
0220
0221
0222
0223
0224
0225
0226
0227
0228
0229
0230
0231
0232
0233
0234
0235
0236
0237
0238
0239
0240
0241
0242
0243
0244
0245
0246
0247
0248
0249
0250
0251
0252
0253
0254
0255
0256
0257
0258
0259
0260
0261
0262
0263
0264
0265
0266
0267
0268
0269
0270
0271
0272
0273
0274
0275
0276
0277
0278
0279
0280
0281
0282
0283
0284
0285
0286
0287
0288
0289
0290
0291
0292
0293
0294
0295
0296
0297
0298
0299
0300
0301
0302
0303
0304
0305
0306
0307
0308
0309
0310
0311
0312
0313
0314
0315
0316
0317
0318
0319
0320
0321
0322
0323
0324
0325
0326
0327
0328
0329
0330
0331
0332
0333
0334
0335
0336
0337
0338
0339
0340
0341
0342
0343
0344
0345
0346
0347
0348
0349
0350
0351
0352
0353
0354
0355
0356
0357
0358
0359
0360
0361
0362
0363
0364
0365
0366
0367
0368
0369
0370
0371
0372
0373
0374
0375
0376
0377
0378
0379
0380
0381
0382
0383
0384
0385
0386
0387
0388
0389
0390
0391
0392
0393
0394
0395
0396
0397
0398
0399
0400
0401
0402
0403
0404
0405
0406
0407
0408
0409
0410
0411
0412
0413
0414
0415
0416
0417
0418
0419
0420
0421
0422
0423
0424
0425
0426
0427
0428
0429
0430
0431
0432
0433
0434
0435
0436
0437
0438
0439
0440
0441
0442
0443
0444
0445
0446
0447
0448
0449
0450
0451
0452
0453
0454
0455
0456
0457
0458
0459
0460
0461
0462
0463
0464
0465
0466
0467
0468
0469
0470
0471
0472
0473
0474
0475
0476
0477
0478
0479
0480
0481
0482
0483
0484
0485
0486
0487
0488
0489
0490
0491
0492
0493
0494
0495
0496
0497
0498
0499
0500
0501
0502
0503
0504
0505
0506
0507
0508
0509
0510
0511
0512
0513
0514
0515
0516
0517
0518
0519
0520
0521
0522
0523
0524
0525
0526
0527
0528
0529
0530
0531
0532
0533
0534
0535
0536
0537
0538
0539
0540
0541
0542
0543
0544
0545
0546
0547
0548
0549
0550
0551
0552
0553
0554
0555
0556
0557
0558
0559
0560
0561
0562
0563
0564
0565
0566
0567
0568
0569
0570
0571
0572
0573
0574
0575
0576
0577
0578
0579
0580
0581
0582
0583
0584
0585
0586
0587
0588
0589
0590
0591
0592
0593
0594
0595
0596
0597
0598
0599
0600
0601
0602
0603
0604
0605
0606
0607
0608
0609
0610
0611
0612
0613
0614
0615
0616
0617
0618
0619
0620
0621
0622
0623
0624
0625
0626
0627
0628
0629
0630
0631
0632
0633
0634
0635
0636
0637
0638
0639
0640
0641
0642
0643
0644
0645
0646
0647
0648
0649
0650
0651
0652
0653
0654
0655
0656
0657
0658
0659
0660
0661
0662
0663
0664
0665
0666
0667
0668
0669
0670
0671
0672
0673
0674
0675
0676
0677
0678
0679
0680
0681
0682
0683
0684
0685
0686
0687
0688
0689
0690
0691
0692
0693
0694
0695
0696
0697
0698
0699
0700
0701
0702
0703
0704
0705
0706
0707
0708
0709
0710
0711
0712
0713
0714
0715
0716
0717
0718
0719
0720
0721
0722
0723
0724
0725
0726
0727
0728
0729
0730
0731
0732
0733
0734
0735
0736
0737
0738
0739
0740
0741
0742
0743
0744
0745
0746
0747
0748
0749
0750
0751
0752
0753
0754
0755
0756
0757
0758
0759
0760
0761
0762
0763
0764
0765
0766
0767
0768
0769
0770
0771
0772
0773
0774
0775
0776
0777
0778
0779
0780
0781
0782
0783
0784
0785
0786
0787
0788
0789
0790
0791
0792
0793
0794
0795
0796
0797
0798
0799
0800
0801
0802
0803
0804
0805
0806
0807
0808
0809
0810
0811
0812
0813
0814
0815
0816
0817
0818
0819
0820
0821
0822
0823
0824
0825
0826
0827
0828
0829
0830
0831
0832
0833
0834
0835
0836
0837
0838
0839
0840
0841
0842
0843
0844
0845
0846
0847
0848
0849
0850
0851
0852
0853
0854
0855
0856
0857
0858
0859
0860
0861
0862
0863
0864
0865
0866
0867
0868
0869
0870
0871
0872
0873
0874
0875
0876
0877
0878
0879
0880
0881
0882
0883
0884
0885
0886
0887
0888
0889
0890
0891
0892
0893
0894
0895
0896
0897
0898
0899
0900
0901
0902
0903
0904
0905
0906
0907
0908
0909
0910
0911
0912
0913
0914
0915
0916
0917
0918
0919
0920
0921
0922
0923
0924
0925
0926
0927
0928
0929
0930
0931
0932
0933
0934
0935
0936
0937
0938
0939
0940
0941
0942
0943
0944
0945
0946
0947
0948
0949
0950
0951
0952
0953
0954
0955
0956
0957
0958
0959
0960
0961
0962
0963
0964
0965
0966
0967
0968
0969
0970
0971
0972
0973
0974
0975
0976
0977
0978
0979
0980
0981
0982
0983
0984
0985
0986
0987
0988
0989
0990
0991
0992
0993
0994
0995
0996
0997
0998
0999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638

-