// Copyright (C) 2016 EDF
// All Rights Reserved
// This code is published under the GNU Lesser General Public License (GNU LGPL)
#ifndef MESHTOCOORDINATES_H
#define  MESHTOCOORDINATES_H
#include <Eigen/Dense>

/** \file meshToCoordinates.h
 *  \brief To  a global mesh position, get back the Cartesian coordinates
 *  \author Xavier Warin
 */
namespace StOpt
{

/// \fn void meshToCoordinates( const  Eigen::ArrayXi &  p_nbMesh, const int & nDivInit , const int & iPosition )
/// \param p_nbMesh       number of meshes in each direction
/// \param nDivInit       product of p_nbMesh array values (utilitarian)
/// \param iPosition      Global position in the meshes \f$ = i_0 + i_1 \mbox{p\_nbMesh}(0) + ... + i_{d-1}  \prod_{j=0}^{d-2} \mbox{p\_nbMesh}(j) \f$
/// \return  coord         Coordinate associated to iPosition \f$ (i_0, ..., i_{d-1}) \f$
inline  Eigen::ArrayXi  meshToCoordinates(const  Eigen::ArrayXi   &p_nbMesh,  const int &nDivInit, const int &iPosition)
{
    int rest = iPosition ;
    int nDiv = nDivInit ;
    int nDim = p_nbMesh.size();
    Eigen::ArrayXi coord(nDim);
    for (int id = nDim - 1 ; id >= 1 ; --id)
    {
        coord(id) = rest / nDiv ;
        rest -= coord(id) * nDiv ;
        nDiv /= p_nbMesh(id - 1);
    }
    coord(0) =  rest / nDiv;
    return coord;
}
}
#endif /*MESHTOCOORDINATES_H*/
