//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2016 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
//
#include <DynamXProcessCellDivide.hpp>

// Process to perform cell division.
namespace mgx
{
  bool CellDivide::initialize(QStringList &parms, QWidget *parent)
  {
    // Get the mesh, tissue
    mesh = currentMesh();
    T = &mesh->tissue();

    // Check the mesh type
    if(T->meshType() != "MGX2D")
      throw(QString("Invalid mesh type, must be a 2D cellular mesh"));

    // Process the parameters
    T->processParmsDivide(parms);

    Information::out << "Initialized cell divide." << endl;

    return true;
  }

  // Run a step of cell division
  bool CellDivide::step(Mesh *mesh, Subdivide *sDiv)
  {
    CellTissue &T = mesh->tissue();

    // Check if we need to use selection
    bool useSelect = mesh->activeVertices().size() != mesh->graph().size();
    CellVec D;
    // Find cells over target area that require division
    forall(const cell &c, T.C)
      if(c->area > T.CellMaxArea and (!useSelect or T.getVtx(c)->selected))
        D.push_back(c);

    if(D.empty())
      return false;

    forall(cell d, D)
      T.divideCell(d, sDiv);

    // Update mesh points, edges, surfaces
    mesh->updateAll();   
    return true; 
  }
}

