/*
    GNU Octave level-set package.
    Copyright (C) 2014  Daniel Kraft <d@domob.eu>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* Internal routine for ls_nb_from_geom.  */

#include "Utils.hpp"

#include <octave/oct.h>
#include <octave/lo-ieee.h>
#include <octave/oct-norm.h>

#include <cassert>
#include <stdexcept>

/* Tolerance for considering distances equal when averaging over multiple
   g values.  */
static const double avgTol = 1.0e-9;

/* C++ implementation.  */
DEFUN_DLD (__levelset_nbFromGeom, args, nargout,
  "  [D, GSUM, GCNT] = nbFromGeom (BEDGES, PHI, HASG, G0,\n"
  "                                NODELIST, BDRYINDEX, ONEDGE,\n"
  "                                NODECOORD, ISPTCOORD)\n\n"
  "Internal routine to calculate the narrow-band distances from the geometry\n"
  "information in the respective arguments (corresponding to ls_find_geometry\n"
  "struct fields).\n")
{
  try
    {
      if (args.length () != 9 || nargout > 3)
        throw std::runtime_error ("invalid argument counts");

      /* Get arguments.  */
      const Matrix bedges = args(0).matrix_value ();
      const Matrix phi = args(1).matrix_value ();
      const bool hasG = args(2).bool_value ();
      const ColumnVector g0 = args(3).column_vector_value ();
      const Matrix nodelist = args(4).matrix_value ();
      const ColumnVector bdryIndex = args(5).column_vector_value ();
      const Matrix onEdge = args(6).matrix_value ();
      const Matrix nodeCoord = args(7).matrix_value ();
      const Matrix isptCoord = args(8).matrix_value ();

      /* Extract the dimensions.  */

      const unsigned nEdges = getDimension (bedges, -1, 2);
      if (hasG)
        getDimension (g0, nEdges, 1);

      const dim_vector dims = phi.dims ();
      const unsigned L = dims(0);
      const unsigned M = dims(1);
      const unsigned nNodes = L * M;
      const unsigned nElems = (L - 1) * (M - 1);

      getDimension (nodelist, nElems, 4);
      const unsigned nBdryEl = getDimension (bdryIndex, -1, 1);
      const unsigned nIspts = getDimension (onEdge, -1, 2);
      getDimension (nodeCoord, nNodes, 2);
      getDimension (isptCoord, nIspts, 2);

      /* Loop over each boundary segment and perform the update to d.  */

      Matrix d(L, M), gSum(L, M), gCnt(L, M);
      d.fill (octave_NA);
      if (hasG)
        {
          gSum.fill (octave_NA);
          gCnt.fill (octave_NA);
        }

      for (unsigned i = 0; i < nEdges; ++i)
        {
          const unsigned indA = bedges(i, 0) - 1;
          const unsigned indB = bedges(i, 1) - 1;
          const unsigned bdryEl = onEdge(indA, 0) - 1;
          assert (bdryEl == onEdge(indB, 1) - 1);
          assert (bdryEl < nBdryEl);
          const unsigned elem = bdryIndex(bdryEl) - 1;

#define EXTRACT_VERTEX(varname, coordlist, ind) \
  ColumnVector varname(2); \
  varname(0) = coordlist((ind), 0); \
  varname(1) = coordlist((ind), 1);

          /* Get information about the line segment.  */

          EXTRACT_VERTEX (a, isptCoord, indA)
          EXTRACT_VERTEX (b, isptCoord, indB)

          ColumnVector dir = b - a;
          const double len = xnorm (dir);
          dir /= len;

          /* Try to update all boundary element nodes.  */
          for (unsigned j = 0; j < 4; ++j)
            {
              const unsigned node = nodelist(elem, j) - 1;
              assert (node < nNodes);

              EXTRACT_VERTEX (x, nodeCoord, node)

              /* Project onto the side.  If the projection is negative,
                 x lies "beyond" the edge on the side of a.  In this case,
                 its distance is the distance to a.  The same is true (with b)
                 if the projection is too large.  Otherwise, we
                 use the distance to the line spanned by a and b as usual.  */
              const double proj = dir.transpose () * (x - a);
              double cur;
              if (proj < 0.0)
                cur = xnorm (x - a);
              else if (proj > len)
                cur = xnorm (x - b);
              else
                cur = xnorm (x - (a + proj * dir));

              if (hasG)
                {
                  if (lo_ieee_is_NA (d(node)) || d(node) > cur + avgTol)
                    {
                      gSum(node) = g0(i);
                      gCnt(node) = 1;
                    }
                  else if (std::abs (d(node) - cur) < avgTol)
                    {
                      gSum(node) += g0(i);
                      ++gCnt(node);
                    }
                }

              if (lo_ieee_is_NA (d(node)) || d(node) > cur)
                d(node) = cur;
            }

#undef EXTRACT_VERTEX
        }

      /* Return.  */
      octave_value_list res;
      res(0) = d;
      res(1) = gSum;
      res(2) = gCnt;

      return res;
    }
  catch (const std::runtime_error& exc)
    {
      error (exc.what ());
      return octave_value_list ();
    }
}
