<|start_filename|>src/DgDiscRF2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDiscRF2D.h: DgDiscRF2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDISCRF2D_H 
#define DGDISCRF2D_H

#include <cmath>
#include <cstdint>

#include "DgDiscRF.h"
#include "DgDVec2D.h"
#include "DgIVec2D.h"

class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgDiscRF2D : public DgDiscRF<DgIVec2D, DgDVec2D, long double> {

   public:

      DgDiscRF2D (DgRFNetwork& networkIn, 
                  const DgRF<DgDVec2D, long double>& ccFrameIn,
                  const string& nameIn = "DiscRF2D", long double eIn = 1.0L,
                  long double rIn = 1.0L, long double cIn = 1.0L, long double areaIn = 1.0L)
         : DgDiscRF<DgIVec2D, DgDVec2D, long double> 
                       (networkIn, ccFrameIn, nameIn, eIn, rIn, cIn, areaIn)
           { undefLoc_ = makeLocation(undefAddress()); }

      DgDiscRF2D (const DgDiscRF2D& grd) 
           : DgDiscRF<DgIVec2D, DgDVec2D, long double> (grd)
           { undefLoc_ = makeLocation(undefAddress()); }

      DgDiscRF2D& operator= (const DgDiscRF2D& grd)
           { DgDiscRF<DgIVec2D, DgDVec2D, long double>::operator=(grd); 
             return *this; }

      virtual string add2str (const DgIVec2D& add) const { return string(add); }

      virtual string add2str (const DgIVec2D& add, char delimiter) const 
               { return dgg::util::to_string(add.i()) + delimiter + dgg::util::to_string(add.j()); }

      virtual const char* str2add (DgIVec2D* add, const char* str, 
                                   char delimiter) const
                  {    if (!add) add = new DgIVec2D();
                       return add->fromString(str, delimiter); }

      virtual const DgIVec2D& undefAddress (void) const 
                            { return DgIVec2D::undefDgIVec2D; }

      // remind users of the pure virtual functions remaining from above

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const = 0;

      virtual DgIVec2D quantify    (const DgDVec2D& point) const = 0;
      virtual DgDVec2D invQuantify (const DgIVec2D& add)   const = 0;

      virtual void setAddNeighbors (const DgIVec2D& add, 
                                    DgLocVector& vec) const = 0;

      virtual void setAddVertices  (const DgIVec2D& add, 
                                    DgPolygon& vec) const = 0;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgPhysicalRF2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRF2D.h: DgPhysicalRF2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPHYSICALRF2D_H
#define DGPHYSICALRF2D_H

#include "DgPhysicalRF.h"
#include "DgBoundedRF2D.h"
#include "DgIVec2D.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
template<class C> class DgPhysicalRF2D : public DgPhysicalRF<DgIVec2D, C> {

   public:

      DgPhysicalRF2D<C> (const DgBoundedRF2D& rfIn, bool allocate = false);

      const DgBoundedRF2D& boundedRF2D (void) const { return boundedRF2D_; }

      virtual void replaceAddContents (const DgIVec2D& add, C* cont); // no copy

      virtual void setAddContents (const DgIVec2D& add, const C& cont); // copy

      virtual C* getAddContents (const DgIVec2D& add, 
                                 bool allocate = false) const;

      virtual void deleteAddContents (const DgIVec2D& add);

   protected:

      const DgBoundedRF2D& boundedRF2D_;
      C*** matrix_;

};

#include "DgPhysicalRF2D_template.h"

#endif


<|start_filename|>src/DgBoundedRF_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedRF_template.h: DgBoundedRF template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cstdint>

template<class A, class B, class DB>
DgBoundedRF<A, B, DB>::DgBoundedRF (const DgDiscRF<A, B, DB>& rfIn, 
      const A& firstAddIn, const A& lastAddIn, const A& endAddIn, bool zBasedIn)
   : DgBoundedRFBase<B, DB> (rfIn, *rfIn.makeLocation(firstAddIn), 
     *rfIn.makeLocation(lastAddIn), *rfIn.makeLocation(endAddIn), zBasedIn),
     discRF_(rfIn),
     firstAdd_(firstAddIn), lastAdd_(lastAddIn), endAdd_(endAddIn)
{

} // DgBoundedRF<A, B, DB>::DgBoundedRF

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> bool
DgBoundedRF<A, B, DB>::validLocation (const DgLocation& loc, bool convert) const
{   
   return validAddress(*discRF().getAddress(loc));

} // bool DgBoundedRF<A, B, DB>::validLocation

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> DgLocation&
DgBoundedRF<A, B, DB>::incrementLocation (DgLocation& loc, bool convert) const
{
   const A* add = discRF().getAddress(loc);
   
   incrementAddress(const_cast<A&>(*add)); // cheat for speed
   
   return loc;

} // DgLocation& DgBoundedRF<A, B, DB>::incrementLocation
                         
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> DgLocation&
DgBoundedRF<A, B, DB>::decrementLocation (DgLocation& loc, bool convert) const
{
   const A* add = discRF().getAddress(loc);
   
   decrementAddress(const_cast<A&>(*add)); // cheat for speed
   
   return loc;

} // DgLocation& DgBoundedRF<A, B, DB>::decrementLocation
                                                  
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> std::uint64_t
DgBoundedRF<A, B, DB>::seqNum (const DgLocation& loc, bool convert) const
{
   const A* add = discRF().getAddress(loc);
   
   return seqNumAddress(*add);

} // std::uint64_t DgBoundedRF<A, B, DB>::seqNum
                                                  
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> DgLocation*
DgBoundedRF<A, B, DB>::locFromSeqNum (std::uint64_t sNum) const
{
   A add = addFromSeqNum(sNum);

   return discRF().makeLocation(add);

} // DgLocation* DgBoundedRF<A, B, DB>::locFromSeqNum
                                                  
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////



<|start_filename|>src/DgIDGGS4H.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS4H.h: DgIDGGS4H class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIDGGS4H_H 
#define DGIDGGS4H_H

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgIDGGS.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgIDGGS4H : public DgIDGGS {

   public:

      DgIDGGS4H (DgRFNetwork& networkIn, const DgGeoSphRF& backFrameIn,
               const DgGeoCoord& vert0, long double azDegs, int nResIn = 1,
               const string& nameIn = "ISEA4H", const string& projType = "ISEA")
         : DgIDGGS (networkIn, backFrameIn, vert0, azDegs, 4, nResIn,
                "HEXAGON", nameIn, projType, false, 0, false) 
           { frequency_ = sqrt((long double) aperture()); }

      DgIDGGS4H (const DgIDGGS4H& rf);

     ~DgIDGGS4H (void);

      DgIDGGS4H& operator= (const DgIDGGS4H& rf);

      long double frequency (void) const { return frequency_; }

   protected:

      long double frequency_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgQ2DICoord>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgQ2DICoord>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIVec3D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIVec3D.cpp: DgIVec3D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <limits>
#include <cstdint>

#include "DgBase.h"
#include "DgIVec3D.h"

////////////////////////////////////////////////////////////////////////////////

const DgIVec3D& DgIVec3D::undefDgIVec3D = DgIVec3D(std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), std::numeric_limits<int>::max());

////////////////////////////////////////////////////////////////////////////////
const char*
DgIVec3D::fromString (const char* str, char delimiter)
{
   char delimStr[2];
   delimStr[0] = delimiter;
   delimStr[1] = '\0';

   char* tmpStr = new char[strlen(str) + 1];
   strcpy(tmpStr, str);

   // Get i, j, and k
   char* tok;

   std::int64_t	iIn(0),
	   		jIn(0),
                        kIn(0);

   try
    {
   	tok = strtok(tmpStr, delimStr);
   	iIn = dgg::util::from_string<std::int64_t>(tok);
	
   	tok = strtok(NULL, delimStr);
   	jIn = dgg::util::from_string<std::int64_t>(tok);

   	tok = strtok(NULL, delimStr);
   	kIn = dgg::util::from_string<std::int64_t>(tok);
    }  
   catch(...)
    {
      ::report("DgIVec3D::fromString() invalid value in string " + string(tok), 
               DgBase::Fatal);
    }

   setI(iIn);
   setJ(jIn);
   setK(kIn);

   std::uint64_t offset = (tok - tmpStr) + strlen(tok) + 1;
   if (offset >= strlen(str)) 
    return 0;

   return &str[offset];

} // const char* DgIVec3D::fromString

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgIDGGS4T.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS4T.cpp: DgIDGGS4T class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <cstdint>

#include "DgContCartRF.h"
#include "DgDiscRF.h"
#include "DgIDGGS4T.h"
#include "DgTriGrid2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIDGGS4T::DgIDGGS4T (const DgIDGGS4T& rf) 
  : DgIDGGS (rf)
{
   report("DgIDGGS4T::operator=() not implemented yet", DgBase::Fatal);

} // DgIDGGS4T::DgIDGGS4T

////////////////////////////////////////////////////////////////////////////////
DgIDGGS4T::~DgIDGGS4T (void)
{
   for (unsigned int i = 0; i < grids().size(); i++) 
    delete (*grids_)[i]; 

   delete grids_;

} // DgIDGGS4T::~DgIDGGS4T

////////////////////////////////////////////////////////////////////////////////
DgIDGGS4T&
DgIDGGS4T::operator= (const DgIDGGS4T& rf)
{
   report("DgIDGGS4T::operator=() not implemented", DgBase::Fatal);

   return *this;

} // DgIDGGS4T& DgIDGGS4T::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4T::setAddParents (const DgResAdd<DgQ2DICoord>& add, 
                               DgLocVector& vec) const
{
//cout << "   setAddParents: " << add << endl;
   if (isCongruent())
   {
      DgLocation* tmpLoc = makeLocation(add);
      grids()[add.res() - 1]->convert(tmpLoc);
      convert(tmpLoc);

      vec.push_back(*tmpLoc);

      delete tmpLoc;
   }
   else
   {
      report("DgIDGGS4T::DgIDGGS4T() only congruent triangle grid "
             "systems implemented", DgBase::Fatal);
   }

} // void DgIDGGS4T::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4T::setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent())
   {
//cout << "Children: " << add << " " << lowerLeft << endl;

      vector<DgAddressBase*>& v = vec.addressVec();

      if (DgTriGrid2D::isUp(add.address().coord()))
      {
         const DgIVec2D lowerLeft((add.address().coord().i() * radix()),
                                  (add.address().coord().j() * radix()));

         std::int64_t maxJ = 0;
         for (int i = 0; i < radix(); i++)
         {
            for (std::int64_t j = 0; j <= maxJ; j++)
            {
               v.push_back(new DgAddress< DgResAdd<DgQ2DICoord> >(
                  DgResAdd<DgQ2DICoord>(DgQ2DICoord(add.address().quadNum(),
                       DgIVec2D(lowerLeft.i() + i, lowerLeft.j() + j)),
                               add.res() + 1)));
            }
            maxJ += 2;
         }
      }
      else // down pointing
      {
         const DgIVec2D upperRight(
                         (add.address().coord().i() * radix() + radix() - 1),
                         (add.address().coord().j() * radix() + radix() - 1));

         std::int64_t maxJ = 0;
         for (int i = 0; i < radix(); i++)
         {
            for (std::int64_t j = 0; j <= maxJ; j++)
            {
               v.push_back(new DgAddress< DgResAdd<DgQ2DICoord> >(
                  DgResAdd<DgQ2DICoord>(DgQ2DICoord(add.address().quadNum(),
                       DgIVec2D(upperRight.i() - i, upperRight.j() - j)),
                               add.res() + 1)));
            }
            maxJ += 2;
         }
      }
   }
   else
   {
      report("DgIDGGS4T::DgIDGGS4T() only congruent triangle grid "
             "systems implemented", DgBase::Fatal);
   }
//cout << vec << endl;
   
} // void DgIDGGS4T::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4T::setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent())
   {
      // no boundary children in this topology; leave vec empty
   }
   else
   {
      report("DgIDGGS4T::DgIDGGS4T() only congruent triangle grid "
             "systems implemented", DgBase::Fatal);
   }

} // void DgIDGGS4T::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4T::setAddAllChildren (const DgResAdd<DgQ2DICoord>& add, 
                                   DgLocVector& vec) const
{
   setAddInteriorChildren(add, vec);

} // void DgIDGGS4T::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/pj_qsfn.cpp<|end_filename|>
/* determine small q */
#include <cmath>

# define EPSILON 1.0e-7
	long double
pj_qsfn(long double sinphi, long double e, long double one_es) {
	long double con;

	if (e >= EPSILON) {
		con = e * sinphi;
		return (one_es * (sinphi / (1. - con * con) -
		   (.5 / e) * std::log ((1. - con) / (1. + con))));
	} else
		return (sinphi + sinphi);
}


<|start_filename|>src/DgTriGrid2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgTriGrid2D.cpp: DgTriGrid2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <cstdint>

#include "DgTriGrid2D.h"
#include "DgPolygon.h"

////////////////////////////////////////////////////////////////////////////////
void
DgTriGrid2D::setAddVertices (const DgIVec2D& add, DgPolygon& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   // find the center

   DgLocation tmpLoc;
   setAddPoint(add, tmpLoc);
   const DgDVec2D& cent = *(backFrame().getAddress(tmpLoc));

   if (isUp(add))
   {
      v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-e() / 2.0, -0.5)));
      v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(       0.0,  1.0)));
      v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( e() / 2.0, -0.5)));
   }
   else
   {
      v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-e() / 2.0,  0.5)));
      v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( e() / 2.0,  0.5)));
      v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(       0.0, -1.0)));
   }

/*
   cout << "triangle: " << add << " " << tmpLoc << endl;
   cout << vec << endl;
*/

} // void DgTriGrid2D::setAddVertices

////////////////////////////////////////////////////////////////////////////////
void
DgTriGrid2D::setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   if (isUp(add))
   {
      v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(),     add.j() + 1)));
      v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1, add.j() + 1)));
      v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(),     add.j() - 1)));
   }
   else
   {
      v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(),     add.j() + 1)));
      v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(),     add.j() - 1)));
      v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1, add.j() - 1)));
   }

} // void DgTriGrid2D::setAddNeighbors

////////////////////////////////////////////////////////////////////////////////
DgIVec2D 
DgTriGrid2D::quantify (const DgDVec2D& point) const
{
   DgDVec2D p(point);  // p prime
   p += DgDVec2D(e() / 2.0, 0.5);   // move origin to lower left

   DgDVec2D pp(p.x() + p.y() / sqrt(3.0), p.y()); // p long double prime

   std::int64_t i    = static_cast<std::int64_t>(floor(pp.x() / e()));
   std::int64_t jTmp = static_cast<std::int64_t>(floor(2.0/3.0 * pp.y()));

   DgDVec2D ppp(p.x() - p.y() / sqrt(3.0), p.y()); // p triple prime
   std::int64_t k    = static_cast<std::int64_t>(floor(ppp.x() / e()));

   std::int64_t j = jTmp * 2;
   if (jTmp % 2) // i + j + k should be odd
   {
      if (!((i + j + k) % 2)) j++;
   }
   else // i + j + k should be even
   {
      if ((i + j + k) % 2) j++;
   }

   return DgIVec2D(i, j);

} // DgIVec2D DgTriGrid2D::quantify

////////////////////////////////////////////////////////////////////////////////
DgDVec2D 
DgTriGrid2D::invQuantify (const DgIVec2D& add) const
{
   long double x = ((long double) add.i() * e()) - 
                 ((long double) ((add.j() + 1) / 2) * e() / 2.0);
   long double y = 1.5 * (long double) (add.j() / 2) + 0.5 * (long double) (add.j() % 2);

   return DgDVec2D(x, y);

} // DgDVec2D DgTriGrid2D::invQuantify

////////////////////////////////////////////////////////////////////////////////
std::int64_t
DgTriGrid2D::dist (const DgIVec2D& add1, const DgIVec2D& add2) const
{
   return 0;
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgHexC1Grid2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgHexC1Grid2D.cpp: DgHexC1Grid2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <cstdint>

#include "DgHexC1Grid2D.h"
#include "DgPolygon.h"

////////////////////////////////////////////////////////////////////////////////
void
DgHexC1Grid2D::setAddVertices (const DgIVec2D& add, DgPolygon& vec) const
{

   vector<DgAddressBase*>& v = vec.addressVec();

   // find the center

#if DGDEBUG
cout << setprecision(20) << "^^^^^^^^^^^^^^^^^\nDgHexC1Grid2D::setAddVertices"
     << endl; 
cout << "^^ input: " << add << endl;
cout.flush();
#endif

   DgLocation tmpLoc;
   setAddPoint(add, tmpLoc);

   const DgDVec2D& cent = *(backFrame().getAddress(tmpLoc));

   long double r2 = r_ / 2.0L;
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( 0.0L,  r_)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-0.5L,  r2)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-0.5L, -r2)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( 0.0L, -r_)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( 0.5L, -r2)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( 0.5L,  r2)));

} // void DgHexC1Grid2D::setAddVertices

////////////////////////////////////////////////////////////////////////////////
void
DgHexC1Grid2D::setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1, add.j() + 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(    add.i(), add.j() + 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1,     add.j())));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1, add.j() - 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(    add.i(), add.j() - 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1,     add.j())));

} // void DgHexC1Grid2D::setAddNeighbors

////////////////////////////////////////////////////////////////////////////////
DgIVec2D 
DgHexC1Grid2D::quantify (const DgDVec2D& point) const
{
   long double a1, a2;
   long double x1, x2;
   std::int64_t m1, m2;
   long double r1, r2;
   DgIVec2D add;

   a1 = fabs(point.x());
   a2 = fabs(point.y());

   /* first do a reverse conversion */

   x2 = a2 / M_SIN60;
   x1 = a1 + x2 / 2.0L;

   /* check if we have the center of a hex */

   m1 = static_cast<std::int64_t>(x1);
   m2 = static_cast<std::int64_t>(x2);

   /* otherwise round correctly */

   r1 = x1 - m1;
   r2 = x2 - m2;

   if (r1 < 0.5L)
   {
      if (r1 < 1.0L/3.0L)
      {
         if (r2 < (1.0L + r1) / 2.0L)
         {
            add.setI(m1);
            add.setJ(m2);
         }
         else
         {
            add.setI(m1);
            add.setJ(m2 + 1);
         }
      }
      else
      {
         if (r2 < (1.0L - r1))
         {
            add.setJ(m2);
         }
         else
         {
            add.setJ(m2 + 1);
         }

         if ((1.0L - r1) <= r2 && r2 < (2.0 * r1))
         {
            add.setI(m1 + 1);
         }
         else
         {
            add.setI(m1);
         }
      }
   }
   else
   {
      if (r1 < 2.0L/3.0L)
      {
         if (r2 < (1.0L - r1))
         {
            add.setJ(m2);
         }
         else
         {
            add.setJ(m2 + 1);
         }

         if ((2.0L * r1 - 1.0L) < r2 && r2 < (1.0L - r1))
         {
            add.setI(m1);
         }
         else
         {
            add.setI(m1 + 1);
         }
      }
      else
      {
         if (r2 < (r1 / 2.0L))
         {
            add.setI(m1 + 1);
            add.setJ(m2);
         }
         else
         {
            add.setI(m1 + 1);
            add.setJ(m2 + 1);
         }
      }
   }

   // now fold across the axes if necessary

   if (point.x() < 0.0L)
   {
      if ((add.j() % 2) == 0) // even
      {
         std::int64_t axisi = add.j() / 2;
         std::int64_t diff = add.i() - axisi;
         add.setI(add.i() - 2 * diff);
      }
      else
      {
         std::int64_t axisi = (add.j() + 1) / 2;
         std::int64_t diff = add.i() - axisi;
         add.setI(add.i() - (2 * diff + 1));
      }
   }

   if (point.y() < 0.0L) 
   {
      add.setI(add.i() - (2 * add.j() + 1) / 2);
      add.setJ(-1 * add.j());
   }

   return add;

} // DgIVec2D DgHexC1Grid2D::quantify

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/hypot.cpp<|end_filename|>
#include <cmath>

/* hypot - sqrt(x * x + y * y)
**
**	Because this was omitted from the ANSI standards, this version
** 	is included for those systems that do not include hypot as an
**	extension to libm.a.  Note: GNU version was not used because it
**	was not properly coded to minimize potential overflow.
**
**	The proper technique for determining hypot is to factor out the
**	larger of the two terms,  thus leaving a possible case of float
**	overflow when max(x,y)*sqrt(2) > max machine value.  This allows
**	a wider range of numbers than the alternative of the sum of the
**	squares < max machine value.  For an Intel x87 IEEE long double of
**	approximately 1.8e308, only argument values > 1.27e308 are at
**	risk of causing overflow.  Whereas, not using this method limits
**	the range to values less that 9.5e153 --- a considerable reduction
**	in range!
*/


long double
usgs_hypot(long double x, long double y) {
	if ( x < 0.)
		x = -x;
	else if (x == 0.)
		return (y < 0. ? -y : y);
	if (y < 0.)
		y = -y;
	else if (y == 0.)
		return (x);
	if ( x < y ) {
		x /= y;
		return ( y * std::sqrt( 1. + x * x ) );
	} else {
		y /= x;
		return ( x * std::sqrt( 1. + y * y ) );
	}
}


<|start_filename|>src/DgDmdD4Grid2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDmdD4Grid2D.h: DgDmdD4Grid2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDMDD4GRID2D_H 
#define DGDMDD4GRID2D_H

#include <cmath>
#include <cstdint>

#include "DgDiscRF2D.h"
#include "DgDVec2D.h"
#include "DgIVec2D.h"
#include "DgConstants.h"

class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgDmdD4Grid2D : public DgDiscRF2D {

   public:

      DgDmdD4Grid2D (DgRFNetwork& networkIn, 
                     const DgRF<DgDVec2D, long double>& contCartFrameIn,
                     const string& nameIn = "Dmd2D")
         : DgDiscRF2D (networkIn, contCartFrameIn, nameIn, 1.0L, 1.0L, 
                       M_SQRT3_2, 1.0L) 
           { r_ = c(); }

      DgDmdD4Grid2D (const DgDmdD4Grid2D& grd) : DgDiscRF2D (grd) {}

      DgDmdD4Grid2D& operator= (const DgDmdD4Grid2D& grd)
           { DgDiscRF2D::operator=(grd); return *this; }

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const
           { return abs(add2.i() - add1.i()) + abs(add2.j() - add1.j()); }

      static long double yOff (void) { return yOff_; }
      static long double xOff (void) { return xOff_; }

   protected:

      virtual void setAddVertices (const DgIVec2D& add, DgPolygon& vec) const;
      virtual void setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) 
                                                                          const;

      static const long double yOff_;
      static const long double yOff2_;
      static const long double xOff_;
      static const long double xOffComp_;
      static const long double skewFac_;

      virtual DgIVec2D quantify (const DgDVec2D& point) const
         {
            DgDVec2D tmp(point);
            tmp.setX(tmp.x() + skewFac_ * tmp.y());

            return DgIVec2D(dgg::util::lrint(tmp.x()), 
                            dgg::util::lrint(tmp.y() / yOff2_));

         } // DgIVec2D DgDmdD4Grid2D::quantify


      virtual DgDVec2D invQuantify (const DgIVec2D& add) const
         {
            DgDVec2D tmp(add.i(), add.j() * yOff2_);
            tmp.setX(tmp.x() - skewFac_ * tmp.y());
         
            return tmp;

         } // DgDVec2D DgDmdD4Grid2D::invQuantify

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgDVec3D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDVec3D.cpp: DgDVec3D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgDVec3D.h"
#include <limits>

////////////////////////////////////////////////////////////////////////////////

const DgDVec3D& DgDVec3D::undefDgDVec3D = DgDVec3D(std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max());

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgProjFuller.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgProjFuller.cpp: DgProjFuller class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <limits>
#include "DgProjFuller.h"

////////////////////////////////////////////////////////////////////////////////
DgProjFullerInv::DgProjFullerInv (const DgRF<DgProjTriCoord, long double>& from,
                       const DgRF<DgGeoCoord, long double>& to)
         : DgConverter<DgProjTriCoord, long double, DgGeoCoord, long double>(from, to),
           pProjTriRF_ (0)
{ 
   pProjTriRF_ = dynamic_cast<const DgProjTriRF*>(&fromFrame());

   if (!pProjTriRF_)
   {
      report("DgProjFullerInv::DgProjFullerInv(): "
        " fromFrame not of type DgProjTriRF", DgBase::Fatal);
   }

} // DgProjFullerInv::DgProjFullerInv

////////////////////////////////////////////////////////////////////////////////
DgGeoCoord 
DgProjFullerInv::convertTypedAddress (const DgProjTriCoord& addIn) const
{
//cout << "***DgProjFullerInv: DgProjTriCoord: " << addIn << endl;
   IcosaGridPt gridpt;
   gridpt.pt.x = addIn.coord().x();
   gridpt.pt.y = addIn.coord().y();
   gridpt.triangle = addIn.triNum();

//cout << "    gridpt.triangle .x .y: " << gridpt.triangle << ", " <<
//      gridpt.pt.x << ", " << gridpt.pt.y << endl;

   GeoCoord ll = fullerInv(gridpt, projTriRF().sphIcosa().sphIcosa());

//cout << " ll.lon, ll.lat: " << ll.lon << ", " << 
//ll.lat << endl;
   DgGeoCoord geoPt(ll.lon, ll.lat);
   geoPt.normalize();

//cout << "    geoPt: " << geoPt << endl;
   return geoPt;

} // DgGeoCoord DgProjFullerInv::convertTypedAddress

////////////////////////////////////////////////////////////////////////////////
DgProjFullerFwd::DgProjFullerFwd (const DgRF<DgGeoCoord, long double>& from,
                    const DgRF<DgProjTriCoord, long double>& to)
         : DgConverter<DgGeoCoord, long double, DgProjTriCoord, long double>(from, to) 
{ 
   pProjTriRF_= dynamic_cast<const DgProjTriRF*>(&toFrame());

   if (!pProjTriRF_)
   {
      report("DgProjFullerFwd::DgProjFullerFwd(): "
        " toFrame not of type DgProjTriRF", DgBase::Fatal);
   }

} // DgProjFullerFwd::DgProjFullerFwd 

////////////////////////////////////////////////////////////////////////////////
DgProjTriCoord 
DgProjFullerFwd::convertTypedAddress (const DgGeoCoord& addIn) const
{
         
//cout << "***DgProjFullerFwd: geoPt: " << addIn << endl;
         GeoCoord ll;

   ll.lon = addIn.lon();
   ll.lat = addIn.lat();

//cout << "   ll.lon, ll.lat: " << ll.lon << ", " << ll.lat << endl;

   IcosaGridPt gridpt = fullerFwd(ll, projTriRF().sphIcosa());
//cout << "    gridpt.triangle .x .y: " << gridpt.triangle << ", " <<
//      gridpt.pt.x << ", " << gridpt.pt.y << endl;

//cout << "DgProjTriCoord: " << DgProjTriCoord(gridpt.triangle, 
//                               DgDVec2D(gridpt.pt.x, gridpt.pt.y)) << endl;

   return DgProjTriCoord(gridpt.triangle, DgDVec2D(gridpt.pt.x, gridpt.pt.y));

} // DgProjTriCoord DgProjFullerFwd::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/* 
   The C++ methods above are wrappers for the C functions below.
*/
////////////////////////////////////////////////////////////////////////////////

const long double edgeScale = M_ATAN2;
const long double originXOff = M_ATAN2_2; // edgeScale/2;
const long double originYOff = 0.3196063051256835802821381404218L;
                           //originXOff / M_SQRT3;

////////////////////////////////////////////////////////////////////////////////
IcosaGridPt fullerFwd (const GeoCoord& ll, DgSphIcosa& sphicosa)
/*
   project the point ll (lat, lon in radius) to the
   plane and return relevant info in IcosaGridPt
*/
{
   IcosaGridPt gridpt;

   gridpt.triangle = sphicosa.whichIcosaTri(ll);

   if (gridpt.triangle < 0)
   {
      // printf("ERROR: point in no triangle:");
      // printGeoCoord(ll); 
      // printf("\n");

      gridpt.pt.x = M_ZERO;
      gridpt.pt.y = M_ZERO;

      return gridpt;
   }

   //gridpt.pt = fllxy(ll, sphicosa, gridpt.triangle);

   long double v1[3], v2[3], v3[3];
   
   v1[0] = sphicosa.sphIcosa().icotri[gridpt.triangle][0].lon;
   v1[1] = sphicosa.sphIcosa().icotri[gridpt.triangle][0].lat;

   v2[0] = sphicosa.sphIcosa().icotri[gridpt.triangle][1].lon;
   v2[1] = sphicosa.sphIcosa().icotri[gridpt.triangle][1].lat;

   v3[0] = sphicosa.sphIcosa().icotri[gridpt.triangle][2].lon;
   v3[1] = sphicosa.sphIcosa().icotri[gridpt.triangle][2].lat;

   v1[2] = v2[2] = v3[2] = M_ZERO;

   gridpt.pt = fullerFwdOneTri(ll, M_ONE, v1, v2, v3);
   gridpt.pt.x = (gridpt.pt.x + originXOff) / edgeScale;
   gridpt.pt.y = (gridpt.pt.y + originYOff) / edgeScale;

   return gridpt;

} /* IcosaGridPt fullerFwd */

////////////////////////////////////////////////////////////////////////////////
GeoCoord fullerInv (const IcosaGridPt& icosaPt, SphIcosa& sphicosa)
/*
    project the point icosaPt.pt (x, y in Fuller in the coordinate
    system of the specified triangle) to lon, lat in radians

    this replaces the old fullerInv/sxyll combo.
*/
{
  long double ddazh;
  long double sinlat,sinlon;
  GeoCoord Geovect;
  const PreCompGeo& cent = sphicosa.triCen[icosaPt.triangle];
 
  IcosaGridPt iPt;
  iPt.triangle = icosaPt.triangle;
  iPt.pt.x = icosaPt.pt.x * edgeScale - originXOff;
  iPt.pt.y = icosaPt.pt.y * edgeScale - originYOff;

//printf("   iPt.triangle .x .y: %d %.15lf %.15lf\n", iPt.triangle,
    //iPt.pt.x, iPt.pt.y);

  ddazh = sphicosa.dazh[icosaPt.triangle];

  if ((fabs(iPt.pt.x) < PRECISION) && (fabs(iPt.pt.y) < PRECISION))
  {
    Geovect.lat=cent.pt.lat; Geovect.lon=cent.pt.lon;
  }
  else
  {  
    long double azh, theta;
    Geovect = fullerInvOneTri(iPt, M_ONE, &azh, &theta);

    azh = dgM_PI - azh; // 180' - azh

    // now reposition to the actual triangle

    azh += ddazh;

    while (azh <= -dgM_PI) azh += M_2PI;
    while (azh > dgM_PI) azh -= M_2PI;

    sinlat=cent.sinLat * cos(theta) + cent.cosLat * sin(theta) * cos(azh);
    if (sinlat > M_ONE) sinlat = M_ONE;
    if (sinlat < -M_ONE) sinlat = -M_ONE;
    Geovect.lat = asin(sinlat);

    if (fabs(fabs(Geovect.lat) - dgM_PI_2) < M_EPSILON)
    {
       Geovect.lat = (Geovect.lat > M_ZERO) ? dgM_PI_2 : -dgM_PI_2;
       Geovect.lon = M_ZERO;
    }
    else
    {
      sinlon = sin(azh)*sin(theta)/cos(Geovect.lat);
      long double coslon = (cos(theta) - cent.sinLat * sin(Geovect.lat)) /
              cent.cosLat/cos(Geovect.lat);
      if (sinlon > M_ONE) sinlon = M_ONE;
      if (sinlon < -M_ONE) sinlon = -M_ONE;
      if (coslon > M_ONE) coslon = M_ONE;
      if (coslon < -M_ONE) coslon =-M_ONE;
      Geovect.lon = cent.pt.lon+asin(sinlon);
      Geovect.lon = cent.pt.lon+atan2(sinlon, coslon);
      if (Geovect.lon <= -dgM_PI) Geovect.lon += M_2PI;
      if (Geovect.lon >= dgM_PI) Geovect.lon -= M_2PI;
    }
  }
  return Geovect;

} /* GeoCoord fullerInv */

void geogtocartesian (long double lon, long double lat, long double R, long double ret[])
{
   long double inc = dgM_PI_2 - lat;
   long double azi = lon + dgM_PI;

   ret[0] = R * cos(azi) * sin(inc);
   ret[1] = R * sin(azi) * sin(inc);
   ret[2] = R * cos(inc);

} // static void geogtocartesian

long double scalar_triple(long double * x, long double * y, long double * z)
{
   long double yzcross[3];

   yzcross[0] = y[1]*z[2] - y[2]*z[1];
   yzcross[1] = y[2]*z[0] - y[0]*z[2];
   yzcross[2] = y[0]*z[1] - y[1]*z[0];

   long double xyztrip = x[0] * yzcross[0] + x[1]*yzcross[1] + x[2]*yzcross[2];

   return xyztrip;

} // static long double scalar_triple

Vec2D fullerFwdOneTri (const GeoCoord geo, long double R, long double * v1, 
                       long double * v2, long double * v3)
{
   const long double cosarc = 0.447213595499957939281834733746255L; // cos(atan(2))

   long double ret [3];
   long double ret2 [3];
   long double ret3 [3];
   long double ret4 [3];

   geogtocartesian(geo.lon, geo.lat, R, ret);
   geogtocartesian(v1[0], v1[1], R, ret2);
   geogtocartesian(v2[0], v2[1], R, ret3);
   geogtocartesian(v3[0], v3[1], R, ret4);

   long double v1v2p = scalar_triple(ret2, ret3, ret);
   long double v1v3p = scalar_triple(ret2, ret4, ret);
   long double v2v1p = scalar_triple(ret3, ret2, ret);
   long double v2v3p = scalar_triple(ret3, ret4, ret);
   long double v3v1p = scalar_triple(ret4, ret2, ret);
   long double v3v2p = scalar_triple(ret4, ret3, ret);
   
   long double a1 = atan((2.0L*v2v3p*cosarc) / (v2v3p*cosarc-(v2v1p+v1v3p))); 
   long double a2 = atan((2.0L*v1v2p*cosarc) / (v1v2p*cosarc - (v1v3p + v3v2p)));
   long double a3 = atan((2.0L*v3v1p*cosarc) / (v3v1p*cosarc - (v3v2p + v2v1p)));

   long double x = R * (a2-a3)/2.0L;
   long double y = R * (2.0L * a1 - a2 - a3)/(2.0L * M_SQRT3);

   //IcosaGridPt p;
   Vec2D pt;
   pt.x = x;
   pt.y = y;

   return pt;

} // Vec2D fullerFwdOneTri

GeoCoord fullerInvOneTri(const IcosaGridPt pt, long double R, long double* pAzimuth, 
                         long double* pTheta)
{
   long double alpha, el, dve;      /* constants used with Fuller projection*/
   long double x, y, z;             /* 3-D x, y, z coords of output  */
   long double x1, y1, z1;          /* 3-D x, y, z coords of template triangle plane*/
   long double x2, y2;              /* initial planar coords*/
   long double a1, a2, a3;          /* arc lengths on plane and sphere*/
   long double a1p, a2p;            /* arc lengths on template triangle plane*/ 
   long double s;                   /* length from unit sphere origin to plane*/
   long double group1, group2;      /* grouping of constants for use in finding a2*/
   long double inc;                 /* increment to obtain an accurate a2*/
   long double theta, azimuth;      /* conversion angles from x,y,z to lat/lon*/
   long double test, answer;        /* compared values for use in finding a2*/

   //el = M_SQRT8 / sqrt(5.0L + M_SQRT5);
   el = 1.05146222423826721205133816969575L;
   //dve = sqrt(3.0L + M_SQRT5) / sqrt(5.0L + M_SQRT5);
   dve = 0.85065080835203993218154049706301L;
   //alpha = 0.5L * arc;
   alpha = M_ATAN2_2;
   
   x2 = pt.pt.x / R;
   y2 = pt.pt.y / R;
   
   group1 = (M_SQRT3 * y2) - x2 - alpha;
   group2 = (2.0L * x2) + alpha;
   //answer = -el / (2.0L * dve);
   answer = -0.6180339887498948482045868343656L;
   test = M_ONE;

   inc = alpha;
   a2 = inc;

   long double hi = answer-test;
   long double lastHi = hi;
   while (std::abs(hi) > PRECISION) 
   { 
      test = std::tan (a2 + group1) + std::tan (a2 - alpha) + std::tan (a2 - group2);
      inc = inc / 2.0L;
   
      hi = answer - test;
      if (hi == lastHi)
      {
         // std::cerr<<"ERROR: fullerInvOneTri: iterative step failed.\n";
         // std::cerr<<"loss of precision: "<<(std::abs(hi) - PRECISION)<<".\n";
         break;
      }
      lastHi = hi;

      if (std::abs(hi) < PRECISION) break;

      if (test > answer)
         a2 = a2 - inc;
      else
         a2 = a2 + inc;
   }

   a3 = a2 - (2.0L * x2);
   a1 = (M_SQRT3 * y2) + (M_HALF * a2) + (M_HALF * a3);

   a1p = dve * tan (a1 - alpha) + (el / 2.0L);
   a2p = dve * tan (a2 - alpha) + (el / 2.0L);

   /* Find x1, y1 and z1 on template planar triangle*/

   //y1 = a1p * sin (60.0L * dgM_PI_180) - (el / (2.0L * M_SQRT3));
   y1 = a1p * M_SIN60 - 0.30353099910334311154769579070999L;
   //x1 = a2p + (y1 / M_SQRT3) - (el / 3.0L);
   x1 = a2p + (y1 / M_SQRT3) - 0.3504874080794224040171127232319L;
   //z1 = sqrt (5.0L + (2.0L * M_SQRT5)) / M_SQRT15;
   z1 = 0.79465447229176612295553092832759L;

   s = sqrt(x1 * x1 + y1 * y1 + z1 * z1);

   x = x1 / s;
   y = y1 / s;
   z = z1 / s;
   test = sqrt(x*x + y*y + z*z);

   //printf("XYZ: %f, %f, %f\n", x, y, z);

   /* Convert x, y, z coords to lat/lon*/

   theta = acos (z);
   azimuth = atan2 (y, x);
   long double j = dgM_PI / 2.0L;
   if (azimuth <= j )
      azimuth = azimuth + dgM_PI_2;
   else
   {
      //azimuth = azimuth - 3.0L * dgM_PI / 2.0L;
      azimuth -= 4.712388980384689857693965074919L;
   }

   *pTheta = theta;
   *pAzimuth = azimuth;
   
   long double lat = (dgM_PI_2 - theta) * M_180_PI;
   long double lon = azimuth;
   if (fabs (dgM_PI_2 - lat) < PRECISION)
      lon = M_ZERO;

   lon = lon * M_180_PI;

   GeoCoord geo;
   geo.lon = lon;
   geo.lat = lat;
   
   return geo;

} // GeoCoord fullerInvOneTri

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////




<|start_filename|>src/DgCell.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgCell.cpp: DgCell class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////
//
//  The DgCell class defines an object with a point node, a region, and a 
//  label.
//
////////////////////////////////////////////////////////////////////////////////

#include "DgBase.h"
#include "DgCell.h"
#include "DgLocation.h"
#include "DgPolygon.h"

////////////////////////////////////////////////////////////////////////////////
void 
DgCell::convertTo (const DgRFBase& rfIn) 
{ 
   if (!rf_ || rf() != rfIn)
   {
      rf_ = &rfIn;
      rfIn.convert(&node_); 
      if (hasRegion()) rfIn.convert(*region_);
   }

} // DgCell::convertTo

////////////////////////////////////////////////////////////////////////////////
string 
DgCell::asString (void) const
{ 
   string tmp = "[" + node().asString();
   if (hasRegion()) tmp += ":" + region().asString();
   tmp += "]"; 

   return tmp;

} // DgCell::asString

////////////////////////////////////////////////////////////////////////////////
string 
DgCell::asString (char delimiter) const
{ 
   string tmp = node().asString(delimiter);
   if (hasRegion()) tmp += delimiter + region().asString(delimiter);

   return tmp;

} // DgCell::asString

////////////////////////////////////////////////////////////////////////////////
string 
DgCell::asAddressString (void) const
{ 
   string tmp = "[" + node().asAddressString();
   if (hasRegion()) tmp += ":" + region().asAddressString();
   tmp += "]"; 

   return tmp;

} // DgCell::asAddressString

////////////////////////////////////////////////////////////////////////////////
string 
DgCell::asAddressString (char delimiter) const
{ 
   string tmp = node().asAddressString(delimiter);
   if (hasRegion()) tmp += delimiter + region().asAddressString(delimiter);

   return tmp;

} // DgCell::asAddressString

////////////////////////////////////////////////////////////////////////////////
const char*
DgCell::fromString (const char* str, char delimiter)
{
   clearAddress();

   DgLocation tloc(rf());
   const char* tmp = tloc.fromString(str, delimiter);
   setNode(tloc);

   if (*tmp == delimiter) tmp++;

   DgPolygon* reg = new DgPolygon(rf());
   tmp = reg->fromString(tmp, delimiter);
   setRegion(reg);

   return tmp;

} // DgCell::fromString

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgConverter.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgConverter.h: DgConverter class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGCONVERTER_H
#define DGCONVERTER_H

#include <vector>

using namespace std;

#include "DgRF.h"
#include "DgConverterBase.h"
#include "DgAddress.h"

////////////////////////////////////////////////////////////////////////////////
template <class AFrom, class DFrom, class ATo, class DTo> class DgConverter : 
public DgConverterBase {

   public:

      DgConverter (const DgRF<AFrom, DFrom>& fromFrame, 
                   const DgRF<ATo, DTo>& toFrame)
          : DgConverterBase(fromFrame, toFrame) {}

      DgConverter (const DgConverter& con) : DgConverterBase(con) {}

      DgConverter& operator= (const DgConverter& con)
         { DgConverterBase::operator=(con); return *this; }

      virtual ATo convertTypedAddress (const AFrom& addIn) const = 0;

   protected:

      virtual DgAddressBase* createConvertedAddress 
                                  (const DgAddressBase& addIn) const
#if DGDEBUG
          { 
            const DgAddress<AFrom>& addFrom = 
                static_cast<const DgAddress<AFrom>&>(addIn).address();
            DgAddress<ATo> *addTo = 
                //new DgAddress<ATo>(convertTypedAddress(addFrom));
                new DgAddress<ATo>(convertTypedAddress(
                static_cast<const DgAddress<AFrom>&>(addIn).address()));
            cout << " " << addFrom.address() << "->" << addTo->address() << endl;
            return addTo;
          }
#else
          { return new DgAddress<ATo>(convertTypedAddress(
                static_cast<const DgAddress<AFrom>&>(addIn).address())); }
#endif

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgSqrD8Grid2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSqrD8Grid2D.h: DgSqrD8Grid2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSQRGRIDD82D_H 
#define DGSQRGRIDD82D_H

#include <cstdint>

#include "DgSqrD4Grid2D.h"

////////////////////////////////////////////////////////////////////////////////
class DgSqrD8Grid2D : public DgSqrD4Grid2D {

   public:

      DgSqrD8Grid2D (DgRFNetwork& networkIn, 
                     const DgRF<DgDVec2D, long double>& contCartFrameIn,
                     const string& nameIn = "Sqr2D")
         : DgSqrD4Grid2D (networkIn, contCartFrameIn, nameIn) { }

      DgSqrD8Grid2D (const DgSqrD8Grid2D& grd) 
         : DgSqrD4Grid2D (grd) {}

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const
           { std::int64_t diffi = abs(add2.i() - add1.i());
             std::int64_t diffj = abs(add2.j() - add1.j());
             return (diffi >= diffj) ? diffi : diffj; }

   protected:

      virtual void setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) 
                                                                        const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIDGGS4D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS4D.h: DgIDGGS4D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIDGGS4D_H 
#define DGIDGGS4D_H

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgIDGGS.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgIDGGS4D : public DgIDGGS {

   public:

      DgIDGGS4D (DgRFNetwork& networkIn, const DgGeoSphRF& backFrameIn,
               const DgGeoCoord& vert0, long double azDegs, int nResIn = 1,
               const string& nameIn = "ISEA4D", const string& projType = "ISEA")
         : DgIDGGS (networkIn, backFrameIn, vert0, azDegs, 4, nResIn,
                "DIAMOND", nameIn, projType, false, 0, false) 
           { radix_ = (int) sqrt((float) aperture()); }

      DgIDGGS4D (const DgIDGGS4D& rf);

     ~DgIDGGS4D (void);

      DgIDGGS4D& operator= (const DgIDGGS4D& rf);

      int radix (void) const { return radix_; }

   protected:

      int radix_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgQ2DICoord>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgQ2DICoord>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgOutLocTextFile.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutLocTextFile.cpp: DgOutLocTextFile class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgOutLocTextFile.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocTextFile::DgOutLocTextFile (const string& fileName, const DgRFBase& rf, 
                    bool isPointFile,  const string& suffix, int precision,
                    DgReportLevel failLevel)
   : DgOutputStream (fileName, suffix, failLevel),
     DgOutLocFile (fileName, rf, isPointFile, failLevel), 
     precision_ (precision)
{
} // DgOutLocTextFile::DgOutLocTextFile

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDmdD8Grid2DS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDmdD8Grid2DS.h: DgDmdD8Grid2DS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDMDD8GRID2DS_H 
#define DGDMDD8GRID2DS_H 

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgDiscRFS2D.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgDmdD8Grid2DS : public DgDiscRFS2D {

   public:

      DgDmdD8Grid2DS (DgRFNetwork& networkIn, 
                 const DgRF<DgDVec2D, long double>& backFrameIn,
                 int nRes = 1, unsigned int apertureIn = 4, 
                 bool isCongruentIn = true, bool isAlignedIn = false,
                 const string& nameIn = "8D4");

      DgDmdD8Grid2DS (const DgDmdD8Grid2DS& rf);

     ~DgDmdD8Grid2DS (void);

      DgDmdD8Grid2DS& operator= (const DgDmdD8Grid2DS& rf);

      int radix (void) const { return radix_; }

   protected:

      int radix_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgIVec2D>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgIVec2D>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgAddressBase.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgAddressBase.h: DgAddressBase class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGADDRESSBASE_H
#define DGADDRESSBASE_H

#include <iostream>

using namespace std;

class DgDistanceBase;

////////////////////////////////////////////////////////////////////////////////
class DgAddressBase {

   public:

      virtual ~DgAddressBase (void);

   protected:

      DgAddressBase (void) {}

      virtual ostream& writeTo (ostream& stream) const = 0;

   friend ostream& operator<< (ostream& stream, const DgAddressBase& add);

};

inline ostream& operator<< (ostream& stream, const DgAddressBase& add)
{ return add.writeTo(stream); }

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgProjISEA.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgProjISEA.cpp: DgProjISEA class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <limits>
#include <iostream>
#include <stdexcept>
#include "DgProjISEA.h"

////////////////////////////////////////////////////////////////////////////////
DgProjISEAInv::DgProjISEAInv (const DgRF<DgProjTriCoord, long double>& from,
                       const DgRF<DgGeoCoord, long double>& to)
         : DgConverter<DgProjTriCoord, long double, DgGeoCoord, long double>(from, to),
           pProjTriRF_ (0)
{ 
   pProjTriRF_ = dynamic_cast<const DgProjTriRF*>(&fromFrame());

   if (!pProjTriRF_)
   {
      report("DgProjISEAInv::DgProjISEAInv(): "
        " fromFrame not of type DgProjTriRF", DgBase::Fatal);
   }

} // DgProjISEAInv::DgProjISEAInv

////////////////////////////////////////////////////////////////////////////////
DgGeoCoord 
DgProjISEAInv::convertTypedAddress (const DgProjTriCoord& addIn) const
{
//cout << "***DgProjISEAInv: DgProjTriCoord: " << addIn << endl;
   IcosaGridPt gridpt;
   gridpt.pt.x = addIn.coord().x();
   gridpt.pt.y = addIn.coord().y();
   gridpt.triangle = addIn.triNum();

//cout << "    gridpt.triangle .x .y: " << gridpt.triangle << ", " <<
//      gridpt.pt.x << ", " << gridpt.pt.y << endl;

   GeoCoord ll = snyderInv(gridpt, projTriRF().sphIcosa().sphIcosa());

//cout << " ll.lon, ll.lat: " << ll.lon << ", " << 
//ll.lat << endl;
   DgGeoCoord geoPt(ll.lon, ll.lat);
   geoPt.normalize();

//cout << "    geoPt: " << geoPt << endl;
   return geoPt;

} // DgGeoCoord DgProjISEAInv::convertTypedAddress

////////////////////////////////////////////////////////////////////////////////
DgProjISEAFwd::DgProjISEAFwd (const DgRF<DgGeoCoord, long double>& from,
                    const DgRF<DgProjTriCoord, long double>& to)
         : DgConverter<DgGeoCoord, long double, DgProjTriCoord, long double>(from, to) 
{ 
   pProjTriRF_= dynamic_cast<const DgProjTriRF*>(&toFrame());

   if (!pProjTriRF_)
   {
      report("DgProjISEAFwd::DgProjISEAFwd(): "
        " toFrame not of type DgProjTriRF", DgBase::Fatal);
   }

} // DgProjISEAFwd::DgProjISEAFwd 

////////////////////////////////////////////////////////////////////////////////
DgProjTriCoord 
DgProjISEAFwd::convertTypedAddress (const DgGeoCoord& addIn) const
{
         
//cout << "***DgProjISEAFwd: geoPt: " << addIn << endl;
         GeoCoord ll;

   ll.lon = addIn.lon();
   ll.lat = addIn.lat();

//cout << "   ll.lon, ll.lat: " << ll.lon << ", " << ll.lat << endl;

   IcosaGridPt gridpt = snyderFwd(ll, projTriRF().sphIcosa());
//cout << "    gridpt.triangle .x .y: " << gridpt.triangle << ", " <<
//      gridpt.pt.x << ", " << gridpt.pt.y << endl;

//cout << "DgProjTriCoord: " << DgProjTriCoord(gridpt.triangle, 
//                               DgDVec2D(gridpt.pt.x, gridpt.pt.y)) << endl;

   return DgProjTriCoord(gridpt.triangle, DgDVec2D(gridpt.pt.x, gridpt.pt.y));

} // DgProjTriCoord DgProjISEAFwd::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/* 
   The C++ methods above are wrappers for the C functions below, which were
   written by <NAME> and <NAME>.
*/
////////////////////////////////////////////////////////////////////////////////

static const long double R1 = 0.9103832815L;
static const long double R1S = R1 * R1;

static const long double DH    = 37.37736814L * dgM_PI_180;
static const long double GH    = 36.0L * dgM_PI_180;
static const long double cot30 = 1.0L / tan(30.0 * dgM_PI_180);
static const long double tanDH = tan(DH);
static const long double cosDH = cos(DH);
static const long double sinGH = sin(GH);
static const long double cosGH = cos(GH);

static const long double originXOff = 0.6022955029L;
static const long double originYOff = 0.3477354707L;
static const long double icosaEdge = 2.0L * originXOff; 

////////////////////////////////////////////////////////////////////////////////
Vec2D sllxy (const GeoCoord& geoVect, SphIcosa& sphico, int nTri)
/*
   ISEA projection: from sphere to plane
*/
{
   long double ph, fh, azh, azh1, dazh, h, dz, z, azh0, ag, cosAzh, sinAzh;
   Vec2D  Planevect;
   const PreCompGeo& cent = sphico.triCen[nTri];

   long double cosLat = cos(geoVect.lat);
   long double sinLat = sin(geoVect.lat);

   dazh = sphico.dazh[nTri];

   z = acos(cent.sinLat * sinLat + cent.cosLat * cosLat * 
       cos(geoVect.lon - cent.pt.lon));

   if (z > DH + 0.00000005)
   {
      // std::cout<<"nTri: "<<nTri
      //          <<"z:    "<<z
      //          <<"DH+:  "<<(DH + 0.00000005)
      //          <<"diff: "<<((DH + 0.00000005) - z)
      //          <<"\n";
      // std::cout<<"1: The point: ";
      // printGeoCoord(geoVect);
      // std::cout<<" is located on another polygon.\n";
      throw std::runtime_error("sllxy found a point in another polygon!");
   }

   azh = atan2(cosLat * sin(geoVect.lon - cent.pt.lon), 
         cent.cosLat * sinLat - cent.sinLat * cosLat * cos(geoVect.lon - 
         cent.pt.lon)) - dazh;

   if (azh < 0.0) azh = azh + 2.0 * dgM_PI;
   azh0 = azh;
   if ((azh >= 120.0 * dgM_PI_180) && (azh <= 240.0 * dgM_PI_180)) azh -= 120.0 * dgM_PI_180;
   if (azh > 240.0 * dgM_PI_180) azh -= 240.0 * dgM_PI_180;

   cosAzh = cos(azh);
   sinAzh = sin(azh);

   dz = atan2(tanDH, cosAzh + cot30 * sinAzh);

   if (z > dz + 0.00000005)
   {
      // printf("2: The point: ");
      // printGeoCoord(geoVect);
      // printf(" is located on another polygon.\n");
      throw std::runtime_error("sllxy found a point located in another polygon!");
      // exit(1);
   }

   h = acos(sinAzh * sinGH * cosDH - cosAzh * cosGH);
   ag = azh + GH + h - 180.0 * dgM_PI_180;
   azh1 = atan2(2.0 * ag, R1S * tanDH * tanDH - 2.0 * ag * cot30);
   fh = tanDH / (2.0 * (cos(azh1) + cot30 * sin(azh1)) * sin(dz / 2.0));
   ph = 2.0 * R1 * fh * sin(z / 2.0);

   if ((azh0 >= 120.0 * dgM_PI_180) && (azh0 < 240.0 * dgM_PI_180)) azh1 += 120.0 * dgM_PI_180;
   if (azh0 >= 240.0 * dgM_PI_180) azh1 += 240 * dgM_PI_180;

   Planevect.x = (ph * sin(azh1) + originXOff) / icosaEdge;
   Planevect.y = (ph * cos(azh1) + originYOff) / icosaEdge;

   return (Planevect);

} /* Vec2D sllxy */

////////////////////////////////////////////////////////////////////////////////
IcosaGridPt snyderFwd (const GeoCoord& ll, DgSphIcosa& sphicosa)
/*
   project the point ll (lat, lon in radius) to the
   plane and return relevant info in IcosaGridPt
*/
{
   IcosaGridPt gridpt;

   gridpt.triangle = sphicosa.whichIcosaTri(ll);

   if (gridpt.triangle < 0)
   {
      // printf("ERROR: point in no triangle:");
      // printGeoCoord(ll); 
      // printf("\n");

      gridpt.pt.x = M_ZERO;
      gridpt.pt.y = M_ZERO;

      return gridpt;
   }

   gridpt.pt = sllxy(ll, sphicosa.sphIcosa(), gridpt.triangle);

   return gridpt;

} /* IcosaGridPt snyderFwd */

////////////////////////////////////////////////////////////////////////////////
GeoCoord snyderInv (const IcosaGridPt& icosaPt, SphIcosa& sphicosa)
/*
    project the point icosaPt.pt (x, y in ISEA in the coordinate
    system of the specified triangle) to lon, lat in radians

    this replaces the old snyderInv/sxyll combo.
*/
{
  long double ddazh,ph,fh,azh,azh1,dazh,h,fazh,flazh,dz,z;
  long double sinlat,sinlon;
  long double azh0;
  GeoCoord Geovect;
  const PreCompGeo& cent = sphicosa.triCen[icosaPt.triangle];
 
  Vec2D pt;
  pt.x = icosaPt.pt.x * icosaEdge - originXOff;
  pt.y = icosaPt.pt.y * icosaEdge - originYOff;

  ddazh = sphicosa.dazh[icosaPt.triangle];

  if ((fabs(pt.x) < PRECISION) && (fabs(pt.y) < PRECISION))
  {
    Geovect.lat=cent.pt.lat; Geovect.lon=cent.pt.lon;
  }
  else
  {  
    ph=sqrt(pt.x*pt.x+pt.y*pt.y);
    azh1=atan2(pt.x,pt.y);

    if (azh1<0.0) azh1=azh1+2*dgM_PI;
    azh0=azh1;
    if ((azh1>120.0*dgM_PI_180) && (azh1<=240.0*dgM_PI_180)) azh1=azh1-120.0*dgM_PI_180;
    if (azh1>240.0*dgM_PI_180) azh1=azh1-240.0*dgM_PI_180;

    azh=azh1;

    if (fabs(azh1) > PRECISION) 
    {
       long double agh=R1S*tanDH*tanDH/(2.0*(1.0/tan(azh1)+cot30));

       //cout << "agh: " << agh << endl;

       dazh=1.0; 
       while (fabs(dazh) > PRECISION)
        {
         h=acos(sin(azh)*sinGH*cosDH-cos(azh)*cosGH);
         fazh=agh-azh-GH-h+dgM_PI;
         flazh=((cos(azh)*sinGH*cosDH+sin(azh)*cosGH)/sin(h))-1.0;      
         dazh=-fazh/flazh;
         azh=azh+dazh;
         //cout << "loop: h: " << h << "  fazh: " << fazh*(180.0/dgM_PI) << 
         //  "  flazh: " << flazh*(180.0/dgM_PI) <<
         //  "  dazh: " << dazh*(180.0/dgM_PI) << 
         //  "  azh: " << azh*(180.0/dgM_PI) << endl;
        }   
    }
    else azh = azh1 = 0.0;

    dz=atan2(tanDH,cos(azh)+cot30*sin(azh));
    fh=tanDH/(2.0*(cos(azh1)+cot30*sin(azh1))*sin(dz/2.0));
    z=2.0*asin(ph/(2.0*R1*fh));
    if ((azh0>=120*dgM_PI_180) && (azh0<240*dgM_PI_180)) azh=azh+120*dgM_PI_180;
    if (azh0>=240*dgM_PI_180) azh=azh+240*dgM_PI_180;

    // now reposition to the actual triangle

    azh += ddazh;

    while (azh <= -dgM_PI) azh += M_2PI;
    while (azh > dgM_PI) azh -= M_2PI;

    sinlat=cent.sinLat * cos(z) + cent.cosLat * sin(z) * cos(azh);
    if (sinlat > M_ONE) sinlat = M_ONE;
    if (sinlat < -M_ONE) sinlat = -M_ONE;
    Geovect.lat = asin(sinlat);

    if (fabs(fabs(Geovect.lat) - dgM_PI_2) < M_EPSILON)
    {
       Geovect.lat = (Geovect.lat > M_ZERO) ? dgM_PI_2 : -dgM_PI_2;
       Geovect.lon = M_ZERO;
    }
    else
    {
      sinlon = sin(azh)*sin(z)/cos(Geovect.lat);
      long double coslon = (cos(z) - cent.sinLat * sin(Geovect.lat)) /
              cent.cosLat/cos(Geovect.lat);
      if (sinlon > M_ONE) sinlon = M_ONE;
      if (sinlon < -M_ONE) sinlon = -M_ONE;
      if (coslon > M_ONE) coslon = M_ONE;
      if (coslon < -M_ONE) coslon =-M_ONE;
      Geovect.lon = cent.pt.lon+asin(sinlon);
      Geovect.lon = cent.pt.lon+atan2(sinlon, coslon);
      if (Geovect.lon <= -dgM_PI) Geovect.lon += M_2PI;
      if (Geovect.lon >= dgM_PI) Geovect.lon -= M_2PI;
    }
  }
  return Geovect;

} /* GeoCoord snyderInv */

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDistanceBase.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDistanceBase.cpp: DgDistanceBase class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgDistance.h"

////////////////////////////////////////////////////////////////////////////////
DgDistanceBase::~DgDistanceBase (void)
{
   // virtual destructor

} // DgDistanceBase::~DgDistanceBase

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgInputStream.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgInputStream.h: DgInputStream class definition
//
//   This class provides wrappers around some basic input stream functionality
//   to increase ease of use.
//
// Version 6.2 - <NAME>, 9/10/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGINPUTSTREAM_H
#define DGINPUTSTREAM_H

#include <fstream>
#include <string>

using namespace std;

#include "DgBase.h"

////////////////////////////////////////////////////////////////////////////////
class DgInputStream : public ifstream, public DgBase {

   public:

      DgInputStream (void) : DgBase ("DgInputStream") {}

      DgInputStream (const string& fileNameIn,
                     const string& suffixIn  = string(""),
                     DgReportLevel failLevel = DgBase::Fatal);

      bool open (string fileName, DgReportLevel failLevel = DgBase::Fatal);

      static void setDefaultDir (const string& defaultDirIn)
                     { defaultDirectory_ = defaultDirIn; }

      void setSuffix (const string& suffixIn) { suffix_ = suffixIn; }

      const string& defaultDir (void) const { return defaultDirectory_; }
      const string& fileName   (void) const { return fileName_; }
      const string& suffix     (void) const { return suffix_; }

      void rewind (void) { seekg(std::streampos(0)); clear(); }

   private:

      static string defaultDirectory_;

      string fileName_;
      string suffix_;
};

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedIDGG.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedIDGG.h: DgBoundedIDGG class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBOUNDEDIDGG_H 
#define DGBOUNDEDIDGG_H

#include <cstdint>

#include "DgIDGG.h"
#include "DgGeoSphRF.h"
#include "DgBoundedRF.h"

using namespace std;

class DgBoundedRF2D;

////////////////////////////////////////////////////////////////////////////////
class DgBoundedIDGG : public DgBoundedRF<DgQ2DICoord, DgGeoCoord, long double> {

   public:

      DgBoundedIDGG (const DgIDGG& IDGGin);

      virtual DgQ2DICoord& incrementAddress (DgQ2DICoord& add) const;
      virtual DgQ2DICoord& decrementAddress (DgQ2DICoord& add) const;

      virtual bool validAddress (const DgQ2DICoord& add) const;

      const DgQ2DICoord& invalidAdd (void) const
                         { return idgg().undefAddress(); }

      const DgIDGG& idgg (void) const { return IDGG_; }

      std::uint64_t offsetPerQuad (void) const { return offsetPerQuad_; }

      virtual std::uint64_t seqNumAddress (const DgQ2DICoord& add) const;

      virtual DgQ2DICoord addFromSeqNum (std::uint64_t sNum) const;

   protected:

      const DgBoundedRF2D& bnd2D (void) const { return *bnd2D_; }

   private:

      const DgIDGG& IDGG_;
      DgBoundedRF2D* bnd2D_;
      std::uint64_t offsetPerQuad_;
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#endif


<|start_filename|>src/DgDiscRF_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDiscRF_template.h: DgDiscRF template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

template<class A, class B, class DB> void
DgDiscRF<A, B, DB>::setVertices (const DgLocation& loc, DgPolygon& vec) const
{
   vec.clearAddress(); 
   backFrame().convert(vec);
   
   if (loc.rf() == *this)
   {
      setAddVertices(*(this->getAddress(loc)), vec);
   }
   else
   {
      DgLocation tmpLoc(loc);
      this->convert(&tmpLoc);
      setAddVertices(*(this->getAddress(tmpLoc)), vec);
   }

} // void DgDiscRF::setVertices

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRF<A, B, DB>::setVertices (const DgLocation& loc, const DgRFBase& rf,
                                                     DgPolygon& vec) const
{
   setVertices(loc, vec);
   if (rf != backFrame()) backFrame().convert(vec);

} // const DgLocVector& DgDiscRF::setVertices

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRF<A, B, DB>::setNeighbors (const DgLocation& loc, DgLocVector& vec) const
{
   vec.clearAddress(); 
   this->convert(vec);
   
   if (loc.rf() == *this)
   {
      setAddNeighbors(*(this->getAddress(loc)), vec);
   }
   else
   {
      DgLocation tmpLoc(loc);
      this->convert(&tmpLoc);
      setAddNeighbors(*(this->getAddress(tmpLoc)), vec);
   }

} // void DgDiscRF::setNeighbors

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRF<A, B, DB>::setPoint (const DgLocation& loc, DgLocation& point) const
{
   if (loc.rf() == *this)
   {
      setAddPoint(*(this->getAddress(loc)), point);
   }
   else
   {
      DgLocation tmpLoc(loc);
      this->convert(&tmpLoc);
      setAddPoint(*(this->getAddress(tmpLoc)), point);
   }

} // void DgDiscRF::setPoint

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRF<A, B, DB>::setPoint (const DgLocation& loc, const DgRFBase& rf,
                                                     DgLocation& point) const
{
   setPoint(loc, point);
   if (rf != backFrame()) backFrame().convert(&point);

} // void DgDiscRF::setPoint

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRF<A, B, DB>::setAddPoint (const A& add, DgLocation& pt) const
{
   DgLocation* tmpLoc = backFrame().makeLocation(invQuantify(add));

   pt = *tmpLoc;

   delete tmpLoc;

} // void DgDiscRF<A, B, DB>::setPoint

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgSpatialDB.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSpatialDB.h: DgSpatialDB class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSPATIALDB_H
#define DGSPATIALDB_H

#include "DgPhysicalRF.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
template<class C> class DgSpatialDB {

   public:
   
      class iterator : public DgLocation {

         public:

            iterator (DgSpatialDB<C>& db) 
               : DgLocation (db.rf()), db_ (&db) {}

            iterator (DgSpatialDB<C>& db, const DgLocation& loc) 
               : DgLocation (db.rf()), db_ (&db) { *this = loc; }

            iterator (const iterator& it) 
               : DgLocation (it), db_ (&it.db()) { }

            iterator& operator++ (void) 
                { db().boundedRF().incrementLocation(*this, true); 
                  return *this; } 

            iterator& operator-- (void) 
                { db().boundedRF().decrementLocation(*this, true); 
                  return *this; } 

            C* operator* (void) const 
                { return db_->getContents(*this, false); }

            C& operator-> (void) { return *(db_->getContents(*this, true)); }
            
            const DgSpatialDB<C>& db (void) const { return *db_; }

            iterator& operator= (const iterator& it) 
                { DgLocation::operator=(it); db_ = &it.db(); return *this; }

            iterator& operator= (const DgLocation& loc)
                { DgLocation tmpLoc(loc); rf().convert(&tmpLoc);
                  DgLocation::operator=(tmpLoc); return *this; }

            bool operator== (const iterator& it) const
                   { return (DgLocation::operator==(it) && it.db() == db()); }
        
            bool operator!= (const iterator& it) const
                   { return !operator==(it); }

         protected:
         
            const DgSpatialDB<C>* db_;
      };

      DgSpatialDB<C> (DgPhysicalRFBase<C>& rfIn)
         : physicalRF_ (rfIn), begin_ (*this), end_ (*this)
         {  begin_ = boundedRF().first(); end_ = boundedRF().end(); 
            rfIn.initAllCells(); }

      virtual ~DgSpatialDB (void) { }

      const DgPhysicalRFBase<C>& physRF (void) const { return physicalRF_; }

      const DgBoundedRFBase& boundedRF (void) const 
                     { return physicalRF_.boundedRFBase(); }

      const DgRFBase& rf (void) const { return boundedRF().rf(); }

      bool operator== (const DgSpatialDB<C>& dbIn) const
         { return physicalRF_ == dbIn.physicalRF_; }

      bool operator!= (const DgSpatialDB<C>& dbIn) const
         { return !operator==(dbIn.physicalRF_); }

      C* getContents (const DgLocation& loc, bool convert = true,
                      bool allocate = false) const
            { return physicalRF_.getContents(loc, convert, allocate); }

      void replaceContents (const DgLocation& loc, C* cont, 
                            bool convert = true) // no copy
            { physicalRF_.replaceContents(loc, cont, convert); }

      void setContents (const DgLocation& loc, const C& cont, 
                        bool convert = true) // makes copy
            { physicalRF_.setContents(loc, cont, convert); }

      void deleteAddContents (const DgLocation& loc, bool convert = true)
            { physicalRF_.deleteAddContents(loc, convert); }

      bool validAddress (const DgLocation& loc, bool convert = true) const
            { return rf().validAddress(loc, convert); }

      virtual const iterator& begin (void) const { return begin_; }      
      virtual const iterator& end   (void) const { return end_; }

   protected:

      DgPhysicalRFBase<C>& physicalRF_;
      iterator begin_;
      iterator end_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgLocList.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgLocList.h: DgLocList class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////
//
//  The DgLocList class defines a set of locations which can be treated as a 
//  group for purposes of conversion, etc.
//
//  Note: add only loc's of the correct RF or use push_back. Other STL list
//    methods should be checked/corrected for RF-safeness.
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGLOCLIST_H
#define DGLOCLIST_H

#include <list>
#include <functional>

#include "DgLocBase.h"

////////////////////////////////////////////////////////////////////////////////
class DgLocList : public DgLocBase, public list<DgLocBase*> {

   public:

      DgLocList (void) : isOwner_ (true) { }

      DgLocList (const DgRFBase& rfIn) : DgLocBase(rfIn), isOwner_ (true) { }

     ~DgLocList (void);

      void destroy (void);

      bool isOwner (void) const { return isOwner_; }

      void setIsOwner (bool isOwnerIn) { isOwner_ = isOwnerIn; }

      virtual void clearAddress (void);

      //virtual bool thin (float dMin = 0.0, bool clear = true);

      virtual int cardinality (void) const;

      DgLocList& operator= (const DgLocList& list); // does not make copy

      //bool operator== (const DgLocList& list) const;

      //bool operator!= (const DgLocList& list) const
      //     { return !operator==(list); }

      virtual string asString (void) const;
      virtual string asAddressString (void) const;

      virtual string asString (char delimiter) const;
      virtual string asAddressString (char delimiter) const;

      virtual const char* fromString (const char* str, char delimiter);

      void push_back (DgLocBase* loc);

   protected:

      virtual void convertTo (const DgRFBase& rf);

   private:

      bool isOwner_;

};

////////////////////////////////////////////////////////////////////////////////
ostream& operator<< (ostream& stream, const DgLocList& list);

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgRF_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRF_template.h: DgRF template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cstdint>

#include "DgBase.h"
#include "DgLocation.h"
#include "DgLocVector.h"
#include "DgDistance.h"
#include "DgConverter.h"

////////////////////////////////////////////////////////////////////////////////
template<class A, class D> 
DgRF<A, D>::~DgRF (void)
{
   // virtual destructor

} // DgRF::~DgRF

////////////////////////////////////////////////////////////////////////////////
template<class A, class D> DgLocation*
DgRF<A, D>::createLocation (const DgLocation& loc, bool conv) const
{
   if (loc.rf() == *this)
   {
      return new DgLocation(loc);
   }
   else if (loc.rf().network() != network())
   {
      report("DgRF<A, D>::getConverter() location not in this network",
             DgBase::Fatal);
      return 0;
   }
   else if (conv)
   {
      DgLocation* newLoc = new DgLocation(loc);
      convert(newLoc);

      return newLoc;
   }
   else
   {
      report("DgRF<A, D>::getConverter() location not from this rf"
             " and conversion not specified",
             DgBase::Fatal);
      return 0;
   }

} // DgLocation* DgRF<A>::createLocation

////////////////////////////////////////////////////////////////////////////////
template<class A, class D> DgLocation*
DgRF<A, D>::makeLocation (const A& addIn) const
{
   return buildLocation(new DgAddress<A>(addIn));

} // DgLocation* DgRF<A>::makeLocation

////////////////////////////////////////////////////////////////////////////////
template<class A, class D> const A*
DgRF<A, D>::getAddress (const DgLocation& loc) const
{
   if (loc.rf() != *this)
   {
      report("DgRF<A, D>::getAddress() location not from this rf",
             DgBase::Fatal);
      return 0;
   }

   if (loc.address())
   {
      return (&(static_cast<const DgAddress<A>*>(loc.address()))->address()); 
   }
   else
   {
      return 0;
   }

} // const A* DgRF<A>::getAddress

////////////////////////////////////////////////////////////////////////////////
template<class A, class D> void 
DgRF<A, D>::buildLocVector (DgLocVector* vec, const vector<A*> inVec) const
{
   vec->clearAddress();
   vec->resize(inVec.size());
   for (unsigned int i = 0; i < vec->size(); i++) 
   {
      vec->vec_[i] = new DgAddress<A>(*inVec[i]);
   }

} // void DgRF<A, D>::buildLocVector

////////////////////////////////////////////////////////////////////////////////
template<class A, class D> DgDistanceBase*
DgRF<A, D>::distance (const DgLocation& loc1, const DgLocation& loc2,
                            bool conv) const
{
   if (loc1.rf() == *this && loc2.rf() == *this)
   {
      const A* add1 = getAddress(loc1);
      const A* add2 = getAddress(loc2);
      if (!add1 || !add2)
      {
         report("DgRF<A, D>::distance() null address", DgBase::Fatal);
         return 0;
      }

      return new DgDistance<D>(*this, dist(*add1, *add2));
   }
   else if (loc1.rf().network() != network() ||
            loc2.rf().network() != network())
   {
      report("DgRF<A, D>::distance() location not in this network",
             DgBase::Fatal);
      return 0;
   }
   else if (conv)
   {
      A add1;
      A add2;

      if (loc1.rf() != *this)
      {
         DgLocation* pLoc1 = createLocation(loc1);
         convert(pLoc1);
         const A* pAdd1 = getAddress(*pLoc1);
         if (!pAdd1)
         {
            report("DgRF<A, D>::distance() null address", DgBase::Fatal);
            return 0;
         }
         add1 = *pAdd1;
         delete pLoc1;
      }

      if (loc2.rf() != *this)
      {
         DgLocation* pLoc2 = createLocation(loc2);
         convert(pLoc2);
         const A* pAdd2 = getAddress(*pLoc2);
         if (!pAdd2)
         {
            report("DgRF<A, D>::distance() null address", DgBase::Fatal);
            return 0;
         }
         add2 = *pAdd2;
         delete pLoc2;
      }

      return new DgDistance<D>(*this, dist(add1, add2));
   }
   else
   {
      report("DgRF<A, D>::distance() location not from this rf"
             " and conversion not specified", DgBase::Fatal);
      return 0;
   }

} // DgDistanceBase* DgRF<A, D>::distance

////////////////////////////////////////////////////////////////////////////////
template<class A, class D> D
DgRF<A, D>::getDistance (const DgDistanceBase& dist) const
{
   D d;
   if (dist.rf() != *this)
   {
      report("DgRF<A, D>::getDistance() distance not from this rf",
             DgBase::Fatal);
   }

   return ((static_cast<const DgDistance<D>&>(dist)).distance()); 

} // D DgRF<A, D>::getDistance

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toString (const DgLocation& loc) const
{
   string str;

   if (loc.rf() != *this)
   {
      report("DgRF<A, D>::toString(" + loc.asString() + 
             ") location not from this rf", DgBase::Fatal);
      return str;
   }

   str = name() + "{";

   const A* add = getAddress(loc);
   if (add)
   {
      str += add2str(*add) + "}";
   }
   else
   {
      str += "NULL}";
   }

   return str;

} // string DgRF<A, D>::toString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toString (const DgLocation& loc, char delimiter) const
{
   string str;

   if (loc.rf() != *this)
   {
      report("DgRF<A, D>::toString(" + loc.asString() + 
             ") location not from this rf", DgBase::Fatal);
      return str;
   }

   const A* add = getAddress(loc);
   if (add)
   {
      str = add2str(*add, delimiter);
   }
   else
   {
      str = "NULL";
   }

   return str;

} // string DgRF<A, D>::toString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> const char*
DgRF<A, D>::fromString (DgLocation& loc, const char* str, char delimiter) const
{
   A add;
   const char* tmp = str2add(&add, str, delimiter);
   if (add == undefAddress())
   {
      ::report("DgRF<A, D>::fromString() invalid address string " + string(str),
               DgBase::Fatal);
   }

   DgLocation* tloc = makeLocation(add);
   loc = *tloc;
   delete tloc;

   return tmp;

} // const char* DgRF<A, D>::fromString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toString (const DgLocVector& locVec) const
{
   string str;

   if (locVec.rf() != *this)
   {
      report("DgRF<A, D>::toString(" + locVec.asString() + 
             ") location vector not from this rf", DgBase::Fatal);
      return str;
   }

   str = name() + "{\n";
   const vector<DgAddressBase*>& v = locVec.addressVec();
   for (unsigned int i = 0; i < v.size(); i++)
   {
      const A& add = (static_cast<const DgAddress<A>*>(v[i]))->address();
      str += add2str(add) + "\n";
   }
   str += "}";

   return str;

} // string DgRF<A, D>::toString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toString (const DgLocVector& locVec, char delimiter) const
{
   string str;

   if (locVec.rf() != *this)
   {
      report("DgRF<A, D>::toString(" + locVec.asString() + 
             ") location vector not from this rf", DgBase::Fatal);
      return str;
   }

   const vector<DgAddressBase*>& v = locVec.addressVec();
   for (unsigned int i = 0; i < v.size(); i++)
   {
      const A& add = (static_cast<const DgAddress<A>*>(v[i]))->address();
      str += add2str(add, delimiter) + "\n";
   }

   return str;

} // string DgRF<A, D>::toString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toAddressString (const DgLocation& loc) const
{
   string str;

   if (loc.rf() != *this)
   {
      report("DgRF<A, D>::toAddressString(" + loc.asString() + 
             ") location not from this rf", DgBase::Fatal);
      return str;
   }

   const A* add = getAddress(loc);
   if (add)
   {
      str = add2str(*add);
   }
   else
   {
      str = "(NULL)";
   }

   return str;

} // string DgRF<A, D>::toAddressString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toAddressString (const DgLocation& loc, char delimiter) const
{
   string str;

   if (loc.rf() != *this)
   {
      report("DgRF<A, D>::toAddressString(" + loc.asString() + 
             ") location not from this rf", DgBase::Fatal);
      return str;
   }

   const A* add = getAddress(loc);
   if (add)
   {
      str = add2str(*add, delimiter);
   }
   else
   {
      str = "NULL";
   }

   return str;

} // string DgRF<A, D>::toAddressString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toAddressString (const DgLocVector& locVec) const
{
   string str;

   if (locVec.rf() != *this)
   {
      report("DgRF<A, D>::toAddressString(" + locVec.asString() + 
             ") location vector not from this rf", DgBase::Fatal);
      return str;
   }

   str = "{\n";
   const vector<DgAddressBase*>& v = locVec.addressVec();
   for (unsigned int i = 0; i < v.size(); i++)
   {
      const A& add = (static_cast<const DgAddress<A>*>(v[i]))->address();
      str += add2str(add) + "\n";
   }
   str += "}";

   return str;

} // string DgRF<A, D>::toAddressString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toAddressString (const DgLocVector& locVec, char delimiter) const
{
   string str;

   if (locVec.rf() != *this)
   {
      report("DgRF<A, D>::toAddressString(" + locVec.asString() + 
             ") location vector not from this rf", DgBase::Fatal);
      return str;
   }

   const vector<DgAddressBase*>& v = locVec.addressVec();
   for (unsigned int i = 0; i < v.size(); i++)
   {
      const A& add = (static_cast<const DgAddress<A>*>(v[i]))->address();
      str += add2str(add, delimiter) + "\n";
   }

   return str;

} // string DgRF<A, D>::toAddressString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> string
DgRF<A, D>::toString (const DgDistanceBase& dist) const
{
   string str;

   if (dist.rf() != *this)
   {
      report("DgRF<A, D>::toString(" + dist.asString() + 
             ") distance not from this rf", DgBase::Fatal);
      return str;
   }

   str = name() + "{" + 
         dist2str((static_cast<const DgDistance<D>&>(dist)).distance()) + "}";

   return str;

} // string DgRF<A, D>::toString

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> long double
DgRF<A, D>::toDouble (const DgDistanceBase& dist) const
{
   if (dist.rf() != *this)
   {
      report("DgRF<A, D>::toDouble(" + dist.asString() + 
             ") distance not from this rf", DgBase::Fatal);
      return -1;
   }

   return dist2dbl((static_cast<const DgDistance<D>&>(dist)).distance());

} // long double DgRF<A, D>::toDouble

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> 
std::uint64_t
DgRF<A, D>::toInt (const DgDistanceBase& dist) const
{
   if (dist.rf() != *this)
   {
      report("DgRF<A, D>::toInt(" + dist.asString() + 
             ") distance not from this rf", DgBase::Fatal);
      return 0;
   }

   return dist2int((static_cast<const DgDistance<D>&>(dist)).distance());

} // std::uint64_t DgRF<A, D>::toInt

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> void
DgRF<A, D>::jumpRF (DgLocation* loc)
{
   const DgRF<A, D>* newRF = dynamic_cast<const DgRF<A, D>*>(&loc->rf());
   if (!newRF)
   {
      report("DgRF<A, D>::jumpTo(" + loc->asString() + 
             ") does not match type of " + name(), DgBase::Fatal);
   }

   forceRF(loc);

} // void DgRF<A, D>::jumpRF

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////



<|start_filename|>src/Dg2WayConverter.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// Dg2WayConverter.h: Dg2WayConverter class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DG2WAYCONVERTER_H
#define DG2WAYCONVERTER_H

class DgRFBase;

////////////////////////////////////////////////////////////////////////////////
class Dg2WayConverter {

   public:

      Dg2WayConverter (const DgConverterBase& forward,
                       const DgConverterBase& inverse);

      Dg2WayConverter (const Dg2WayConverter& con)
         : forward_ (&con.forward()), inverse_ (&con.inverse()) {}

      Dg2WayConverter& operator= (const Dg2WayConverter& con)
         { forward_ = &con.forward(); inverse_ = &con.inverse(); 
           return *this; }

      const DgConverterBase& forward (void) const { return *forward_; }
      const DgConverterBase& inverse (void) const { return *inverse_; }

   protected:

      const DgConverterBase* forward_;
      const DgConverterBase* inverse_;

};

////////////////////////////////////////////////////////////////////////////////
inline
Dg2WayConverter::Dg2WayConverter (const DgConverterBase& forward,
                                  const DgConverterBase& inverse)
{
   if (forward.fromFrame() != inverse.toFrame() ||
       forward.toFrame()   != inverse.fromFrame())
   {
      report("Dg2WayConverter::Dg2WayConverter() rf mismatch", DgBase::Fatal);
   }

   forward_ = &forward;
   inverse_ = &inverse;

} // Dg2WayConverter::Dg2WayConverter

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgEllipsoidRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgEllipsoidRF.h: DgEllipsoidRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGELLIPSOIDRF_H
#define DGELLIPSOIDRF_H

#include <limits>
#include <iostream>
#include <cstdint>

#include "DgConstants.h"
#include "DgGeoDatumRF.h"
#include "DgDVec2D.h"

using namespace std;

typedef struct GeoCoord {

   long double lat;
   long double lon;

} GeoCoord;

class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgGeoCoord : public DgDVec2D {

   public:

      static const DgGeoCoord undefGeoCoord;

      static const long double tolerance; // decimal degrees

      static long double gcDist (const DgGeoCoord& g1, const DgGeoCoord& g2,
                            bool rads = true);

      static DgGeoCoord gcIntersect (const DgGeoCoord& g11,
                  const DgGeoCoord& g12, const DgGeoCoord& g21,
                  const DgGeoCoord& g22);

      static long double geoTriArea (const DgGeoCoord& g1, const DgGeoCoord& g2,
                                const DgGeoCoord& g3);

      static long double geoPolyArea (const DgPolygon& poly, 
                                 const DgGeoCoord center);

      DgGeoCoord (void) { }

      DgGeoCoord (const DgGeoCoord& coord) { *this = coord; }

      DgGeoCoord (const DgDVec2D& coord, bool rads = true)
        { if (rads) *this = coord; else *this = coord * dgM_PI_180; } 

      DgGeoCoord (long double lon, long double lat, bool rads = true) 
        { if (rads) *this = DgDVec2D(lon, lat); 
          else *this = DgDVec2D(lon * dgM_PI_180, lat * dgM_PI_180); }

      DgGeoCoord (const GeoCoord& coord)
           { *this = DgDVec2D(coord.lon, coord.lat); }

      DgGeoCoord& operator= (const DgGeoCoord& coord)
           { DgDVec2D::operator=(coord); return *this; }

      DgGeoCoord& operator= (const DgDVec2D& coord)
           { DgDVec2D::operator=(coord); return *this; }

      operator string (void) const
           { return "(" + dgg::util::to_string(lonDegs()) + ", " + 
		   dgg::util::to_string(latDegs()) + ")"; }

      long double lat (void) const { return y(); } // latitude in radians
      long double lon (void) const { return x(); } // longitude in radians

      long double latDegs (void) const { return lat() * M_180_PI; }
      long double lonDegs (void) const { return lon() * M_180_PI; }

      void setLat (long double rads) { setY(rads); }
      void setLon (long double rads) { setX(rads); }

      void setLatDeg (long double degs) { setY(degs * dgM_PI_180); }
      void setLonDeg (long double degs) { setX(degs * dgM_PI_180); }

      void normalize (void)
           {
              if (fabs(latDegs()) >= (90.0L - tolerance))
              {
                 setLon(0.0L);
              }
              else
              {
                 while (lonDegs() <= -180.0L) setLonDeg(lonDegs() + 360.0L);
                 while (lonDegs() > 180.0L) setLonDeg(lonDegs() - 360.0L);
              }
           }

};

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgGeoCoord& pt)
{
   return stream << string(pt);

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgEllipsoidRF : public DgGeoDatumRF<DgGeoCoord, long double> {

   public:

      DgEllipsoidRF (DgRFNetwork& networkIn, const string& nameIn)
               : DgGeoDatumRF<DgGeoCoord, long double> (networkIn, nameIn),
                 a_ (-1.0L), b_ (-1.0L), f_ (-1.0L), e_ (-1.0L), es_ (-1.0L),
                 as_ (-1.0L), bs_ (-1.0L), ra_ (-1.0L), one_es_ (-1.0L),
                 rone_es_ (-1.0L) { }

      DgEllipsoidRF (DgRFNetwork& networkIn, const string& nameIn,
                   const DgEllipsoidRF& ell)
               : DgGeoDatumRF<DgGeoCoord, long double> (networkIn, nameIn),
                 a_ (ell.a()), b_ (ell.b()), f_ (ell.f()),
                 e_ (ell.e()), es_ (ell.es()), as_ (ell.as()), bs_ (ell.bs()),
                 ra_ (ell.ra()), one_es_ (ell.one_es()),
                 rone_es_ (ell.rone_es())
           { undefLoc_ = makeLocation(undefAddress()); }

      DgEllipsoidRF (DgRFNetwork& networkIn, const string& nameIn, 
                   long double aIn, long double bIn)
               : DgGeoDatumRF<DgGeoCoord, long double> (networkIn, nameIn),
                 a_ (aIn), b_ (bIn)
                { 
                   undefLoc_ = makeLocation(undefAddress());

                   f_ = (a() - b()) / a();
                   as_ = a() * a();
                   bs_ = b() * b();
                   es_ = 1.0L - bs() / as();
                   e_ = sqrt(es());
                   ra_ = 1.0L / a();
                   one_es_ = 1.0L - es();
                   rone_es_ = 1.0L / one_es();
                }  

      DgEllipsoidRF& operator= (const DgEllipsoidRF& ell)
               {
                  if (&ell != this)
                  {
                     a_ = ell.a();
                     b_ = ell.b();
                     f_ = ell.f();
                     e_ = ell.e();
                     es_ = ell.es();
                     as_ = ell.as();
                     bs_ = ell.bs();
                     ra_ = ell.ra();
                     one_es_ = ell.one_es();
                     rone_es_ = ell.rone_es();
                  }

                  return *this;

               } // DgEllipsoidRF::operator=

/*
      bool operator== (const DgEllipsoidRF& ell) const
               {
                  return (a() == ell.a() &&
                          b() == ell.b());

               } // bool DgEllipsoidRF::operator==

      bool operator!= (const DgEllipsoidRF& ell) const
               {
                  return !operator==(ell);

               } // bool DgEllipsoidRF::operator!=
*/

      // get methods

      long double a (void) const { return a_; }

      long double b (void) const { return b_; }

      long double f (void) const { return f_; }

      long double e (void) const { return e_; }

      long double es (void) const { return es_; }

      long double as (void) const { return as_; }

      long double bs (void) const { return bs_; }

      long double ra (void) const { return ra_; }

      long double one_es (void) const { return one_es_; }

      long double rone_es (void) const { return rone_es_; }

      // set methods

      void setA (long double aIn) { a_ = aIn; }

      void setB (long double bIn) { b_ = bIn; }

      void setF (long double fIn) { f_ = fIn; }

      void setE (long double eIn) { e_ = eIn; }

      void setEs (long double esIn) { es_ = esIn; }

      void setAs (long double asIn) { as_ = asIn; }

      void setBs (long double bsIn) { bs_ = bsIn; }

      void setRa (long double raIn) { ra_ = raIn; }

      void setOne_es (long double one_esIn) { one_es_ = one_esIn; }

      void setRone_es (long double rone_esIn) { rone_es_ = rone_esIn; }

      virtual const DgGeoCoord& undefAddress (void) const
               { return DgGeoCoord::undefGeoCoord; }

      // the following routines are "back-doors" included for speed;
      // use with care!

      virtual DgAddressBase* vecAddress (const DgDVec2D& v) const
                    { return new DgAddress<DgGeoCoord>(DgGeoCoord(v, false)); }

      virtual DgLocation* vecLocation (const DgDVec2D& v) const
                    { return makeLocation(DgGeoCoord(v, false)); }

      virtual DgDVec2D getVecAddress (const DgAddressBase& add) const
         { 
            const DgGeoCoord& g = 
                  static_cast< const DgAddress<DgGeoCoord> &>(add).address(); 
            return DgDVec2D(g.lonDegs(), g.latDegs());
         }

      virtual DgDVec2D getVecLocation (const DgLocation& loc) const
                    { return DgDVec2D(getAddress(loc)->lonDegs(),
                                      getAddress(loc)->latDegs()); }

      // distance in km; not currently defined (except for DgGeoSphRF)

      virtual long double dist (const DgGeoCoord& add1, const DgGeoCoord& add2) const
         { return 1.0L; } 

      virtual string add2str (const DgGeoCoord& add) const
                       { return string(add); }

      virtual string add2str (const DgGeoCoord& add, char delimiter) const
                { return dgg::util::to_string(add.lonDegs(), formatStr()) + delimiter +
                         dgg::util::to_string(add.latDegs(), formatStr()); }

      virtual const char* str2add (DgGeoCoord* add, const char* str, 
                                   char delimiter) const;

      virtual string dist2str (const long double& dist) const
                       { return dgg::util::to_string(dist, formatStr()); }

      virtual long double dist2dbl (const long double& dist) const
                       { return dist; }

      virtual std::uint64_t dist2int (const long double& dist) const
                       { return static_cast<std::uint64_t>(dist); }

   private:

      long double a_; // semi-major axis in meters 

      long double b_; // semi-minor axis in meters

      // values used by PROJ4 projections

      long double f_; // flattening = (a - b) / a

      long double e_; // eccentricity

      long double es_; // e squared

      long double as_; // a squared

      long double bs_; // b squared

      long double ra_; // 1 / a

      long double one_es_; // 1 / es

      long double rone_es_; // 1 / one_es

}; // class DgEllipsoidRF

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgEllipsoidRF& ell)
{
   return stream << "a: " << ell.a() << " " << "b: " << ell.b() << " "
                 << "f: " << ell.f() << " " << "e: " << ell.e(); 

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*  
   Below are typedefs, defines, and function prototypes for vector and 
   spherical trig routines.

   By <NAME> and <NAME>.
*/
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

/**** macros ****/

#define UNDEFVAL  std::numeric_limits<long double>::max()
#define UNDEFINT  std::numeric_limits<int>::max()

#define PRECISION 0.0000000000005L /* precise 12 digits after dot  */

/**** typedefs ****/

typedef struct Vec2D {

   long double x;
   long double y;

   Vec2D()
    : x(0.0L), y(0.0L)
   {}

} Vec2D;

typedef struct Vec3D {

   long double x;
   long double y;
   long double z;

   Vec3D()
    : x(0.0L), y(0.0L), z(0.0L)
   {}

} Vec3D;

typedef struct SphTri {

   std::int64_t code; 
   GeoCoord verts[3];  /* vertices in degrees */
   long double   edges[3];  /* edges opposite to verts in central angle degrees */
   long double   angles[3]; /* interior angles in degrees corresponding to verts */
   long double   area;      /* area in km */
   long double   perimeter;  /* perimeter in km */
   long double   compactness;

} SphTri;

typedef struct PlaneTri {

   std::int64_t code;
   std::int64_t direction; /* 0: up, 1: down */
   Vec2D    points[3]; /* points in plane triangle in km */ 
   Vec2D    cenpoint;  /* central point of plane triangle in km */ 
 
} PlaneTri;

typedef struct SCtri {

  std::int64_t code;
  GeoCoord verts[3]; /* vertices in radius*/
  GeoCoord poles[3];  
  long double edges[3];
  long double area;
  long double perimeter;
  long double sclat[3]; 
         /* latitude from pole of small circle v1v2 in radius */
/*  long double   darea[3];
     area surounded by great circle and small circle of two points.
       positive means small circle is more convex than great circle
       from the center of the triangle. */

} SCtri;

/* precomputed trig info for a geodetic point */

typedef struct PreCompGeo {

   GeoCoord pt;
   long double sinLat;
   long double sinLon;
   long double cosLat;
   long double cosLon;

} PreCompGeo;

/* pre-computed info corresponding to a spherical triangle 
   (for use in finding if a point lies in the triangle) */

typedef struct PreCompInTri {

   long double p0x0;
   long double p0y0;
   long double p0z0;

   long double p0x1;
   long double p0y1;
   long double p0z1;

   long double p0x2;
   long double p0y2;
   long double p0z2;

   long double t00;
   long double t01;
   long double t02;

} PreCompInTri;

typedef struct SphIcosa {

   /* sufficient icosa placement data */

   GeoCoord pt;
   long double azimuth;

   /* pre-calculated projection values */

   GeoCoord icoverts[12];
   GeoCoord icotri[20][3];
   PreCompGeo triCen[20];
   PreCompInTri ptin[20];
   long double dazh[20];

} SphIcosa;

typedef struct IcosaGridPt {

   Vec2D pt; /* the point itself in triangle coordinates */
   int triangle; /* index (0 - 19) of the triangle */

} IcosaGridPt;

/**** function prototypes ****/

/* printing functions */

void   printVal      (long double val);  /* print val or 'UNDEFVAL' to stdout */
void   printGeoCoord (const GeoCoord& p);  /* print p to stdout */
void   printVec2D    (const Vec2D& p);     /* print p to stdout */
void   printVec3D    (const Vec3D& p);     /* print p to stdout */
void   printSphTri   (const SphTri& tri);  /* print tri to stdout */
void   printPlaneTri (const PlaneTri& tri);/* print plane tri to stdout */

/* Vec3D functions */

Vec3D  vecAdd        (const Vec3D& A, const Vec3D& B); /* return A + B */
Vec3D  vecSub        (const Vec3D& A, const Vec3D& B); /* return A - B */
Vec3D  vecCross      (const Vec3D& A, const Vec3D& B); /* return A x B */
long double vecDot        (const Vec3D& A, const Vec3D& B); /* return A . B */
long double vecMag        (const Vec3D& V);          /* return |V| */
Vec3D  vecNormalize  (const Vec3D& V);          /* return V as a unit vector */

/* spherical triangle functions */

void sphTriInit (SphTri* tri); /* initialize with UNDEFVAL values */

void planeTriInit (PlaneTri* tri); /* initialize with UNDEFVAL values */

/* solve for three sides,three angles and area */
void sphTriSolve (SphTri* tri);

/* calculate the center point of a sphere triangle */
GeoCoord sphTricenpoint(GeoCoord sp[3]); 

/* sphere functions */

GeoCoord xyzll(const Vec3D& v); /* transform a point from xyz to latlon */

Vec3D llxyz(const GeoCoord& sv); /* transform a point from latlon to xyz */

/* calculate the chord distance */
long double chorddist(const GeoCoord& ll1,const GeoCoord& ll2); 

/* calculate the sphere distance */
long double spheredist(const GeoCoord& ll1,const GeoCoord& ll2); 

/* decide if pt is in sphere triangle */ 
int ptinsphTri(const GeoCoord& pt, GeoCoord sTri[3]); 

/* return the middle point of the great circle */
GeoCoord GCmidpoint(const GeoCoord& pp1, const GeoCoord& pp2); 

/* return intersect point of two great circle */
GeoCoord GCintersect(const GeoCoord& sv11, const GeoCoord& sv12, 
                     const GeoCoord& sv21, const GeoCoord& sv22, int sign);

/* return latitude of a point with known longtitude on great circle */
long double GCptlat(long double lon, const GeoCoord& sv1, const GeoCoord& sv2);

/* return azimuth from pt1 to pt2 */
long double Azimuth(const GeoCoord& pt1, const GeoCoord& pt2); 

/* return Geopoint that have great-circle-distance d along azimuth az from pt */
GeoCoord GCdaz(const GeoCoord& pt, long double d, long double az); 

/******************************************************************************/

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#endif


<|start_filename|>src/DgIVec3D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIVec3D.h: DgIVec3D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIVEC3D_H
#define DGIVEC3D_H

#include <cmath>
#include <string>
#include <cstdint>

#include "DgUtil.h"
#include "DgIVec2D.h"
#include "DgDVec2D.h"

////////////////////////////////////////////////////////////////////////////////
class DgIVec3D {

   public:

      static const DgIVec3D& undefDgIVec3D;

      DgIVec3D (std::int64_t i = 0, std::int64_t j = 0,
                std::int64_t k = 0) 
       : i_(i), j_(j), k_(k)
      {}

      DgIVec3D (const DgIVec3D& pt) 
       : i_ (pt.i_), j_ (pt.j_), k_ (pt.k_) 
      {}

      DgIVec3D (const DgDVec2D&  pt) 
       : i_ ((int) dgg::util::lrint(pt.x())),  
         j_ ((int) dgg::util::lrint(pt.y())),
         k_ (0) 
      {}

      void setI (std::int64_t i) { i_ = i; }
      void setJ (std::int64_t j) { j_ = j; }
      void setK (std::int64_t k) { k_ = k; }

      long double distance (const DgIVec3D& pt) const
              { return (pt - *this).magnitude(); }

      std::int64_t i (void) const { return i_; }
      std::int64_t j (void) const { return j_; }
      std::int64_t k (void) const { return k_; }
      
      long double magnitude (void) const 
              { return sqrt((long double) (i_ * i_ + j_ * j_) + k_ * k_); }

      DgIVec3D diffVec (const DgIVec3D& pt0) const
                          { return DgIVec3D(*this - pt0); }

      DgIVec3D absDiffVec (const DgIVec3D& pt0) const
                          { return DgIVec3D(abs(i_ - pt0.i()),
                                            abs(j_ - pt0.j()),
                                            abs(k_ - pt0.k())); }

      const char* fromString (const char* str, char delimiter);

      inline DgIVec3D& scale (long double iScaleFactor, long double jScaleFactor, 
                 long double zScaleFacgtor);

      inline operator string (void) const;
      inline operator DgIVec2D  (void) const;

      inline DgIVec3D& operator=  (const DgIVec3D& pt);
      inline DgIVec3D& operator+= (const DgIVec3D& pt);
      inline DgIVec3D& operator-= (const DgIVec3D& pt);

      inline DgIVec3D& operator*= (long double scaleFactor);

      friend DgIVec3D operator*  (const DgIVec3D& pt, long double scaleFactor);
      friend DgIVec3D operator*  (long double scaleFactor, const DgIVec3D& pt);
      friend DgIVec3D operator+  (const DgIVec3D& pt1, const DgIVec3D& pt2);
      friend DgIVec3D operator-  (const DgIVec3D& pt1, const DgIVec3D& pt2);

      friend bool operator== (const DgIVec3D& pt1, const DgIVec3D& pt2);
      friend bool operator!= (const DgIVec3D& pt1, const DgIVec3D& pt2);
      friend bool operator<  (const DgIVec3D& pt1, const DgIVec3D& pt2);
      friend bool operator<= (const DgIVec3D& pt1, const DgIVec3D& pt2);
      friend bool operator>  (const DgIVec3D& pt1, const DgIVec3D& pt2);
      friend bool operator>= (const DgIVec3D& pt1, const DgIVec3D& pt2);

      friend ostream& operator<< (ostream& stream, const DgIVec3D& pt);

   private:

      std::int64_t i_;
      std::int64_t j_;
      std::int64_t k_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D&
DgIVec3D::scale (long double iScaleFactor, long double jScaleFactor, 
                 long double kScaleFactor)
//
// Scale me by each factor in the corresponding ijk direction.
//
////////////////////////////////////////////////////////////////////////////////
{
   i_ = (std::int64_t) dgg::util::lrint(i_ * iScaleFactor);
   j_ = (std::int64_t) dgg::util::lrint(j_ * jScaleFactor);
   k_ = (std::int64_t) dgg::util::lrint(k_ * kScaleFactor);

   return *this;

} // void DgIVec3D::scale

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D::operator DgIVec2D (void) const
//
// DgIVec2D conversion function. 
//
////////////////////////////////////////////////////////////////////////////////
{
   return DgIVec2D(i_ - k_, j_ - k_);

} // DgIVec3D::operator DgIVec2D

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D::operator string (void) const
{
   return "(" + dgg::util::to_string(i_) + ", " 
              + dgg::util::to_string(j_) + ", "
              + dgg::util::to_string(k_) + ")";

} // DgIVec3D::operator string

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D&
DgIVec3D::operator= (const DgIVec3D& pt)
{
   if (&pt != this)
   {
      i_ = pt.i_;
      j_ = pt.j_;
      k_ = pt.k_;
   }
   return *this;

} // DgIVec3D& DgIVec3D::operator=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D&
DgIVec3D::operator*= (long double scaleFactor)
{
   scale(scaleFactor, scaleFactor, scaleFactor);

   return *this;

} // DgIVec3D& DgIVec3D::operator*=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D&
DgIVec3D::operator+= (const DgIVec3D& pt)
{
   i_ += pt.i_;
   j_ += pt.j_;
   k_ += pt.k_;

   return *this;

} // DgIVec3D& DgIVec3D::operator+=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D&
DgIVec3D::operator-= (const DgIVec3D& pt)
{
   i_ -= pt.i_;
   j_ -= pt.j_;
   k_ -= pt.k_;

   return *this;

} // DgIVec3D& DgIVec3D::operator-=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D
operator* (const DgIVec3D& pt, long double scaleFactor)
{
   DgIVec3D result(pt);
   result.scale(scaleFactor, scaleFactor, scaleFactor);

   return result;

} // bool operator*

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D
operator* (long double scaleFactor, const DgIVec3D& pt)
{
   DgIVec3D result(pt);
   result.scale(scaleFactor, scaleFactor, scaleFactor);

   return result;

} // bool operator*

////////////////////////////////////////////////////////////////////////////////
inline bool
operator== (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   return (pt1.i_ == pt2.i_ && pt1.j_ == pt2.j_ && pt1.k_ == pt2.k_);

} // bool operator==

////////////////////////////////////////////////////////////////////////////////
inline bool
operator!= (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   return !operator==(pt1, pt2);

} // bool operator!=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator> (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   return (pt1.i_ > pt2.i_ && pt1.j_ > pt2.j_ && pt1.k_ > pt2.k_);

} // bool operator>

////////////////////////////////////////////////////////////////////////////////
inline bool
operator>= (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   return (pt1.i_ >= pt2.i_ && pt1.j_ >= pt2.j_ && pt1.k_ >= pt2.k_);

} // bool operator>=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator< (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   return (pt1.i_ < pt2.i_ && pt1.j_ < pt2.j_ && pt1.k_ < pt2.k_);

} // bool operator<

////////////////////////////////////////////////////////////////////////////////
inline bool
operator<= (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   return (pt1.i_ <= pt2.i_ && pt1.j_ <= pt2.j_ && pt1.k_ <= pt2.k_);

} // bool operator<=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D
operator+ (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   DgIVec3D result(pt1);
   result += pt2;

   return result;

} // bool operator+

////////////////////////////////////////////////////////////////////////////////
inline DgIVec3D
operator- (const DgIVec3D& pt1, const DgIVec3D& pt2)
{
   DgIVec3D result(pt1);
   result -= pt2;

   return result;

} // bool operator-

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgIVec3D& pt)
{
   return stream << string(pt);

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIDGGS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS.h: DgIDGGS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIDGGS_H 
#define DGIDGGS_H

#include <cmath>

#include "DgDiscRFS.h"
#include "DgIDGG.h"
#include "DgEllipsoidRF.h"

////////////////////////////////////////////////////////////////////////////////
class DgIDGGS : public DgDiscRFS<DgQ2DICoord, DgGeoCoord, long double> {

   public:

      static const DgIDGGS* makeRF (DgRFNetwork& network, 
               const DgGeoSphRF& backFrame, const DgGeoCoord& vert0,
               long double azDegs, unsigned int aperture = 4, int nRes = 1,
               const string& gridTopo = string("HEXAGON"),
               const string& name = "IDGGS", const string& projType = "ISEA", 
               bool isMixed43 = false, int numAp4 = 0, 
               bool isSuperfund = false);

      // copy constructor and operator= not implemented

      virtual const DgResAdd<DgQ2DICoord>& undefAddress (void) const 
           { static DgResAdd<DgQ2DICoord> 
                        undef(DgQ2DICoord::undefDgQ2DICoord, -1); 
             return undef; }

      const DgIDGG& idgg (int res) const
             { return static_cast<const DgIDGG&>(operator[](res)); }

      const DgGeoSphRF&  geoRF       (void) const { return geoRF_; }
      const DgGeoCoord&  vert0       (void) const { return vert0_; }
      long double           azDegs      (void) const { return azDegs_; }
      unsigned int       aperture    (void) const { return aperture_; }
      bool               isMixed43   (void) const { return isMixed43_; }
      bool               isSuperfund (void) const { return isSuperfund_; }
      int                numAp4      (void) const { return numAp4_; }
      const string&      gridTopo    (void) const { return gridTopo_; }
      const string&      projType    (void) const { return projType_; }

   protected:

      DgIDGGS (DgRFNetwork& network, 
               const DgGeoSphRF& backFrame,
               const DgGeoCoord& vert0,
               long double azDegs, unsigned int aperture = 4, int nRes = 1,
               const string& gridTopo = string("HEXAGON"),
               const string& name = "IDGGS", 
               const string& projType = "ISEA", 
               bool isMixed43 = false, int numAp4 = 0, 
               bool isSuperfund = false);

      // remind sub-classes of the pure virtual functions remaining from above

      virtual void setAddParents (const DgResAdd<DgQ2DICoord>& add,
                                  DgLocVector& vec) const = 0;

      virtual void setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const = 0;

      virtual void setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const = 0;

      virtual void setAddAllChildren (const DgResAdd<DgQ2DICoord>& add,
                                      DgLocVector& vec) const = 0;

   private:

      const DgGeoSphRF& geoRF_;

      DgGeoCoord vert0_;
      long double azDegs_;

      string gridTopo_;
      string projType_;

      bool isMixed43_;
      int  numAp4_;
      bool isSuperfund_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgGeoDatumRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgGeoDatumRF.h: DgGeoDatumRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGGEODATUMRF_H
#define DGGEODATUMRF_H

using namespace std;

#include <cstdint>

#include "DgRF.h"

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> class DgGeoDatumRF : public DgRF<A, D> {

   public:

      DgGeoDatumRF (DgRFNetwork& networkIn, const string& nameIn)
         : DgRF<A, D> (networkIn, nameIn) { }

      DgGeoDatumRF (const DgGeoDatumRF& rf) : DgRF<A, D> (rf) { }

      DgGeoDatumRF& operator= (const DgGeoDatumRF& rf)
          { DgRF<A, D>::operator=(rf); return *this; }

      // these are the pure virtual functions which subclasses need to define

      virtual D dist (const A& add1, const A& add2) const = 0;

      virtual string add2str  (const A& add)  const = 0;
      virtual string add2str  (const A& add, char delimiter) const = 0;
      virtual string dist2str (const D& dist) const = 0;
      virtual long double dist2dbl (const D& dist) const = 0;

      virtual const char* str2add (A* add, const char* str, char delimiter) 
                                                                     const = 0;

      virtual std::uint64_t dist2int (const D& dist) const = 0;

      virtual const A& undefAddress (void) const = 0;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/pj_mlfn.cpp<|end_filename|>
#include "proj4.h"
#include <cmath>
#include <cstdlib>
/* meridinal distance for ellipsoid and inverse
**	8th degree - accurate to < 1e-5 meters when used in conjuction
**		with typical major axis values.
**	Inverse determines phi to EPS (1e-11) radians, about 1e-6 seconds.
*/

#define C00 1.
#define C02 .25
#define C04 .046875
#define C06 .01953125
#define C08 .01068115234375
#define C22 .75
#define C44 .46875
#define C46 .01302083333333333333
#define C48 .00712076822916666666
#define C66 .36458333333333333333
#define C68 .00569661458333333333
#define C88 .3076171875
#define EPS 1e-11
#define MAX_ITER 10
#define EN_SIZE 5
	long double *
pj_enfn(long double es) {
	long double t, *en;

	if ( (en = (long double *)malloc(EN_SIZE * sizeof(long double))) ) {
		en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));
		en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));
		en[2] = (t = es * es) * (C44 - es * (C46 + es * C48));
		en[3] = (t *= es) * (C66 - es * C68);
		en[4] = t * es * C88;
	} /* else return NULL if unable to allocate memory */
	return en;
}
	long double
pj_mlfn(long double phi, long double sphi, long double cphi, long double *en) {
	cphi *= sphi;
	sphi *= sphi;
	return(en[0] * phi - cphi * (en[1] + sphi*(en[2]
		+ sphi*(en[3] + sphi*en[4]))));
}
	long double
pj_inv_mlfn(long double arg, long double es, long double *en) {
	long double s, t, phi, k = 1.-es;
	int i;

	phi = arg;
	for (i = MAX_ITER; i ; --i) { /* rarely goes over 5 iterations */
		s = sin(phi);
		t = 1. - es * s * s;
		t = (pj_mlfn(phi, s, std::cos(phi), en) - arg) / ( k * t * std::sqrt(t));
		phi -= t;
		if (std::fabs(t) < EPS)
			break;
	}
/*
	if (i <= 0)
		pj_errno = -17;
*/
	return phi;
}


<|start_filename|>src/DgLocList.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgLocList.cpp: DgLocList class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <algorithm>

#include "DgLocation.h"
#include "DgLocList.h"
#include "DgRFBase.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgLocList::~DgLocList (void)
{
   if (isOwner()) destroy();
   clear();

} // DgLocList::~DgLocList

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgLocList::destroy (void)
{
   if (isOwner())
   {
      list<DgLocBase*>::iterator it;
      for (it = begin(); it != end(); it++)
      {
         (*it)->clearAddress();
         delete (*it);
      }
   }

   clear();

} // DgLocList::destroy

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgLocList::clearAddress (void)
{
   list<DgLocBase*>::iterator it;
   for (it = begin(); it != end(); it++)
   {
      (*it)->clearAddress();
   }
   clear();

} // DgLocList::clearAddress

/*
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool
DgLocList::thin (float dMin, bool clear)
//
// Apply the appropriate line reduction algorithms to all the drawables.
// Returns true if some portion of this object still remains after the thinning
// and false if the entire object has been thinned away.
//
////////////////////////////////////////////////////////////////////////////////
{
   list<DgLocBase*>::iterator it;
   for (it = begin(); it != end(); it++)
   {
      (*it)->thin(dMin, clear);
   }

   return true;

} // bool DgLocList::thin
*/

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
int
DgLocList::cardinality (void) const
//
// Return the total number of elements in this tree.
//
////////////////////////////////////////////////////////////////////////////////
{
   int card = 0;
   list<DgLocBase*>::const_iterator it;
   for (it = begin(); it != end(); it++) card += (*it)->cardinality();

   return card;

} // int DgLocList::cardinality

////////////////////////////////////////////////////////////////////////////////
DgLocList&
DgLocList::operator= (const DgLocList& list)
{
   if (&list != this)
   {
      clearAddress();

      rf_ = &list.rf();
      copy(list.begin(), list.end(), this->begin());
   }

   return *this;

} // DgLocList& DgLocList::operator=

////////////////////////////////////////////////////////////////////////////////
/*
bool 
DgLocList::operator== (const DgLocList& list) const
{
   if (this == &list) return true;

} // DgLocList::operator==
*/

////////////////////////////////////////////////////////////////////////////////
string 
DgLocList::asString (void) const
{
   string str;
   str = "[[\n";
   list<DgLocBase*>::const_iterator it;
   for (it = begin(); it != end(); it++) str += (*it)->asString();
   str += "]]\n";

   return str;

} // DgLocList::asString

////////////////////////////////////////////////////////////////////////////////
string 
DgLocList::asString (char delimiter) const
{
   string str;
   list<DgLocBase*>::const_iterator it;
   for (it = begin(); it != end(); it++) str += (*it)->asString(delimiter);

   return str;

} // DgLocList::asString

////////////////////////////////////////////////////////////////////////////////
const char* 
DgLocList::fromString (const char* str, char delimiter)
{
   destroy();
   setIsOwner(true);

   const char* tmp = str;
   while (*tmp)
   {
      DgLocation* tloc = new DgLocation(rf());
      tmp = tloc->fromString(tmp, delimiter);
      push_back(tloc); 
      if (*tmp == delimiter) tmp++;
   }

   return tmp;

} // DgLocList::fromString

////////////////////////////////////////////////////////////////////////////////
string 
DgLocList::asAddressString (void) const
{
   string str;
   str = "[[\n";

   list<DgLocBase*>::const_iterator it;
   for (it = begin(); it != end(); it++) 
    str += (*it)->asAddressString();

   str += "]]\n";

   return str;
} // DgLocList::asAddressString

////////////////////////////////////////////////////////////////////////////////
string 
DgLocList::asAddressString (char delimiter) const
{
   string str;

   list<DgLocBase*>::const_iterator it;
   for (it = begin(); it != end(); it++) 
      str += (*it)->asAddressString(delimiter);

   return str;
} // DgLocList::asAddressString

////////////////////////////////////////////////////////////////////////////////
void 
DgLocList::convertTo (const DgRFBase& rfIn)
{
   if (!rf_ || rf() != rfIn)
   {
      rf_ = &rfIn;
      list<DgLocBase*>::iterator it;
      for (it = begin(); it != end(); it++) (*it)->convertTo(rfIn);
   }

} // DgLocList::convertTo

////////////////////////////////////////////////////////////////////////////////
void
DgLocList::push_back (DgLocBase* loc)
{ 
   rf().convert(loc); 
   list<DgLocBase*>::push_back(loc); 
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ostream&
operator<< (ostream& stream, const DgLocList& list)
{
   //stream << "[[\n";
   DgLocList::const_iterator it;
   for (it = list.begin(); it != list.end(); it++) stream << **it << "\n";
   stream << "]]\n";

   return stream;

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgOutGeoJSONFile.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutGeoJSONFile.cpp: DgOutGeoJSONFile class implementation
//
// Version 6.2 - <NAME>, added GeoJSON support, 11/4/13
//
////////////////////////////////////////////////////////////////////////////////

#include <sstream>
#include <iostream>

#include "DgOutGeoJSONFile.h"
#include "DgLocList.h"
#include "DgPolygon.h"
#include "DgLocation.h"
#include "DgCell.h"
#include "DgGeoSphRF.h"

DgOutGeoJSONFile::DgOutGeoJSONFile(const DgGeoSphDegRF& rf,
    const std::string& filename, int precision, bool isPointFile,
    DgReportLevel failLevel)
   : DgOutLocTextFile (filename, rf, isPointFile, "geojson", precision,
        failLevel)
{
   if (0 == rf.vecAddress(DgDVec2D()))
   {
      DgOutputStream::report("DgOutGeoJSONFile::DgOutGeoJSONFile(): RF " + rf.name() +
        " must override the vecAddress() method", DgBase::Fatal);
   }

   setFormatStr();
   preamble();
}

DgOutGeoJSONFile::~DgOutGeoJSONFile()
{
   postamble();
   close();
}

void DgOutGeoJSONFile::preamble()
{
   DgOutGeoJSONFile& o(*this);   // make life a bit easier
   o << "{";
   o << "\"type\":\"FeatureCollection\",";
   o << "\"features\":[";
   o.flush();
}

void DgOutGeoJSONFile::postamble()
{
   DgOutGeoJSONFile& o(*this);   

   // Delete the comma from the last feature 
   long pos = o.tellp();
   o.seekp(pos - 1);
   o << "]}";
   o.flush();
}

DgOutLocFile& 
DgOutGeoJSONFile::insert(const DgDVec2D& pt)
{
   DgOutGeoJSONFile& o(*this);

   const int maxBuffSize = 200;
   char buff[maxBuffSize];

   sprintf(buff, formatStr(), pt.x(), pt.y());

   o << buff;

   o.flush();

   return o;
}

DgOutLocFile& 
DgOutGeoJSONFile::insert (DgLocation& loc, const string* label)
{
   DgOutGeoJSONFile& o(*this);

   rf().convert(&loc);

   o << "{\"type\":\"Feature\",";
   o << "\"properties\":{";
   if (label)
      o << "\"name\":" << *label;
   o << "},";
   o << "\"geometry\":{";
   o << "\"type\":\"Point\",";
   o << "\"coordinates\":";

   o.insert(rf().getVecLocation(loc));

   o << "}},";
   o.flush();

   return *this;
}

DgOutLocFile& 
DgOutGeoJSONFile::insert (DgLocVector& vec, const string* label,
   const DgLocation* cent)
{
   DgOutGeoJSONFile& o(*this);   

   rf().convert(vec);

   o << "{\"type\":\"Feature\",";
   o << "\"properties\":{";
   if (label)
      o << "\"name\":" << *label;
   o << "},";
   o << "\"geometry\":{";
   o << "\"type\":\"Polygon\",";
   o << "\"coordinates\":[[";

   vector<DgAddressBase *>& v = vec.addressVec();
   for(vector<DgAddressBase *>::iterator i = v.begin(); v.end() != i; ++i)
   {
         o.insert(rf().getVecAddress(*(*i)));
         o << ",";
   }

   // rewrite first vertex:
   o.insert(rf().getVecAddress(*v[0]));

   o << "]]}},";
   o.flush();

   return *this;
}

DgOutLocFile& 
DgOutGeoJSONFile::insert (DgPolygon& poly, const string* label,
   const DgLocation* cent)
{
   DgOutGeoJSONFile& o(*this);   

   rf().convert(poly);

   o << "{\"type\":\"Feature\",";
   o << "\"properties\":{";
   if (label)
      o << "\"name\":" << *label;
   o << "},";
   o << "\"geometry\":{";
   o << "\"type\":\"Polygon\",";
   o << "\"coordinates\":[[";

   vector<DgAddressBase *>& v = poly.addressVec();
   for(vector<DgAddressBase *>::iterator i = v.begin(); v.end() != i; ++i)
   {
         o.insert(rf().getVecAddress(*(*i)));
         o << ",";
   }

   // rewrite first vertex:
   o.insert(rf().getVecAddress(*v[0]));

   o << "]]}},";
   o.flush();

   return *this;
}


<|start_filename|>src/DgDiscRFS2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDiscRFS2D.h: DgDiscRFS2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDISCRFS2D_H 
#define DGDISCRFS2D_H

#include <cmath>

#include "DgDiscRFS.h"
#include "DgDVec2D.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
class DgDiscRFS2D : public DgDiscRFS<DgIVec2D, DgDVec2D, long double> {

   public:

      static DgDiscRFS2D* makeRF (DgRFNetwork& network, 
                   const DgRF<DgDVec2D, long double>& backFrame,
                   int nRes = 1, unsigned int aperture = 4,
                   bool isCongruent = true, bool isAligned = false,
                   const string& name = "DiscRFS2D", 
                   const string geometry = "sqr8", bool isMixed43 = false,
                   int numAp4 = 0, bool isSuperfund = false);

      DgDiscRFS2D (DgRFNetwork& network, 
                   const DgRF<DgDVec2D, long double>& backFrame,
                   int nRes = 1, unsigned int aperture = 4,
                   bool isCongruent = true, bool isAligned = false,
                   const string& name = "DiscRFS2D")
        : DgDiscRFS<DgIVec2D, DgDVec2D, long double> 
              (network, backFrame, nRes, aperture, 
                               isCongruent, isAligned, name)
           { undefLoc_ = makeLocation(undefAddress()); }

      DgDiscRFS2D (const DgDiscRFS2D& grd) 
        : DgDiscRFS<DgIVec2D, DgDVec2D, long double> (grd) 
           { undefLoc_ = makeLocation(undefAddress()); }

      DgDiscRFS2D& operator= (const DgDiscRFS2D& grd)
           { DgDiscRFS<DgIVec2D, DgDVec2D, long double>::operator=(grd); 
               return *this; }

      virtual const DgResAdd<DgIVec2D>& undefAddress (void) const 
           { static DgResAdd<DgIVec2D> undef(DgIVec2D::undefDgIVec2D, -1); 
             return undef; }

   protected:

      // remind users of the pure virtual functions remaining from above

      virtual void setAddParents (const DgResAdd<DgIVec2D>& add,
                                  DgLocVector& vec) const = 0;

      virtual void setAddInteriorChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const = 0;

      virtual void setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const = 0;

      virtual void setAddAllChildren (const DgResAdd<DgIVec2D>& add,
                                      DgLocVector& vec) const = 0;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgHexC2Grid2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgHexC2Grid2D.cpp: DgHexC2Grid2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <cstdint>

#include "DgContCartRF.h"
#include "DgHexC2Grid2D.h"
#include "DgHexC1Grid2D.h"
#include "DgPolygon.h"

////////////////////////////////////////////////////////////////////////////////
DgHexC2Grid2D::DgHexC2Grid2D (DgRFNetwork& networkIn, 
             const DgRF<DgDVec2D, long double>& ccFrameIn, const string& nameIn)
         : DgDiscRF2D (networkIn, ccFrameIn, nameIn, M_1_SQRT3, M_1_SQRT3, 
                       M_SQRT3_2, 1.0L)
{ 
   area_ = c(); 

   // create the surrogate hex grid: a class I hex grid rotated 30 degrees

   DgContCartRF* surCCRF = new DgContCartRF(network(), 
                              nameIn + string("SurBF"));

   new Dg2WayContAffineConverter(backFrame(), *surCCRF, 1.0L, 30.0L);
   surrogate_ = new DgHexC1Grid2D(network(), *surCCRF, nameIn + string("Sur"));

   // create the substrate hex grid: a class I hex one aperture 3 resolution
   // finer

   DgContCartRF* subCCRF = new DgContCartRF(network(), 
                              nameIn + string("SubBF"));

   new Dg2WayContAffineConverter(backFrame(), *subCCRF, M_SQRT3);
   substrate_ = new DgHexC1Grid2D(network(), *subCCRF, nameIn + string("Sub"));

} // DgHexC2Grid2D::DgHexC2Grid2D

////////////////////////////////////////////////////////////////////////////////
std::int64_t
DgHexC2Grid2D::dist (const DgIVec2D& add1, const DgIVec2D& add2) const
{
   DgLocation* loc1 = substrate().makeLocation(add1);
   DgLocation* loc2 = substrate().makeLocation(add2);

   surrogate().convert(loc1);
   surrogate().convert(loc2);

   std::int64_t d = surrogate().dist(*(surrogate().getAddress(*loc1)),
                            *(surrogate().getAddress(*loc2)));

   delete loc1;
   delete loc2;

   return d;

} // int DgHexC2Grid2D::dist

////////////////////////////////////////////////////////////////////////////////
void
DgHexC2Grid2D::setAddVertices (const DgIVec2D& add, DgPolygon& vec) const
{
   DgLocation* tmpLoc = substrate().makeLocation(add);
   surrogate().setVertices(*tmpLoc, vec);

   backFrame().convert(vec);

   delete tmpLoc;

} // void DgHexC2Grid2D::setAddVertices

////////////////////////////////////////////////////////////////////////////////
void
DgHexC2Grid2D::setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) const
{
   DgLocation* tmpLoc = substrate().makeLocation(add);

   DgLocVector tmpVec;
   surrogate().setNeighbors(*tmpLoc, tmpVec);
   substrate().convert(tmpVec);

   delete tmpLoc;

   vector<DgAddressBase*>& v = vec.addressVec();
   for (std::int64_t i = 0; i < tmpVec.size(); i++)
   {
      v.push_back(new DgAddress<DgIVec2D>(
                     *(substrate().getAddress(tmpVec[i]))));
   }

} // void DgHexC2Grid2D::setAddNeighbors

////////////////////////////////////////////////////////////////////////////////
DgIVec2D 
DgHexC2Grid2D::quantify (const DgDVec2D& point) const
{
   DgLocation* tmpLoc = backFrame().makeLocation(point);

   surrogate().convert(tmpLoc);  // to quantify

   substrate().convert(tmpLoc);  // to set "correct" address

   DgIVec2D add(*(substrate().getAddress(*tmpLoc)));

   delete tmpLoc;

   return add;

} // DgIVec2D DgHexC2Grid2D::quantify

////////////////////////////////////////////////////////////////////////////////
DgDVec2D 
DgHexC2Grid2D::invQuantify (const DgIVec2D& add) const
{
   DgLocation* tmpLoc = substrate().makeLocation(add);

   backFrame().convert(tmpLoc);

   DgDVec2D point(*(backFrame().getAddress(*tmpLoc)));

   delete tmpLoc;

   return point;

} // DgDVec2D DgHexC2Grid2D::invQuantify

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDiscRFS2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDiscRFS2D.cpp: DgDiscRFS2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgDiscRFS2D.h"
#include "DgDmdD4Grid2DS.h"
#include "DgDmdD8Grid2DS.h"
#include "DgHexGrid2DS.h"
#include "DgSqrD4Grid2DS.h"
#include "DgSqrD8Grid2DS.h"
#include "DgTriGrid2DS.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgDiscRFS2D* 
DgDiscRFS2D::makeRF (DgRFNetwork& net, const DgRF<DgDVec2D, long double>& cc0,
   int nRes, unsigned int aperture, bool isCongruent, bool isAligned, 
   const string& name, const string geometry, bool isMixed43, int numAp4,
   bool isSuperfund)
{
   DgDiscRFS2D* dg0 = 0;
   if (geometry == "sqr8")
   {
      dg0 = new DgSqrD8Grid2DS(net, cc0, nRes, aperture, isCongruent,
                               isAligned, "SqrD82DS");
   }
   else if (geometry == "sqr4")
   {
      dg0 = new DgSqrD4Grid2DS(net, cc0, nRes, aperture, isCongruent,
                               isAligned, "SqrD42DS");
   }
   else if (geometry == "dmd8")
   {
      dg0 = new DgDmdD8Grid2DS(net, cc0, nRes, aperture, isCongruent,
                               isAligned, "DmdD82DS");
   }
   else if (geometry == "dmd4")
   {
      dg0 = new DgDmdD4Grid2DS(net, cc0, nRes, aperture, isCongruent,
                               isAligned, "DmdD82DS");
   }
   else if (geometry == "hex")
   {
      dg0 = new DgHexGrid2DS(net, cc0, nRes, aperture, isCongruent,
                   isAligned, "HexC12DS", isMixed43, numAp4, isSuperfund);
   }
   else if (geometry == "tri")
   {
      dg0 = new DgTriGrid2DS(net, cc0, nRes, aperture, isCongruent,
                             isAligned, "Tri2DS");
   }
   else
   {
     report("DgDiscRFS2D::makeRF() invalid or unimplemented geometry type: " + 
            geometry, DgBase::Fatal);
   }

   return dg0;

} // DgDiscRFS2D* DgDiscRFS2D::makeRF

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDmdD4Grid2DS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDmdD4Grid2DS.h: DgDmdD4Grid2DS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDMDD4GRID2DS_H 
#define DGDMDD4GRID2DS_H 

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgDiscRFS2D.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgDmdD4Grid2DS : public DgDiscRFS2D {

   public:

      DgDmdD4Grid2DS (DgRFNetwork& networkIn, 
                 const DgRF<DgDVec2D, long double>& backFrameIn,
                 int nRes = 1, unsigned int apertureIn = 4, 
                 bool isCongruentIn = true, bool isAlignedIn = false,
                 const string& nameIn = "4D4");

      DgDmdD4Grid2DS (const DgDmdD4Grid2DS& rf);

     ~DgDmdD4Grid2DS (void);

      DgDmdD4Grid2DS& operator= (const DgDmdD4Grid2DS& rf);

      int radix (void) const { return radix_; }

   protected:

      int radix_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgIVec2D>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgIVec2D>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgDVec2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDVec2D.cpp: DgDVec2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgBase.h"
#include "DgDVec2D.h"
#include "DgDVec3D.h"

#include <sstream>

////////////////////////////////////////////////////////////////////////////////

const DgDVec2D& DgDVec2D::undefDgDVec2D = DgDVec2D(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());

////////////////////////////////////////////////////////////////////////////////
DgDVec2D::DgDVec2D (const DgDVec3D& pt) : x_ (pt.x()), y_ (pt.y()) {}

////////////////////////////////////////////////////////////////////////////////
DgDVec2D&
DgDVec2D::operator= (const DgDVec3D& pt)
{
   x_ = pt.x();
   y_ = pt.y();

   return *this;

} // DgDVec2D& DgDVec2D::operator=

////////////////////////////////////////////////////////////////////////////////
const char* 
DgDVec2D::fromString (const char* str, char delimiter)
{
   char delimStr[2];
   delimStr[0] = delimiter;
   delimStr[1] = '\0';

   char* tmpStr = new char[strlen(str) + 1];
   strcpy(tmpStr, str);

   char* tok;

   long double xIn;
   long double yIn;

   // get the x
   {
      tok = strtok(tmpStr, delimStr);
      std::istringstream convert(tok);
      convert >> xIn;
      if(convert.fail())
         ::report("DgDVec2D::fromString() invalid value in string " + string(tok), DgBase::Fatal);
   }

   // get the y
   {
      tok = strtok(NULL, delimStr);
      std::istringstream convert(tok);
      convert >> yIn;
      if(convert.fail())
         ::report("DgDVec2D::fromString() invalid value in string " + string(tok), DgBase::Fatal);
   }

   setX(xIn);
   setY(yIn);

   unsigned int offset = (tok - tmpStr) + strlen(tok) + 1;
   if (offset >= strlen(str)) 
    return 0;
   else 
    return &str[offset];
} // const char* DgDVec2D::fromString

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDmdD8Grid2DS.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDmdD8Grid2DS.cpp: DgDmdD8Grid2DS class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgContCartRF.h"
#include "DgDiscRF.h"
#include "DgDmdD8Grid2D.h"
#include "DgDmdD8Grid2DS.h"

////////////////////////////////////////////////////////////////////////////////
DgDmdD8Grid2DS::DgDmdD8Grid2DS (DgRFNetwork& networkIn, 
               const DgRF<DgDVec2D, long double>& backFrameIn, int nResIn, 
               unsigned int apertureIn, bool isCongruentIn, bool isAlignedIn,
               const string& nameIn)
        : DgDiscRFS2D (networkIn, backFrameIn, nResIn, apertureIn, 
                       isCongruentIn, isAlignedIn, nameIn) 
{ 
   // determine the radix

   radix_ = static_cast<int>(sqrt(static_cast<float>(aperture())));
   if (static_cast<unsigned int>(radix() * radix()) != aperture())
   {
      report(
      "DgDmdD8Grid2DS::DgDmdD8Grid2DS() aperture must be a perfect square",
       DgBase::Fatal);
   }

   if (isAligned() && radix() != 2 && radix() != 3)
   {
      report("DgDmdD4Grid2DS::DgDmdD4Grid2DS() only aligned apertures 4 and 9 "
             " parent/children operators fully implemented", DgBase::Warning);
   }

   // do the grids
   
   long double fac = 1;

   DgDVec2D trans;
   if (isCongruent())
   {
      trans = DgDVec2D(-0.5, -0.5);
   }
   else if (isAligned())
   {
      trans = DgDVec2D(0.0, 0.0);
      if (radix() != 2 && radix() != 3)
      {
         report(
         "DgDmdD8Grid2DS::DgDmdD8Grid2DS() only aligned apertures 2 and 3 "
         " are implemented", DgBase::Fatal);
      }
   }
   else
   {
      report("DgDmdD8Grid2DS::DgDmdD8Grid2DS() grid system must be either "
             "congruent, aligned, or both", DgBase::Fatal);
   }

   for (int i = 0; i < nRes(); i++)
   {
      string newName = name() + "_" + dgg::util::to_string(i);

      //cout << newName << " " << fac << ' ' << trans << endl;

      DgContCartRF* ccRF = new DgContCartRF(network(), newName + string("bf"));

      new Dg2WayContAffineConverter(backFrame(), *ccRF, (long double) fac, 0.0, 
                                    trans); 

      (*grids_)[i] = new DgDmdD8Grid2D(network(), *ccRF, newName);
      new Dg2WayResAddConverter<DgIVec2D, DgDVec2D, long double>
                                                  (*this, *(grids()[i]), i);

      fac *= radix();
   }

} // DgDmdD8Grid2DS::DgDmdD8Grid2DS

////////////////////////////////////////////////////////////////////////////////
DgDmdD8Grid2DS::DgDmdD8Grid2DS (const DgDmdD8Grid2DS& rf) 
  : DgDiscRFS2D (rf)
{
   report("DgDmdD8Grid2DS::operator=() not implemented yet", DgBase::Fatal);

} // DgDmdD8Grid2DS::DgDmdD8Grid2DS

////////////////////////////////////////////////////////////////////////////////
DgDmdD8Grid2DS::~DgDmdD8Grid2DS (void)
{
   for (unsigned long i = 0; i < grids().size(); i++)
    delete (*grids_)[i]; 

   delete grids_;
} // DgDmdD8Grid2DS::~DgDmdD8Grid2DS

////////////////////////////////////////////////////////////////////////////////
DgDmdD8Grid2DS&
DgDmdD8Grid2DS::operator= (const DgDmdD8Grid2DS& rf)
{
   report("DgDmdD8Grid2DS::operator=() ", DgBase::Fatal);

   return *this;

} // DgDmdD8Grid2DS& DgDmdD8Grid2DS::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgDmdD8Grid2DS::setAddParents (const DgResAdd<DgIVec2D>& add, 
                               DgLocVector& vec) const
{
//cout << "   setAddParents: " << add << endl;
   if (isCongruent() || radix() == 3)
   {
      DgLocation* tmpLoc = makeLocation(add);
      grids()[add.res() - 1]->convert(tmpLoc);
      convert(tmpLoc);

      vec.push_back(*tmpLoc);

      delete tmpLoc;
   }
   else // must be aligned aperture 4
   {
      // vertices lie in parents

      DgLocation* tmpLoc = makeLocation(add);
      DgPolygon* verts = makeVertices(*tmpLoc);
      delete tmpLoc;

//cout << "   verts 1: " << *verts << endl;

      grids()[add.res() - 1]->convert(*verts);
//cout << "   verts 2: " << *verts << endl;
      convert(*verts);
//cout << "   verts 3: " << *verts << endl;

      for (int i = 0; i < verts->size(); i++)
      {
         bool found = false;

         for (int j = 0; j < vec.size(); j++) 
         {
//cout << "  " << i << " " << j << " " << (*verts)[i] << " " << vec[j];
            if ((*verts)[i] == vec[j]) 
            {
//cout << " YES" << endl;
               found = true;
               break;
            }
//cout << " NO" << endl;
         }
         
         if (!found) vec.push_back((*verts)[i]);
      }
//cout << "   parents: " << vec << endl;

      delete verts;
   }

} // void DgDmdD8Grid2DS::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgDmdD8Grid2DS::setAddInteriorChildren (const DgResAdd<DgIVec2D>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent() || radix() == 3)
   {
      const DgIVec2D& lowerLeft = add.address() * radix();

      vector<DgAddressBase*>& v = vec.addressVec();
      for (int i = 0; i < radix(); i++)
      {
         for (int j = 0; j < radix(); j++)
         {
            v.push_back(new DgAddress< DgResAdd<DgIVec2D> >(
             DgResAdd<DgIVec2D>(DgIVec2D(lowerLeft.i() + i, lowerLeft.j() + j), 
                               add.res() + 1)));
         }
      }
   }
   else // must be aligned aperture 4
   {
      // only center square is interior

      DgLocation* tmpLoc = makeLocation(add);
      grids()[add.res() + 1]->convert(tmpLoc);
      vec.push_back(*tmpLoc);

      delete tmpLoc;
   }
   
} // void DgDmdD8Grid2DS::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgDmdD8Grid2DS::setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent() || radix() == 3)
   {
      // no boundary children in this topology; leave vec empty
   }
   else // must be aligned aperture 4
   {
      DgLocation* tmpLoc = makeLocation(add);
      grids()[add.res() + 1]->convert(tmpLoc);
      convert(tmpLoc);
      setNeighbors(*tmpLoc, vec);

      delete tmpLoc;
   }

} // void DgDmdD8Grid2DS::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgDmdD8Grid2DS::setAddAllChildren (const DgResAdd<DgIVec2D>& add, 
                                   DgLocVector& vec) const
{
   setAddInteriorChildren(add, vec);

   DgLocVector bndVec(vec.rf());
   setAddBoundaryChildren(add, bndVec);

   for (int i = 0; i < bndVec.size(); i++) vec.push_back(bndVec[i]);

} // void DgDmdD8Grid2DS::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgProjFuller.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgProjFuller.h: DgProjFuller class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPROJ_FULLER_H
#define DGPROJ_FULLER_H

#include <limits>
#include <iostream>

#include "DgIVec2D.h"
#include "DgDVec2D.h"
#include "DgPolygon.h"
#include "DgRF.h"
#include "DgLocation.h"
#include "DgConverter.h"
#include "Dg2WayConverter.h"
#include "DgContCartRF.h"
#include "DgGeoSphRF.h"
#include "DgProjTriRF.h"
#include "DgEllipsoidRF.h"
#include "DgUtil.h"
#include "DgIcosaProj.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgProjFullerFwd : public DgConverter<DgGeoCoord, long double,
                                        DgProjTriCoord, long double> {

   public:

      DgProjFullerFwd (const DgRF<DgGeoCoord, long double>& geoRF,
                       const DgRF<DgProjTriCoord, long double>& projTriRF);

      const DgProjTriRF& projTriRF (void) const { return *pProjTriRF_; }

      virtual DgProjTriCoord convertTypedAddress (const DgGeoCoord& addIn) 
                                                               const;

   private:

      const DgProjTriRF* pProjTriRF_;

};

////////////////////////////////////////////////////////////////////////////////
class DgProjFullerInv : public DgConverter<DgProjTriCoord, long double, 
                                           DgGeoCoord, long double> {

   public:

      DgProjFullerInv (const DgRF<DgProjTriCoord, long double>& projTriRF,
                          const DgRF<DgGeoCoord, long double>& geoRF);

      const DgProjTriRF& projTriRF (void) const { return *pProjTriRF_; }

      virtual DgGeoCoord convertTypedAddress (const DgProjTriCoord& addIn) 
                                                                      const;

   private:

      const DgProjTriRF* pProjTriRF_;

};

////////////////////////////////////////////////////////////////////////////////
class DgProjFuller : public DgIcosaProj {

   public:

      DgProjFuller (const DgRF<DgGeoCoord, long double>& geoRF,
                    const DgRF<DgProjTriCoord, long double>& projTriRF)
         : DgIcosaProj(*(new DgProjFullerFwd(geoRF, projTriRF)), 
                       *(new DgProjFullerInv(projTriRF, geoRF))) {}
};

IcosaGridPt fullerFwd (const GeoCoord& ll, DgSphIcosa& sphicosa);
GeoCoord fullerInv (const IcosaGridPt& pt, SphIcosa& sphicosa);

////////////////////////////////////////////////////////////////////////////////
/*
   The C++ methods above are wrappers for the C functions below
*/
////////////////////////////////////////////////////////////////////////////////

Vec2D fullerFwdOneTri (const GeoCoord geo, long double R, long double * v1, 
                       long double * v2, long double * v3);

GeoCoord fullerInvOneTri (const IcosaGridPt pt, long double R, long double* pAzimuth, 
                       long double* pTheta);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#endif


<|start_filename|>src/DgProjGnomonicRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgProjGnomonicRF.h: DgProjGnomonicRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPROJGNOMONICRF_H
#define DGPROJGNOMONICRF_H

#include <iostream>

#include "DgConstants.h"
#include "DgGeoProjRF.h"
#include "DgDVec2D.h"

using namespace std;

class DgEllipsoidRF;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgProjGnomonicRF : public DgGeoProjRF {

   public:

      DgProjGnomonicRF (DgRFNetwork& networkIn, 
                      const string& nameIn = "GnomonicRF",
                      const DgGeoCoord& proj0In = DgGeoCoord(M_ZERO, M_ZERO),
                      long double x0In = M_ZERO, long double y0In = M_ZERO,
                      long double k0In = M_ONE, long double to_meterIn = M_ONE,
                      long double fr_meterIn = M_ONE);

      // pure virtual methods

      virtual DgDVec2D   projForward (const DgGeoCoord& addIn,
                                      const DgEllipsoidRF& e) const;

      virtual DgGeoCoord projInverse (const DgDVec2D& addIn,
                                      const DgEllipsoidRF& e) const;

   protected:

      long double sinph0_;
      long double cosph0_;
      int mode_;

}; // class DgProjGnomonicRF

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgGeoProjRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgGeoProjRF.h: DgGeoProjRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGGEOPROJRF_H
#define DGGEOPROJRF_H

#include <iostream>
#include <cstdint>

#include "DgConstants.h"
#include "DgGeoDatumRF.h"
#include "DgEllipsoidRF.h"
#include "DgDVec2D.h"

using namespace std;

class DgGeoCoord;
class DgEllipsoidRF;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgGeoProjRF : public DgGeoDatumRF<DgDVec2D, long double> {

   public:

      DgGeoProjRF (DgRFNetwork& networkIn, const string& nameIn,
                   const DgGeoCoord& proj0In = DgGeoCoord(M_ZERO, M_ZERO),
                   long double x0In = M_ZERO, long double y0In = M_ZERO,
                   long double k0In = M_ONE, long double to_meterIn = M_ONE,
                   long double fr_meterIn = M_ONE)
               : DgGeoDatumRF<DgDVec2D, long double> (networkIn, nameIn), 
                 proj0_ (proj0In), x0_ (x0In), y0_ (y0In),
                 k0_ (k0In), to_meter_ (to_meterIn), fr_meter_ (fr_meterIn)
               { }

      // pure virtual methods

      virtual DgDVec2D   projForward (const DgGeoCoord& addIn,
                                      const DgEllipsoidRF& e) const = 0;

      virtual DgGeoCoord projInverse (const DgDVec2D& addIn,
                                      const DgEllipsoidRF& e) const = 0;

      // get methods

      const DgGeoCoord& proj0 (void) const { return proj0_; }

      long double lam0 (void) const { return proj0_.lon(); }
      long double phi0 (void) const { return proj0_.lat(); }
      long double x0 (void) const { return x0_; }
      long double y0 (void) const { return y0_; }
      long double k0 (void) const { return k0_; }

      int over (void) const { return over_; }
      int geoc (void) const { return geoc_; }

      long double to_meter (void) const { return to_meter_; }
      long double fr_meter (void) const { return fr_meter_; }

      // set methods

      void setProj0 (const DgGeoCoord& proj0In) { proj0_ = proj0In; }

      void setX0 (long double x0In) { x0_ = x0In; }
      void setY0 (long double y0In) { y0_ = y0In; }

      void setK0 (long double k0In) { k0_ = k0In; }
      void setOver (int overIn) { over_ = overIn; }
      void setGeoc (int geocIn) { geoc_ = geocIn; }
      void setTo_meter (long double to_meterIn) { to_meter_ = to_meterIn; }
      void setFr_meter (long double fr_meterIn) { fr_meter_ = fr_meterIn; }

      // inherited from above

      virtual const DgDVec2D& undefAddress (void) const
               { return DgDVec2D::undefDgDVec2D; }

      virtual long double dist (const DgDVec2D& add1, const DgDVec2D& add2) const
         { return add1.distance(add2); } 

      virtual string add2str (const DgDVec2D& add) const
                       { return string(add); }

      virtual string add2str (const DgDVec2D& add, char delimiter) const
                  { return dgg::util::to_string(add.x(), formatStr()) + delimiter + 
                           dgg::util::to_string(add.y(), formatStr()); }

      virtual const char* str2add (DgDVec2D* add, const char* str, 
                                   char delimiter) const
                  {    if (!add) add = new DgDVec2D();
                       return add->fromString(str, delimiter); }

      virtual string dist2str (const long double& dist) const
                       { return dgg::util::to_string(dist, formatStr()); }

      virtual long double dist2dbl (const long double& dist) const
                       { return dist; }

      virtual std::uint64_t dist2int (const long double& dist) const
                       { return static_cast<std::uint64_t>(dist); }

      // the following routines are "back-doors" included for speed;
      // use with care!

      virtual DgAddressBase* vecAddress (const DgDVec2D& v) const
                    { return new DgAddress<DgDVec2D>(v); }

      virtual DgLocation* vecLocation (const DgDVec2D& v) const
                    { return makeLocation(v); }

      virtual DgDVec2D getVecAddress (const DgAddressBase& add) const
         { return static_cast< const DgAddress<DgDVec2D> &>(add).address(); }

      virtual DgDVec2D getVecLocation (const DgLocation& loc) const
                    { return *getAddress(loc); }

   protected:

      DgGeoCoord proj0_; // central lon/lat in radians

      long double x0_;   // easting; default 0.0
      long double y0_;   // northing; default 0.0
      long double k0_;   // general scaling factor; default 1.0

      // not currently used; kept for PROJ4 compatability

      long double to_meter_; // cartesian scaling
      long double fr_meter_; // cartesian scaling
      int over_;        // over-range flag
      int geoc_;        // geocentric latitude flag

}; // class DgGeoProjRF

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgGeoProjRF& obj)
{
   return stream << obj.name() << ": " << obj.proj0()
                 << " " << obj.x0() << " " << obj.y0() << " " << obj.k0();

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgDiscRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDiscRF.h: DgDiscRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDISCRF_H
#define DGDISCRF_H

#include <cstdint>

#include "DgRF.h"
#include "DgPolygon.h"

////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> 
class DgDiscRF : public DgRF<A, std::int64_t> {

   public:

      class DgQuantConverter : public DgConverter<B, DB, A, std::int64_t> {

         public:

            DgQuantConverter (const DgRF<B, DB>& fromFrame, 
                              const DgDiscRF<A, B, DB>& toFrame)
               : DgConverter<B, DB, A, std::int64_t> 
                       (static_cast< const DgRF<B, DB>& >(fromFrame), 
                        static_cast< const DgRF<A, std::int64_t>& >(toFrame)) { }

            virtual A convertTypedAddress (const B& addIn) const
              { return 
                   static_cast<const DgDiscRF<A, B, DB>&>(
                                  this->toFrame()).quantify(addIn); 
	      }

      };

      class DgInvQuantConverter : public DgConverter<A, std::int64_t, B, DB> {

         public:

            DgInvQuantConverter (const DgDiscRF<A, B, DB>& fromFrame,
                                 const DgRF<B, DB>& toFrame)
               : DgConverter<A, std::int64_t, B, DB> (fromFrame, toFrame) { }

            virtual B convertTypedAddress (const A& addIn) const
             { return 
                  static_cast<const DgDiscRF<A, B, DB>&>(
                                         this->fromFrame()).invQuantify(addIn); 
	     }

      };

      DgDiscRF (DgRFNetwork& networkIn, const DgRF<B, DB>& backFrameIn,
                const string& nameIn = "Disc", long double eIn = 1.0L,
                long double rIn = 1.0L, long double cIn = 1.0L, long double areaIn = 1.0L)
        : DgRF<A, std::int64_t> (networkIn, nameIn), backFrame_ (&backFrameIn),
          e_ (eIn), r_ (rIn), c_ (cIn), area_ (areaIn)
        { new DgQuantConverter(backFrame(), *this);
          new DgInvQuantConverter(*this, backFrame()); }

      DgDiscRF (const DgDiscRF<A, B, DB>& rf) : DgRF<A, std::int64_t> (rf), 
          backFrame_ (&rf.backFrame()), e_ (rf.e()), r_ (rf.r()),
          c_ (rf.c()), area_ (rf.area())
        { new DgQuantConverter(backFrame(), *this);
          new DgInvQuantConverter(*this, backFrame()); 
	}

      DgDiscRF& operator= (const DgDiscRF<A, B, DB>& rf)
          { 
             if (&rf != this)
             {
                DgRF<A, std::int64_t>::operator=(rf); 
                e_ = rf.e();
                r_ = rf.r();
                c_ = rf.c();
                area_ = rf.area();
                backFrame_ = &rf.backFrame();
             }
             return *this; 
          }

      // get methods

      const DgRF<B, DB>& backFrame (void) const { return *backFrame_; }

      long double e    (void) const { return e_; }
      long double r    (void) const { return r_; }
      long double c    (void) const { return c_; }
      long double area (void) const { return area_; }

      // set methods

      void setE    (long double eIn) { e_ = eIn; }
      void setR    (long double rIn) { r_ = rIn; }
      void setC    (long double cIn) { c_ = cIn; }
      void setArea (long double areaIn) { area_ = areaIn; }

      // misc methods
      
      virtual string dist2str (const std::int64_t& dist) const { return dgg::util::to_string(dist); }
      virtual long double dist2dbl (const std::int64_t& dist) const { return (long double) dist; }
      virtual std::uint64_t dist2int (const std::int64_t& dist) const 
                         { return static_cast<std::uint64_t>(dist); }

      virtual void setPoint (const DgLocation& loc, DgLocation& point) const;

      virtual void setPoint (const DgLocation& loc, const DgRFBase& rf,
                                                   DgLocation& point) const; 
      virtual void setPoint (const A& add, const DgRFBase& rf, 
                             DgLocation& point) const
               { setAddPoint(add, point); rf.convert(&point); }

      virtual void setPoint (const A& add, DgLocation& pt) const
                    { pt.clearAddress(); backFrame().convert(&pt); 
                      setAddPoint(add, pt); }

      virtual void setVertices (const DgLocation& loc, DgPolygon& vec) const;

      virtual void setVertices (const DgLocation& loc, const DgRFBase& rf,
                                                       DgPolygon& vec) const;

      virtual void setVertices (const A& add, const DgRFBase& rf, 
                                                        DgPolygon& vec) const
               { setAddVertices(add, vec); rf.convert(vec); }

      virtual void setVertices  (const A& add, DgPolygon& vec) const
               { vec.clearAddress(); backFrame().convert(vec); 
                 setAddVertices(add, vec); }

      virtual void setNeighbors (const DgLocation& loc, DgLocVector& vec) const;

      virtual void setNeighbors (const A& add, const DgRFBase& rf, 
                                                        DgLocVector& vec) const
               { setAddNeighbors(add, vec); rf.convert(vec); }

      virtual void setNeighbors (const A& add, DgLocVector& vec) const
               { vec.clearAddress(); this->convert(vec); setAddNeighbors(add, vec); }

      virtual DgLocVector* makeNeighbors (const DgLocation& loc) const
               { DgLocVector* vec = new DgLocVector(*this);
                 setNeighbors(loc, *vec);  return vec; }

      virtual DgPolygon* makeVertices (const DgLocation& loc) const
               { DgPolygon* vec = new DgPolygon(backFrame());
                 setVertices(loc, *vec);  return vec; }

      virtual DgLocation* makePoint (const DgLocation& loc) const
               { DgLocation* pt = new DgLocation(backFrame());
                 setPoint(loc, *pt);  return pt; }

      virtual DgLocVector* makeNeighbors (const A& add) const
               { DgLocVector* vec = new DgLocVector(*this);
                 setNeighbors(add, *vec);  return vec; }

      virtual DgPolygon* makeVertices (const A& add) const
               { DgPolygon* vec = new DgPolygon(backFrame());
                 setVertices(add, *vec);  return vec; }

      virtual DgLocation* makePoint (const A& add) const
               { DgLocation* pt = new DgLocation(backFrame());
                 setPoint(add, *pt);  return pt; }

      // remind users of the pure virtual functions remaining from above
      
      virtual string add2str (const A& add) const = 0;
      virtual string add2str (const A& add, char delimiter) const = 0;

      virtual std::int64_t dist (const A& add1, const A& add2) const = 0;

      virtual const char* str2add (A* add, const char* str, char delimiter) 
                                                                      const = 0;

      virtual const A& undefAddress (void) const = 0;

      // new pure virtual functions

      virtual A quantify    (const B& point) const = 0;
      virtual B invQuantify (const A& add)   const = 0;

      virtual void setAddNeighbors (const A& add, DgLocVector& vec) const = 0;
      virtual void setAddVertices  (const A& add, DgPolygon& vec) const = 0;

   protected:

      virtual void setAddPoint (const A& add, DgLocation& pt) const;

      const DgRF<B, DB>* backFrame_;

      long double e_;   // edge length
      long double r_;   // radius (max center-to-vertex)
      long double c_;   // irrational constant
      long double area_; // cell area

};

#include "DgDiscRF_template.h"

#endif


<|start_filename|>src/DgInShapefileAtt.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgInShapefileAtt.cpp: DgInShapefileAtt class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <sstream>

#include "DgInShapefileAtt.h"
#include "DgLocList.h"
#include "DgPolygon.h"
#include "DgPolygon.h"
#include "DgLocation.h"
#include "DgCell.h"
#include "DgContCartRF.h"

////////////////////////////////////////////////////////////////////////////////
DgInShapefileAtt::DgInShapefileAtt (const DgGeoSphRF& geoRFIn,
            const string* fileNameIn, DgReportLevel failLevelIn)
   : DgInShapefile (geoRFIn, fileNameIn, failLevelIn), 
      dbfFile_ (NULL), numFields_ (0)
{
   if (fileNameIn)
      if (!open(NULL, DgBase::Silent))
         report("DgInShapefileAtt::DgInShapefileAtt() unable to open file " +
                fileName_, failLevel());

} // DgInShapefileAtt::DgInShapefileAtt

////////////////////////////////////////////////////////////////////////////////
bool 
DgInShapefileAtt::open (const string* fileNameIn, DgReportLevel failLevelIn)
{
   if (!DgInShapefile::open(fileNameIn, failLevelIn))
      return false;

   dbfFile_ = DBFOpen(fileName_.c_str(), "rb");
   if (dbfFile_ == NULL)
   {
      report("DgInShapefileAtt::open() unable to open dbf file " +
             fileName_, failLevelIn);
      return false;
   }

   DBFFieldType type;
   char fName[12];
   int w, p;
   numFields_ = DBFGetFieldCount(dbfFile_);
   for (int i = 0; i < numFields_; i++)
   {
      type = DBFGetFieldInfo(dbfFile_, i, fName, &w, &p);
      if (type == FTInvalid)
      {
         report("DgInShapefileAtt::open() invalid field #" + 
                dgg::util::to_string(i) + " in dbf file " + 
                fileName_, failLevelIn);
         return false;
      }

      DgDBFfield f(fName, type, i, w, p);
      fields_.insert(f);
   }

   return true;
}

////////////////////////////////////////////////////////////////////////////////
void 
DgInShapefileAtt::close (void) 
{ 
   if (dbfFile_)
   {
      DBFClose(dbfFile_);
      dbfFile_ = NULL;
      numFields_ = 0;
      fields_.clear();
   }

   DgInShapefile::close();
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgInShapefileAtt::getNextEntity (void)
{
   DgInShapefile::getNextEntity();
   
   curObjFields_.clear();

   for (set<DgDBFfield>::iterator it = fields_.begin(); it != fields_.end(); it++)
   {
      if (!DBFIsAttributeNULL(dbfFile_, curRecNum_, it->fieldNum()))
         curObjFields_.insert(*it);
   }
}

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgTriGrid2DS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgTriGrid2DS.h: DgTriGrid2DS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGTRIGRID2DS_H 
#define DGTRIGRID2DS_H 

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgDiscRFS2D.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgTriGrid2DS : public DgDiscRFS2D {

   public:

      DgTriGrid2DS (DgRFNetwork& networkIn, 
                    const DgRF<DgDVec2D, long double>& backFrameIn,
                    int nRes = 1, unsigned int apertureIn = 4, 
                    bool isCongruentIn = true, bool isAlignedIn = false,
                    const string& nameIn = "3T4");

      DgTriGrid2DS (const DgTriGrid2DS& rf);

     ~DgTriGrid2DS (void);

      DgTriGrid2DS& operator= (const DgTriGrid2DS& rf);

      int radix (void) const { return radix_; }

   protected:

      int radix_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgIVec2D>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgIVec2D>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgPolygon.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPolygon.cpp: DgPolygon class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgPolygon.h"
#include "DgContCartRF.h"

////////////////////////////////////////////////////////////////////////////////
void 
DgPolygon::densify (int ptsPerEdge)
{ 
   if (ptsPerEdge <= 0) return;

   const DgContCartRF* cc = dynamic_cast<const DgContCartRF*>(&rf());
   if (cc == 0) report("DgPolygon::densify() with non-CCRF", DgBase::Fatal);

   DgPolygon densVerts(*cc);

   vector<DgAddressBase*>& v0 = addressVec();
   vector<DgAddressBase*>& v1 = densVerts.addressVec();

   // for each edge
   for (unsigned long i = 0; i < v0.size(); i++)
   {
      DgDVec2D p1 = dynamic_cast< DgAddress<DgDVec2D>& >(*v0[i]).address();
      DgDVec2D p2 = dynamic_cast< DgAddress<DgDVec2D>& >( 
                                          *v0[(i + 1) % v0.size()]).address();

      long double fracStep = 1.0 / (ptsPerEdge + 1);
      long double frac = fracStep;

      // add the first point

      v1.push_back(new DgAddress<DgDVec2D>(p1));

      // add each densification point

      for (int j = 0; j < ptsPerEdge; j++)
      {
         DgDVec2D p3 = DgDVec2D::fracPoint(p1, p2, frac);
         frac += fracStep;

         v1.push_back(new DgAddress<DgDVec2D>(p3));
      }

      // p2 should get pushed next time
   }

   // now replace the original with the densified version

   *this = densVerts;

} // DgPolygon::densify

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgSqrD8Grid2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSqrD8Grid2D.cpp: DgSqrD8Grid2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgSqrD8Grid2D.h"
#include "DgLocVector.h"

////////////////////////////////////////////////////////////////////////////////
void
DgSqrD8Grid2D::setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(), add.j() + 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1, add.j() + 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1, add.j())));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1, add.j() - 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(), add.j() - 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1, add.j() - 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1, add.j())));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1, add.j() + 1)));

} // void DgSqrD8Grid2D::setAddNeighbors

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgUtil.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgUtil.h: DgUtil class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGUTIL_H
#define DGUTIL_H

#include <vector>
#include <algorithm>

// make sure we have the necessary C99 support in our gcc version

#define DGGS_GCC_VERSION (__GNUC__ * 10000 \
                              + __GNUC_MINOR__ * 100 \
                              + __GNUC_PATCHLEVEL__)

#include <cmath>
#include <cstdint>
#include <limits>// hard-code the TR1 limits (these are GPL)

namespace dgg { namespace util {

// Some older compilers may have an easier time matching this:
template <class T>
void release(T x)
{
 delete x;
}

// Delete a pointer parameter, and set to zero: 
template <class T>
void release(T *& x)
{
 delete x;
 x = 0;		// a little pedantic, but there we have it
}

/* Delete each pointed-at object in a vector, then release the pointers: */
template <class T>
void release(std::vector<T>& v)
{
 for(typename std::vector<T>::iterator i = v.begin(); i != v.end(); ++i)
  dgg::util::release(*i);

 /*
  Note: g++ 4.4.1 is ok with the straightforward: 
	std::for_each(v.begin(), v.end(), dgg::util::release<T>);
 */

 v.resize(0);
}

// Round a long double into a long:
inline long lrint(const long double& x)
{
 return std::llrint(x);
}

}} // namespace dgg::util

#endif



<|start_filename|>src/DgBase.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBase.h: DgBase class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBASE_H
#define DGBASE_H

#include <iostream>
#include <string>

using namespace std;

#define DGDEBUG         0
#define DGGRID_VERSION  "6.2b1" 

////////////////////////////////////////////////////////////////////////////////
class DgBase {

   public:

      enum DgReportLevel { Debug1, Debug0, Info, Warning, Fatal, Silent };

   private:

      static const string defaultName;
      static DgReportLevel minReportLevel_;

   public:

      virtual ~DgBase (void);

      static void setMinReportLevel (DgReportLevel newRLevel)
                   { minReportLevel_ = newRLevel; }

      static DgReportLevel minReportLevel (void) { return minReportLevel_; }

      static bool testArgEqual (int argc, int expected, 
                     const string& message = string("invalid argument count"),
                     DgReportLevel level = Fatal);

      static bool testArgEqual (int argc, char* argv[], int expected, 
                     const string& message = string("invalid argument count"));

      static bool testArgMin (int argc, int minExpected, 
                     const string& message = string("invalid argument count"),
                     DgReportLevel level = Fatal);

      static bool testArgMin (int argc, char* argv[], int minExpected, 
                     const string& message = string("invalid argument count"));

      DgBase (const string& instanceName = defaultName);

      DgBase (const string* instanceName = NULL);
      
      void setInstanceName (const string& instanceName)
              { instanceName_ = instanceName; }

      const string& instanceName (void) const { return instanceName_; }

   protected:

      void report (const string& message, DgReportLevel level = Info) const;
      void debug  (const string& message) const;

   private:

      // data members

      string instanceName_;
};

////////////////////////////////////////////////////////////////////////////////
extern "C" void report (const string& message, 
                        DgBase::DgReportLevel level = DgBase::Info);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline void
DgBase::debug (const string& message) const
//
// Print-out a debugging message if the DGDEBUG flag is set. Otherwise this
// is a null operation.
//
////////////////////////////////////////////////////////////////////////////////
{

#if DGDEBUG

   cout << "DEBUG: [" << instanceName_ << "] " << message << endl;

#endif

} // void DgBase::debug

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgBase& b)
            { return stream << b.instanceName(); }

#endif


<|start_filename|>src/DgDVec2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDVec2D.h: DgDVec2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDVEC2D_H
#define DGDVEC2D_H

#include <cmath>
#include <iostream>

#include "DgUtil.h"
#include "DgConstants.h"
#include "DgString.h"

using namespace std;

class DgDVec3D;

////////////////////////////////////////////////////////////////////////////////
class DgDVec2D {

   public:

      static DgDVec2D midPoint (const DgDVec2D& pt1, const DgDVec2D& pt2)
                       { return pt1 * M_HALF + pt2 * M_HALF; }

      static DgDVec2D fracPoint (const DgDVec2D& pt1, const DgDVec2D& pt2, 
                                long double fraction)
                       { return pt2 * fraction + pt1 * (M_ONE - fraction); }

      static const DgDVec2D& undefDgDVec2D;

      DgDVec2D (void) { x_ = M_ZERO; y_ = M_ZERO; }

      DgDVec2D (long double x, long double y) { x_ = x; y_ = y; }

      DgDVec2D (const DgDVec2D& pt) : x_ (pt.x_), y_ (pt.y_) {}
      DgDVec2D (const DgDVec3D& pt);
      //DgDVec2D (const XPoint&  pt) : x_ (pt.x),  y_ (pt.y)  {}

      void setX (long double x) { x_ = x; }
      void setY (long double y) { y_ = y; }

      long double distance (const DgDVec2D& pt) const
              { return (pt - *this).magnitude(); }

      long double x (void) const { return x_; }
      long double y (void) const { return y_; }
      
      long double magnitude (void) const { return sqrt(x_ * x_ + y_ * y_); }

      long double dotProd (const DgDVec2D& pt) const 
                { return x_ * pt.x() + y_ * pt.y(); }

      long double angle (const DgDVec2D& pt) const  // angle between in radians
                { return acos(dotProd(pt) / (magnitude() * pt.magnitude())); }

      const char* fromString (const char* str, char delimiter);

      inline DgDVec2D& scale (long double xScaleFactor, long double yScaleFactor);
      inline DgDVec2D& rotate (long double degrees);

      //inline operator XPoint   (void) const;
      inline operator string (void) const;

      inline DgDVec2D& operator=  (const DgDVec2D& pt);
      DgDVec2D& operator=  (const DgDVec3D& pt);
      inline DgDVec2D& operator+= (const DgDVec2D& pt);
      inline DgDVec2D& operator-= (const DgDVec2D& pt);

      inline DgDVec2D& operator*= (long double scaleFactor);
      inline DgDVec2D& operator/= (long double scaleFactor);

      friend DgDVec2D operator*  (const DgDVec2D& pt, long double scaleFactor);
      friend DgDVec2D operator*  (long double scaleFactor, const DgDVec2D& pt);
      friend DgDVec2D operator+  (const DgDVec2D& pt1, const DgDVec2D& pt2);
      friend DgDVec2D operator-  (const DgDVec2D& pt1, const DgDVec2D& pt2);

      friend bool operator== (const DgDVec2D& pt1, const DgDVec2D& pt2);
      friend bool operator!= (const DgDVec2D& pt1, const DgDVec2D& pt2);
      friend bool operator<  (const DgDVec2D& pt1, const DgDVec2D& pt2);
      friend bool operator<= (const DgDVec2D& pt1, const DgDVec2D& pt2);
      friend bool operator>  (const DgDVec2D& pt1, const DgDVec2D& pt2);
      friend bool operator>= (const DgDVec2D& pt1, const DgDVec2D& pt2);

      friend ostream& operator<< (ostream& stream, const DgDVec2D& pt);

   private:

      long double x_;
      long double y_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D&
DgDVec2D::scale (long double xScaleFactor, long double yScaleFactor)
//
// Scale me by xScaleFactor in the x direction and yScaleFactor in the y
// direction.
//
////////////////////////////////////////////////////////////////////////////////
{
   x_ *= xScaleFactor;
   y_ *= yScaleFactor;

   return *this;

} // void DgDVec2D::scale

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D&
DgDVec2D::rotate (long double degrees)
//
// Rotate me about the origin degrees degrees in a counter-clockwise
// direction.
//
////////////////////////////////////////////////////////////////////////////////
{
   while (degrees < M_ZERO) degrees += 360.0L;
   while (degrees >= 360.0L) degrees -= 360.0L;
   if (fabs(degrees - M_ZERO) < M_EPSILON) return *this;

   long double rotAng = degrees * dgM_PI_180;
   long double cosAng = cos(rotAng);
   long double sinAng = sin(rotAng);
   long double x = x_;
   long double y = y_;

   x_ = x * cosAng - y * sinAng;
   y_ = x * sinAng + y * cosAng;

   return *this;

} // void DgDVec2D::rotate

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D::operator string (void) const
{
   const char* fmtStr = "%.9LF";
   return "(" + dgg::util::to_string(x_, fmtStr) + ", " 
          + dgg::util::to_string(y_, fmtStr) + ")";

} // DgDVec2D::operator string

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D&
DgDVec2D::operator= (const DgDVec2D& pt)
{
   if (&pt != this)
   {
      x_ = pt.x_;
      y_ = pt.y_;
   }
   return *this;

} // DgDVec2D& DgDVec2D::operator=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D&
DgDVec2D::operator*= (long double scaleFactor)
{
   scale(scaleFactor, scaleFactor);

   return *this;

} // DgDVec2D& DgDVec2D::operator*=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D&
DgDVec2D::operator/= (long double scaleFactor)
{
   x_ /= scaleFactor;
   y_ /= scaleFactor;

   return *this;

} // DgDVec2D& DgDVec2D::operator/=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D&
DgDVec2D::operator+= (const DgDVec2D& pt)
{
   x_ += pt.x_;
   y_ += pt.y_;

   return *this;

} // DgDVec2D& DgDVec2D::operator+=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D&
DgDVec2D::operator-= (const DgDVec2D& pt)
{
   x_ -= pt.x_;
   y_ -= pt.y_;

   return *this;

} // DgDVec2D& DgDVec2D::operator-=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D
operator* (const DgDVec2D& pt, long double scaleFactor)
{
   DgDVec2D result(pt);
   result.scale(scaleFactor, scaleFactor);

   return result;

} // DgDVec2D operator*

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D
operator* (long double scaleFactor, const DgDVec2D& pt)
{
   DgDVec2D result(pt);
   result.scale(scaleFactor, scaleFactor);

   return result;

} // DgDVec2D operator*

////////////////////////////////////////////////////////////////////////////////
inline bool
operator== (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   return (pt1.x_ == pt2.x_ && pt1.y_ == pt2.y_);

} // bool operator==

////////////////////////////////////////////////////////////////////////////////
inline bool
operator!= (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   return !operator==(pt1, pt2);

} // bool operator!=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator> (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   return (pt1.x_ > pt2.x_ && pt1.y_ > pt2.y_);

} // bool operator>

////////////////////////////////////////////////////////////////////////////////
inline bool
operator>= (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   return (pt1.x_ >= pt2.x_ && pt1.y_ >= pt2.y_);

} // bool operator>=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator< (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   return (pt1.x_ < pt2.x_ && pt1.y_ < pt2.y_);

} // bool operator<

////////////////////////////////////////////////////////////////////////////////
inline bool
operator<= (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   return (pt1.x_ <= pt2.x_ && pt1.y_ <= pt2.y_);

} // bool operator<=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D
operator+ (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   DgDVec2D result(pt1);
   result += pt2;

   return result;

} // DgDVec2D operator+

////////////////////////////////////////////////////////////////////////////////
inline DgDVec2D
operator- (const DgDVec2D& pt1, const DgDVec2D& pt2)
{
   DgDVec2D result(pt1);
   result -= pt2;

   return result;

} // DgDVec2D operator-

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgDVec2D& pt)
{
   return stream << string(pt);

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIDGGS43H.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS43H.h: DgIDGGS43H class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIDGGS43H_H 
#define DGIDGGS43H_H

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgIDGGS.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgIDGGS43H : public DgIDGGS {

   public:

      DgIDGGS43H (DgRFNetwork& networkIn, const DgGeoSphRF& backFrameIn,
             const DgGeoCoord& vert0, long double azDegs, int nResIn = 1,
             const string& nameIn = "ISEA43H", const string& projType = "ISEA",
             int numAp4 = 0, bool isSuperfund = false)
         : DgIDGGS (networkIn, backFrameIn, vert0, azDegs, 3, nResIn,
                "HEXAGON", nameIn, projType, true, numAp4, isSuperfund)
         { frequency_ = sqrt((long double) aperture()); }

      DgIDGGS43H (const DgIDGGS43H& rf);

     ~DgIDGGS43H (void);

      DgIDGGS43H& operator= (const DgIDGGS43H& rf);

      long double frequency   (void) const { return frequency_; }

   protected:

      long double frequency_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgQ2DICoord>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgQ2DICoord>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgAddressBase.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgAddressBase.cpp: DgAddressBase class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgAddressBase.h"

////////////////////////////////////////////////////////////////////////////////
DgAddressBase::~DgAddressBase (void)
{
   // virtual destructor

} // DgAddressBase::~DgAddressBase

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgRandom.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRandom.h: DgRandom class definitions.
//
//    Contains two DgRandom sub-classes: DgRand is rand()-based, and
//      DgRandMother is based on George Marsaglia's multiply-with-carry
//      "mother" function.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGRANDOM_H
#define DGRANDOM_H

#include <iostream>

using namespace std;

#include "DgEllipsoidRF.h"

////////////////////////////////////////////////////////////////////////////////
class DgRandom {

   public:

      DgRandom (const DgRandom& obj)
               : status_ (obj.status()), maxVal_ (obj.maxVal()) { }

      DgRandom (const unsigned long int statusIn,
                const unsigned long int maxValIn)
               : status_ (statusIn), maxVal_ (maxValIn) { }

      DgRandom& operator= (const DgRandom& obj)
               {
                  if (&obj != this)
                  {
                     status_ = obj.status();
                     maxVal_ = obj.maxVal();
                  }

                  return *this;

               } // DgRandom::operator=

      virtual ~DgRandom (void);

      // get methods

      unsigned long int status (void) const { return status_; }
      unsigned long int maxVal (void) const { return maxVal_; }

      // set methods

      void setStatus (const unsigned long int statusIn) { status_ = statusIn; }

      // random generation methods

      unsigned long int nextInt (void)
          { setStatus(nextRand()); return status(); }

      double nextDouble (void)  // return 0.0...1.0
          { 
             setStatus(nextRand()); 
             return (double) status() / (double) maxVal(); 
          }

      double randInRange (double min, double max) // inclusive
          { 
             return (min + (max - min) * nextDouble());
          }

      DgGeoCoord nextGeo (void) 
         { 
            return DgGeoCoord(randInRange(-dgM_PI, dgM_PI),
                              asin(randInRange(-1.0, 1.0)));
         }

   protected:

      virtual unsigned long int nextRand (void) = 0;

   private:

      unsigned long int status_;
      unsigned long int maxVal_;

}; // class DgRandom

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgRandom& obj)
{
   return stream << obj.status();

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgRand : public DgRandom {

   public:

      DgRand (const DgRand& obj) : DgRandom (obj) { srand((unsigned) status()); }

      DgRand (const unsigned long int statusIn = 1)
         : DgRandom (statusIn, RAND_MAX) { srand((unsigned) status()); }

   protected:

      virtual unsigned long int nextRand (void) { return rand(); }

}; // class DgRand

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#define m32Double  4294967295.0  /* 2^32-1 */

class DgRandMother : public DgRandom {

   public:

      DgRandMother (const DgRandMother& obj) : DgRandom (obj) { srand((unsigned) status()); }

      DgRandMother (const unsigned long int statusIn = 1)
         : DgRandom (statusIn, (unsigned long int) m32Double) { }

   protected:

      virtual unsigned long int nextRand (void);

}; // class DgRandMother

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIDGGS4T.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS4T.h: DgIDGGS4T class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIDGGS4T_H 
#define DGIDGGS4T_H

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgIDGGS.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgIDGGS4T : public DgIDGGS {

   public:

      DgIDGGS4T (DgRFNetwork& networkIn, const DgGeoSphRF& backFrameIn,
               const DgGeoCoord& vert0, long double azDegs, int nResIn = 1,
               const string& nameIn = "ISEA4T", const string& projType = "ISEA")
         : DgIDGGS (networkIn, backFrameIn, vert0, azDegs, 4, nResIn,
               "TRIANGLE", nameIn, projType, false, 0, false) 
           { radix_ = (int) sqrt((float) aperture()); }

      DgIDGGS4T (const DgIDGGS4T& rf);

     ~DgIDGGS4T (void);

      DgIDGGS4T& operator= (const DgIDGGS4T& rf);

      int radix (void) const { return radix_; }

   protected:

      int radix_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgQ2DICoord>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgQ2DICoord>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedRFBase.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedRFBase.h: DgBoundedRFBase class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBOUNDEDRFBASE_H
#define DGBOUNDEDRFBASE_H

#include <cstdint>

#include "DgDiscRF.h"

class DgLocation;
class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
template<class B, class DB> class DgBoundedRFBase {

   public:
   
      virtual ~DgBoundedRFBase (void) { }
      
      const DgRFBase& rf (void) const { return rf_; }
      
      operator const DgRFBase& (void) const { return rf(); }
      
      virtual bool validLocation (const DgLocation& loc, 
                                  bool convert = true) const = 0;

      virtual DgLocation& incrementLocation (DgLocation& loc, 
                                             bool convert = true) const = 0;
                       
      virtual DgLocation& decrementLocation (DgLocation& loc, 
                                             bool convert = true) const = 0; 
                                     
      const DgLocation& first (void) const { return first_; }
      const DgLocation& last  (void) const { return last_; }
      const DgLocation& end   (void) const { return end_; }

      std::uint64_t size (void) const { return size_; }
      bool validSize (void) const { return validSize_; }

      bool zeroBased (void) const { return zeroBased_; }
      void setZeroBased (bool zBasedIn) { zeroBased_ = zBasedIn; }

      virtual std::uint64_t seqNum (const DgLocation& loc,
                                        bool convert = true) const = 0; 

      virtual bool lessThan (const DgLocation& loc1, 
                     const DgLocation& loc2, bool convert = true) const
                 { return (seqNum(loc1, convert) < seqNum(loc2, convert)); }

      virtual DgLocation* locFromSeqNum (std::uint64_t sNum) const = 0;
      
      // provide a generic interface to the discrete grid functionality

      virtual const DgRF<B, DB>& backFrame (void) const = 0;
      
      virtual string dist2str (const std::int64_t& dist) const = 0;
      virtual long double dist2dbl (const std::int64_t& dist) const = 0;

      virtual std::uint64_t dist2int (const std::int64_t& dist) const = 0;

      virtual void setPoint (const DgLocation& loc, DgLocation& point) 
                                                                     const = 0;

      virtual void setPoint (const DgLocation& loc, const DgRFBase& rf,
                                                  DgLocation& point) const = 0;

      virtual DgLocation* makePoint (const DgLocation& loc) const = 0;

      virtual void setVertices (const DgLocation& loc, DgPolygon& vec) 
                                                                     const = 0;

      virtual void setVertices (const DgLocation& loc, const DgRFBase& rf,
                                                   DgPolygon& vec) const = 0;

      virtual DgPolygon* makeVertices (const DgLocation& loc) const = 0;

      virtual void setNeighbors (const DgLocation& loc, DgLocVector& vec) 
                                                                     const = 0;

      virtual DgLocVector* makeNeighbors (const DgLocation& loc) const = 0;

   protected:

      DgBoundedRFBase (const DgRFBase& rfIn, const DgLocation& firstIn, 
                       const DgLocation& lastIn, const DgLocation& endIn,
                       bool zBasedIn = true)
         : size_(0), validSize_(false), rf_ (rfIn), 
	   first_ (firstIn), last_ (lastIn), end_ (endIn),
	   zeroBased_ (zBasedIn) {}
         
      std::uint64_t size_;
      bool validSize_;

   private:
   
      const DgRFBase& rf_;
      DgLocation first_;
      DgLocation last_;
      DgLocation end_;

      bool zeroBased_; // seq starts with 0 (or 1)?

}; 

////////////////////////////////////////////////////////////////////////////////
template<class B, class DB> inline
ostream& operator<< (ostream& stream, const DgBoundedRFBase<B, DB>& rfIn)
{ return stream << "Bnd-" << rfIn.rf(); }

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedIDGGS.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedIDGGS.cpp: DgBoundedIDGGS class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <limits>
#include <cstdint>

#include "DgBoundedIDGGS.h"
#include "DgBoundedHexC2RF2D.h"
#include "DgIDGGS.h"
#include "DgTriGrid2DS.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgBoundedIDGGS::DgBoundedIDGGS (const DgIDGGS& rf)
   : DgBoundedRF< DgResAdd<DgQ2DICoord>, DgGeoCoord, long double > (rf, 
                  DgResAdd<DgQ2DICoord> (DgQ2DICoord(0, 0), 0),
                  DgResAdd<DgQ2DICoord> (DgQ2DICoord(0, 0), 0), 
                  rf.undefAddress()), IDGGS_ (rf)
{ 
   // allocate the grids

   grids_ = new vector<DgBoundedIDGG*>(IDGGS().nRes());

   for (int i = 0; i < IDGGS().nRes(); i++)
      (*grids_)[i] = new DgBoundedIDGG(rf.idgg(i));

   // set the correct last address

   int maxRes = IDGGS().nRes() - 1;
   DgResAdd<DgQ2DICoord> last((*grids_)[maxRes]->lastAdd(), maxRes);

   setLastAdd(last);

   // set the size

   size_ = 0;
   for (int i = 0; i < IDGGS().nRes(); i++)
   {
      std::uint64_t lastSize = size_;

      const DgBoundedIDGG* g = (*grids_)[i];

      if (g->validSize()) size_ += g->size();

      if (!g->validSize() || size() < lastSize)
      {
         report("DgBoundedIDGGS::DgBoundedIDGGS() invalid size setting due to "
                "possible overflow", DgBase::Warning);
         validSize_ = false;
      }
   }

   validSize_ = true;

} // DgBoundedIDGGS::DgBoundedIDGGS

////////////////////////////////////////////////////////////////////////////////
DgResAdd<DgQ2DICoord>&
DgBoundedIDGGS::incrementAddress (DgResAdd<DgQ2DICoord>& add) const
{
   if (!validAddress(add)) return add = invalidAdd();
   else if (add == lastAdd()) return add = endAdd();
   else if (add == endAdd()) return add;

   const DgBoundedIDGG& grid = *(grids()[add.res()]);

   DgQ2DICoord v(add.address());
   add = DgResAdd<DgQ2DICoord>(grid.incrementAddress(v), add.res());

   if (add.address() == grid.endAdd())
   {
      if (add.res() == (IDGGS().nRes() - 1)) return add = endAdd();
      else 
      {
         int newRes = add.res() + 1;
         add = DgResAdd<DgQ2DICoord>(grids()[newRes]->firstAdd(), newRes);
      }
   }

   return add;

/*
   if (add.address() == grid.lastAdd() ||
       add.address() == grid.endAdd())
   {
      if (add.res() == (IDGGS().nRes() - 1)) return add = endAdd();
      else 
      {
         int newRes = add.res() + 1;
         return add = DgResAdd<DgQ2DICoord>(grids()[newRes]->firstAdd(), newRes);
      }
   }
   else
   {
      DgQ2DICoord v(add.address());
      return add = DgResAdd<DgQ2DICoord>(grid.incrementAddress(v), add.res());
   }
*/

} // DgResAdd<DgQ2DICoord>& DgBoundedIDGGS::incrementAddress

////////////////////////////////////////////////////////////////////////////////
DgResAdd<DgQ2DICoord>&
DgBoundedIDGGS::decrementAddress (DgResAdd<DgQ2DICoord>& add) const
{
   if (!validAddress(add) || add == firstAdd()) return add = invalidAdd();

   const DgBoundedIDGG& grid = *(grids()[add.res()]);

   if (add.address() == grid.firstAdd())
   {
      int newRes = add.res() - 1;
      return add = DgResAdd<DgQ2DICoord>(grids()[newRes]->lastAdd(), newRes);
   }
   else
   {
      DgQ2DICoord v(add.address());
      return add = DgResAdd<DgQ2DICoord>(grid.decrementAddress(v), add.res());
   }

} // DgResAdd<DgQ2DICoord>& DgBoundedIDGGS::decrementAddress

////////////////////////////////////////////////////////////////////////////////
std::uint64_t 
DgBoundedIDGGS::seqNumAddress (const DgResAdd<DgQ2DICoord>& add) const
{
   if (!validSize())
   {
      report("DgBoundedIDGGS::seqNumAddress() valid size required",
             DgBase::Fatal);
      return 0;
   }

   std::uint64_t sNum = 0;
   if (!zeroBased()) sNum++;

   for (int i = 0; i < add.res(); i++) sNum += (*grids_)[i]->size();

   sNum += (*grids_)[add.res()]->seqNumAddress(add.address());

   return sNum;

} // std::uint64_t DgBoundedIDGGS::seqNumAddress

////////////////////////////////////////////////////////////////////////////////
DgResAdd<DgQ2DICoord> 
DgBoundedIDGGS::addFromSeqNum (std::uint64_t sNum) const
{
   if (!validSize())
   {
      report("DgBoundedIDGGS::seqNumAddress() valid size required",
             DgBase::Fatal);
      return DgResAdd<DgQ2DICoord>();
   }

   if (!zeroBased()) sNum--;

   DgResAdd<DgQ2DICoord> tmp;
   std::uint64_t n = sNum;
   tmp.setRes(0);

   int r;
   for (r = 0; r < IDGGS().nRes(); r++)
   {
      tmp.setRes(r);

      if (n < (*grids_)[r]->size()) break;

      n -= (*grids_)[r]->size();
   }

   if (r == IDGGS().nRes()) return invalidAdd();

   tmp.setAddress((*grids_)[tmp.res()]->addFromSeqNum(n));

   return tmp;

} // DgResAdd<DgQ2DICoord> DgBoundedIDGGS::addFromSeqNum

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgOutRandPtsText.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutRandPtsText.h: DgOutRandPtsText class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGOUTRANDPTSTEXT_H
#define DGOUTRANDPTSTEXT_H

#include <cstdio>

#include "DgOutLocTextFile.h"

class DgDVec2D;
class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgOutRandPtsText : public DgOutLocTextFile {

   using DgOutLocFile::insert;

   public:

      DgOutRandPtsText (const DgRFBase& rfIn, const string& fileNameIn = "",
                   int precision = 7, DgReportLevel failLevel = DgBase::Fatal);

      virtual ~DgOutRandPtsText (void) { if (good()) close(); }

      virtual void close (void) { *this << "END" << endl; ofstream::close(); }

      virtual DgOutLocFile& insert (DgLocation& loc, const string* label = NULL);
      virtual DgOutLocFile& insert (DgLocVector& vec, const string* label = NULL, 
                                const DgLocation* cent = NULL);
      virtual DgOutLocFile& insert (DgPolygon& poly, const string* label = NULL, 
                                const DgLocation* cent = NULL);

   private:

      virtual DgOutLocFile& insert (const DgDVec2D& pt);

      virtual void setFormatStr(void)
      {
          ostringstream os;
          os << "%#." << getPrecision() << "LF, "
             << "%#." << getPrecision() << "LF\n";

          formatStr_ = os.str();
      }
};

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedRF2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedRF2D.h: DgBoundedRF2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBOUNDEDRF2D_H
#define DGBOUNDEDRF2D_H

#include <cstdint>

#include "DgBoundedRF.h"
#include "DgIVec2D.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
class DgBoundedRF2D : public DgBoundedRF<DgIVec2D, DgDVec2D, long double> {

   public:

      DgBoundedRF2D (const DgDiscRF<DgIVec2D, DgDVec2D, long double>& rf, 
                     const DgIVec2D& lowerLeft, const DgIVec2D& upperRight);
                    
      virtual DgIVec2D& incrementAddress (DgIVec2D& add) const;
      virtual DgIVec2D& decrementAddress (DgIVec2D& add) const;

      virtual bool validAddress (const DgIVec2D& add) const
          { return add.i() >= lowerLeft().i() && add.i() <= upperRight().i() &&
                   add.j() >= lowerLeft().j() && add.j() <= upperRight().j(); }

      const DgIVec2D& lowerLeft  (void) const { return lowerLeft_; }
      const DgIVec2D& upperRight (void) const { return upperRight_; }

      std::int64_t numI (void) const { return numI_; }
      std::int64_t numJ (void) const { return numJ_; }
      
      const DgIVec2D& invalidAdd (void) const 
                         { return discRF().undefAddress(); }

      const DgDiscRF<DgIVec2D, DgDVec2D, long double>& discRF (void) const 
               { return discRF_; }

      virtual std::uint64_t seqNumAddress (const DgIVec2D& add) const;

      virtual DgIVec2D addFromSeqNum (std::uint64_t sNum) const;

   private:

      const DgDiscRF<DgIVec2D, DgDVec2D, long double>& discRF_;
      
      DgIVec2D lowerLeft_;
      DgIVec2D upperRight_;
      std::int64_t numI_, numJ_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgPhysicalRF_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRF_template.h: DgPhysicalRF template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

template<class A, class C> void
DgPhysicalRF<A, C>::deleteContents (const DgLocation& loc, bool convert)
{
   DgLocation* pLoc = discRF().createLocation(loc, convert);
   const A* add = discRF().getAddress(*pLoc);

   if (!boundedRF().validAddress(*add))
   {
      report("DgPhysicalRF<A, C>::deleteContents() invalid address",
             DgBase::Fatal);
   }

   deleteAddContents(*add);

   delete pLoc;

} // void DgPhysicalRF<A, C>::deleteContents

////////////////////////////////////////////////////////////////////////////////
template<class A, class C> C*
DgPhysicalRF<A, C>::getContents (const DgLocation& loc, bool convert,
                                       bool allocate) const
{
   DgLocation* pLoc = discRF().createLocation(loc, convert);
   const A* add = discRF().getAddress(*pLoc);

   if (!boundedRF().validAddress(*add)) return (C*) 0;
/*
   {
      report("DgPhysicalRF<A, C>::getContents() invalid address",
             DgBase::Fatal);
   }
*/

   C* cont = getAddContents(*add, allocate);

   delete pLoc;

   return cont;

} // C* DgPhysicalRF<A, C>::getContents

////////////////////////////////////////////////////////////////////////////////
template<class A, class C> void
DgPhysicalRF<A, C>::replaceContents (const DgLocation& loc, C* cont, 
                                        bool convert)
{
   DgLocation* pLoc = discRF().createLocation(loc, convert);
   const A* add = discRF().getAddress(*pLoc);

   if (!boundedRF().validAddress(*add))
   {
      report("DgPhysicalRF<A, C>::replaceContents() invalid address",
             DgBase::Fatal);
   }

   replaceAddContents(*add, cont);

   delete pLoc;

} // void DgPhysicalRF<A, C>::setContents

////////////////////////////////////////////////////////////////////////////////
template<class A, class C> void
DgPhysicalRF<A, C>::setContents (const DgLocation& loc, const C& cont, 
                                    bool convert)
{
   DgLocation* pLoc = discRF().createLocation(loc, convert);
   const A* add = discRF().getAddress(*pLoc);

   if (!boundedRF().validAddress(*add))
   {
      report("DgPhysicalRF<A, C>::setContents() invalid address",
             DgBase::Fatal);
   }

   setAddContents(*add, cont);

   delete pLoc;

} // void DgPhysicalRF<A, C>::setContents

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgIDGGS4H.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS4H.cpp: DgIDGGS4H class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgContCartRF.h"
#include "DgDiscRF.h"
#include "DgHexC1Grid2D.h"
#include "DgHexC2Grid2D.h"
#include "DgIDGGS4H.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIDGGS4H::DgIDGGS4H (const DgIDGGS4H& rf) 
  : DgIDGGS (rf)
{
   report("DgIDGGS4H::operator=() not implemented yet", DgBase::Fatal);

} // DgIDGGS4H::DgIDGGS4H

////////////////////////////////////////////////////////////////////////////////
DgIDGGS4H::~DgIDGGS4H (void)
{
   for (unsigned long i = 0; i < grids().size(); i++) 
    delete (*grids_)[i]; 

   delete grids_;

} // DgIDGGS4H::~DgIDGGS4H

////////////////////////////////////////////////////////////////////////////////
DgIDGGS4H&
DgIDGGS4H::operator= (const DgIDGGS4H& rf)
{
   report("DgIDGGS4H::operator=() not implemented", DgBase::Fatal);

   return *this;

} // DgIDGGS4H& DgIDGGS4H::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4H::setAddParents (const DgResAdd<DgQ2DICoord>& add, 
                             DgLocVector& vec) const
{
   DgPolygon verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res()]->setVertices(*tmpLoc, verts);
   delete tmpLoc;

   // edge midpoints lie in parents

   DgLocVector midPts(verts.rf());
   for (int i = 0; i < verts.size(); i++)
   {
      DgDVec2D pt1 = *(grids()[add.res()]->backFrame().getAddress(verts[i]));

      DgDVec2D pt2 = *(grids()[add.res()]->backFrame().getAddress(
                                           verts[(i + 1) % verts.size()]));

      DgLocation* tmpLoc = 
         grids()[add.res()]->backFrame().makeLocation(
                                           DgDVec2D::midPoint(pt1, pt2));

      midPts.push_back(*tmpLoc);

      delete tmpLoc;
   }

   grids()[add.res() - 1]->convert(midPts);

   for (int i = 0; i < midPts.size(); i++)
   {
      // check if already present

      bool found = false;
      for (int j = 0; j < vec.size(); j++)
      {
         if (vec[j] == midPts[i])
         {
            found = true;
            break;
         }
      }

      if (!found) vec.push_back(midPts[i]);
   }

} // void DgIDGGS4H::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4H::setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   DgLocVector verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res() + 1]->convert(tmpLoc);
   vec.push_back(*tmpLoc);

   delete tmpLoc;

} // void DgIDGGS4H::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4H::setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   DgPolygon verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res()]->setVertices(*tmpLoc, verts);
   delete tmpLoc;

   // edge midpoints lie in children

   DgLocVector midPts(verts.rf());
   for (int i = 0; i < verts.size(); i++)
   {
      DgDVec2D pt1 = *(grids()[add.res()]->backFrame().getAddress(verts[i]));

      DgDVec2D pt2 = *(grids()[add.res()]->backFrame().getAddress(
                                           verts[(i + 1) % verts.size()]));
      DgLocation* tmpLoc = 
         grids()[add.res()]->backFrame().makeLocation(
                                              DgDVec2D::midPoint(pt1, pt2));

      midPts.push_back(*tmpLoc);

      delete tmpLoc;
   }

   grids()[add.res() + 1]->convert(midPts);

   for (int i = 0; i < midPts.size(); i++)
   {
      // check if already present

      bool found = false;
      for (int j = 0; j < vec.size(); j++)
      {
         if (vec[j] == midPts[i])
         {
            found = true;
            break;
         }
      }

      if (!found) vec.push_back(midPts[i]);
   }

} // void DgIDGGS4H::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4H::setAddAllChildren (const DgResAdd<DgQ2DICoord>& add, 
                                   DgLocVector& vec) const
{
   setAddInteriorChildren(add, vec);

   DgLocVector bndVec(vec.rf());
   setAddBoundaryChildren(add, bndVec);

   for (int i = 0; i < bndVec.size(); i++) vec.push_back(bndVec[i]);

} // void DgIDGGS4H::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgIcosaMap.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIcosaMap.h: DgIcosaMap class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGICOSAMAP_H
#define DGICOSAMAP_H

////////////////////////////////////////////////////////////////////////////////

#include "DgConstants.h"
#include "DgDVec2D.h"

////////////////////////////////////////////////////////////////////////////////
class DgIcosaTri {

   public:

      DgIcosaTri (bool mapped = false, int rot60 = 0, 
                   const DgDVec2D& offset = DgDVec2D(M_ZERO, M_ZERO)) 
         : rot60_ (rot60), offset_ (offset), mapped_ (mapped) { }

      static const DgDVec2D origin_;

      int rot60_;

      DgDVec2D offset_;
      bool mapped_;

      void translate (DgDVec2D* pt) const;
      void untranslate (DgDVec2D* pt, bool shiftOrigin = true) const;

   friend class DgIcosaMap;

};

////////////////////////////////////////////////////////////////////////////////
class DgIcosaMap {

   public:

      static DgIcosaMap defIcosaMap;
      //static DgIcosaTri defIcosaTri[20];

      DgIcosaMap (const DgIcosaTri icosaTri[20]);

      void translate (int nTri, DgDVec2D* pt) const;
      void untranslate (int nTri, DgDVec2D* pt, bool shiftOrigin = true) const;
      DgDVec2D maxOffset (void);

      DgIcosaTri icosaTri_[20];

};

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgParamList.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgParamList.cpp: DgParamList class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <string>
#include <algorithm>
#include <fstream>

#include "DgParamList.h"

////////////////////////////////////////////////////////////////////////////////
DgAssoc::~DgAssoc (void)
{
   // does nothing

} // DgAssoc::~DgAssoc

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgParamList::~DgParamList (void)
{
   clearList();

} // DgParamList::~DgParamList

////////////////////////////////////////////////////////////////////////////////
void
DgParamList::clearList (void)
{
   for (unsigned int i = 0; i < parameters.size(); i++)
   {
      delete parameters[i];
      parameters[i] = 0;
   }
   parameters.resize(0);

} // void DgParamList::clearList

////////////////////////////////////////////////////////////////////////////////
void
DgParamList::loadParams (const string& fileName)
{
   ifstream metaFile;
   metaFile.open(fileName.c_str(), ios::in);
   if (!metaFile.good())
   {
      report("DgParamList::loadParams() unable to open file " + fileName,
             DgBase::Fatal);
   }

   const int maxLine = 10000;
   char nextLine[maxLine];

   while (!metaFile.eof())
   {
      metaFile.getline(nextLine, maxLine);
        
      if (metaFile.eof()) break;

      if (strlen(nextLine) <= 1 || nextLine[0] == '#') continue;

      char* token = nextLine;
      while (isspace(*token)) token++;

      char* remainder = token;
      while (!isspace(*remainder)) remainder++;
      *remainder = '\0';

      remainder++;
      while (isspace(*remainder)) remainder++;

      setParam(token, remainder);
   }

   metaFile.close();

} // void DgParamList::loadParams

////////////////////////////////////////////////////////////////////////////////
void
DgParamList::setParam (const string& nameIn, const string& strValIn)
{
   if (toLower(strValIn) == string("invalid")) return;

   DgAssoc* existing = getParam(nameIn, false);
   if (!existing)
   {
      report(string("DgParamList::setParam() unknown parameter ") 
             + nameIn, DgBase::Fatal);
   }
   else // already exists
   {
      existing->setValStr(strValIn);
      existing->setIsDefault(false);
      existing->setIsUserSet(true);
      if (!existing->validate())
      {
         report(string("Invalid parameter data in parameter:\n") +
            existing->asString() + string("\n") +
            existing->validationErrMsg(), DgBase::Fatal);
      }
   }

} // void DgParamList::setParam

////////////////////////////////////////////////////////////////////////////////
void
DgParamList::setPresetParam (const string& nameIn, const string& strValIn)
{
   if (toLower(strValIn) == string("invalid")) return;

   DgAssoc* existing = getParam(nameIn, false);
   if (!existing)
   {
      report(string("DgParamList::setPresetParam() unknown parameter ") 
             + nameIn, DgBase::Fatal);
   }
   else // already exists
   {
      // only change value if it was not set explicitly by the user
      if (!existing->isUserSet())
      {
         existing->setValStr(strValIn);
         existing->setIsDefault(false);
         if (!existing->validate())
         {
            report(string("Invalid parameter data in parameter:\n") +
               existing->asString() + string("\n") +
               existing->validationErrMsg(), DgBase::Fatal);
         }
      }
   }

} // void DgParamList::setPresetParam

////////////////////////////////////////////////////////////////////////////////
void
DgParamList::insertParam (DgAssoc* param) // does not make a copy
{
   if (!param)
   {
      report("DgParamList::insertParam() null parameter", DgBase::Fatal);
   }

   DgAssoc* existing = getParam(param->name(), false);
   if (!existing)
   {
      parameters.push_back(param);
   }
   else // already exists
   {
      report(string("replacing parameter: ") + existing->asString()
        + string("\nwith parameter: ") + param->asString() +
        string("\n"), DgBase::Info);

      *existing = *param;
   }

} // void DgParamList::insertParam

////////////////////////////////////////////////////////////////////////////////
DgAssoc*
DgParamList::getParam (const string& nameIn, bool setToIsApplicable) const
{
   string lower = toLower(nameIn);

   for (unsigned int i = 0; i < parameters.size(); i++)
   {
      if (parameters[i]->name() == lower) 
      {
       if (setToIsApplicable)
          parameters[i]->setIsApplicable(true);
       return parameters[i];
      }
   }

   // if we're here we didn't find it
   return 0;

} // void DgParamList::getParam

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/pj_phi2.cpp<|end_filename|>
/* determine latitude angle phi-2 */
#include "proj4.h"
#include <cmath>

#define TOL 1.0e-10
#define N_ITER 15

	long double
pj_phi2(long double ts, long double e) {
	long double eccnth, Phi, con, dphi;
	int i;

	eccnth = .5 * e;
	Phi = projM_PI_2 - 2. * std::atan (ts);
	i = N_ITER;
	do {
		con = e * std::sin (Phi);
		dphi = projM_PI_2 - 2. * std::atan (ts * std::pow((1. - con) /
		   (1. + con), eccnth)) - Phi;
		Phi += dphi;
	} while ( std::fabs(dphi) > TOL && --i);
/*
	if (i <= 0)
		pj_errno = -18;
*/
	return Phi;
}


<|start_filename|>src/DgGeoSphRF.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgGeoSphRF.cpp: DgGeoSphRF class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgGeoSphRF.h"
#include "DgIDGG.h"
#include "DgConstants.h"
#include "DgPolygon.h"

// these are initialized here but will get set again when the datum is created
long double DgGeoSphRF::earthRadiusKM_ = DEFAULT_RADIUS_KM;
long double DgGeoSphRF::icosaEdgeRads_ = M_ATAN2;
long double DgGeoSphRF::icosaEdgeDegs_ = icosaEdgeRads_ * M_180_PI;
long double DgGeoSphRF::icosaEdgeKM_ = icosaEdgeRads_ * earthRadiusKM_;
long double DgGeoSphRF::totalAreaKM_ = 
                      4.0L * dgM_PI * earthRadiusKM_ * earthRadiusKM_;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgGeoSphRF::densify (DgPolygon& p, long double maxDist, bool rads)
{
   if (maxDist <= 0) return;

   const DgGeoSphRF* gs = dynamic_cast<const DgGeoSphRF*>(&p.rf());
   if (gs == 0) report("DgGeoSphRF::densify() with non-CCRF", DgBase::Fatal);

   if (!rads) maxDist *= dgM_PI_180;

   DgPolygon densVerts(*gs);

   vector<DgAddressBase*>& v0 = p.addressVec();
   vector<DgAddressBase*>& v1 = densVerts.addressVec();

   // for each edge
   for (unsigned long i = 0; i < v0.size(); i++)
   {
      DgGeoCoord p1 = dynamic_cast< DgAddress<DgGeoCoord>& >(*v0[i]).address();
      DgGeoCoord p2 = dynamic_cast< DgAddress<DgGeoCoord>& >(
                                          *v0[(i + 1) % v0.size()]).address();

      // add the first point
      v1.push_back(new DgAddress<DgGeoCoord>(p1));

      while (DgGeoCoord::gcDist(p1, p2) > maxDist)
      {
         DgGeoCoord p3 = travelGC(p1, maxDist, azimuth(p1, p2));

         v1.push_back(new DgAddress<DgGeoCoord>(p3));

         p1 = p3;
      }

      // p2 should get pushed next time
   }

   // now replace the original with the densified version

   p = densVerts;

} // void DgGeoSphRF::densify

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgGeoCoord 
DgGeoSphRF::midPoint (const DgGeoCoord& p1, const DgGeoCoord& p2)
/*
   Return midpoint of great circle connecting two points.

   Works by calling Lian Song's routine GCmidpoint.
*/
{
   GeoCoord pp1, pp2;
   pp1.lon = p1.lon();
   pp1.lat = p1.lat();
   pp2.lon = p2.lon();
   pp2.lat = p2.lat();

   GeoCoord ans = GCmidpoint(pp1, pp2);
   
   return DgGeoCoord(ans.lon, ans.lat);

} // DgGeoCoord DgGeoSphRF::midPoint

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
long double 
DgGeoSphRF::azimuth (const DgGeoCoord& p1, const DgGeoCoord& p2, 
                     bool returnRads)
/*
   Return azimuth from p1 to p2.

   Works by calling Lian Song's routine Azimuth.
*/
{
   GeoCoord pp1, pp2;
   pp1.lon = p1.lon();
   pp1.lat = p1.lat();
   pp2.lon = p2.lon();
   pp2.lat = p2.lat();

   long double ans = Azimuth(pp1, pp2);
   
   if (!returnRads) ans *= M_180_PI;
   return ans;

} // long double DgGeoSphRF::azimuth

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgGeoCoord 
DgGeoSphRF::travelGC (const DgGeoCoord& p0, long double distance, long double azimuth,
                      bool inputRads)
/*
   Return point that is distance from p0 along azimuth. 

   Works by calling Lian Song's routine Azimuth.
*/
{
   GeoCoord pp0;
   pp0.lon = p0.lon();
   pp0.lat = p0.lat();

   if (!inputRads)
   {
      distance *= dgM_PI_180;
      azimuth *= dgM_PI_180;
   }

   GeoCoord ans = GCdaz(pp0, distance, azimuth);
   
   return DgGeoCoord(ans.lon, ans.lat);

} // long double DgGeoSphRF::azimuth

////////////////////////////////////////////////////////////////////////////////
DgGeoSphDegRF::DgGeoSphDegRF (const DgGeoSphRF& geoRFin, const string& nameIn)
         : DgContCartRF (geoRFin.network(), nameIn), geoRF_ (geoRFin)
{
   new DgDegConverter(geoRFin, *this);
}



<|start_filename|>src/DgRadixString.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRadixString.h: DgRadixString class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGRADIXSTRING_H
#define DGRADIXSTRING_H

#include <iostream>

#include "DgBase.h"
#include "DgString.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgRadixString {

   public:

      static string digitInterleave (const DgRadixString& s1, 
                                     const DgRadixString& s2,
                                     bool combineDigits = true)
          {
             if (s1.base() != s2.base())
             {
                report("DgRadixString::digitInterleave(): "
                       "bases do not match", DgBase::Fatal);
             }

             if (s1.digits()[0] == '-' || s2.digits()[0] == '-')
             {
                report("DgRadixString::digitInterleave(): "
                       "negative value input", DgBase::Fatal);
             }

             string tmp1 = s1.digits();
             string tmp2 = s2.digits();

             int n1 = tmp1.length();
             int n2 = tmp2.length();

             // pad shorter one with 0's

             if (n2 < n1)
             {
                for (int i = 0; i < (n1 - n2); i++) tmp2 = "0" + tmp2;
             }
             else
             {
                for (int i = 0; i < (n2 - n1); i++) tmp1 = "0" + tmp1;
             }

             // now interleave

             string result;
             char c1[] = " ";
             char c2[] = " ";
             if (!combineDigits)
             {
                for (unsigned int i = 0; i < tmp1.length(); i++)
                {
                   c1[0] = tmp1[i];
                   c2[0] = tmp2[i];
    
                   result += string(c1) + string(c2);
                }
             }
             else
             {
                for (unsigned int i = 0; i < tmp1.length(); i++)
                {
                   c1[0] = tmp1[i];
                   c2[0] = tmp2[i];

                   int d1 = atoi(c1);
                   int d2 = atoi(c2);

                   result += dgg::util::to_string(d1 * s1.base() + d2);
                }
             } 

             return result;
          }

      DgRadixString (void) : base_ (10), digits_ ("") { }

      DgRadixString (const DgRadixString& obj)
               : base_ (obj.base()), digits_ (obj.digits()) { }

      DgRadixString (unsigned int baseIn, const string& digitsIn)
               : base_ (baseIn), digits_ (digitsIn) { }

      DgRadixString (unsigned int baseIn, int digitsIn, int padWidth = -1)
               : base_ (baseIn), digits_ ("") { convert(digitsIn, padWidth); }

      DgRadixString& operator= (const DgRadixString& obj)
               {
                  if (&obj != this)
                  {
                     base_ = obj.base();
                     digits_ = obj.digits();
                  }

                  return *this;

               } // DgRadixString::operator=

      bool operator== (const DgRadixString& obj) const
               {
                  return (base() == obj.base() && digits() == obj.digits());

               } // bool DgRadixString::operator==

      bool operator!= (const DgRadixString& obj) const
               {
                  return !operator==(obj);

               } // bool DgRadixString::operator!=

      // get methods

      unsigned int base (void) const { return base_; }

      const string& digits (void) const { return digits_; }

      // set methods

      void setBase (unsigned int baseIn) { base_ = baseIn; }

      void setDigits (const string& digitsIn) { digits_ = digitsIn; }

      // conversion methods

      void convert (int val, int padWidth = -1)
         // 
         // Algorithm from Knuth, Vol 2, with padding code by <NAME>
         //
         // padWidth of -1 indicates no padding
         //
         {
            int pval = abs(val);

            int nd = pval % base();
            setDigits(dgg::util::to_string(nd));

            pval = pval / base();
            while (pval > 0)
            {
               nd = pval % base();

               setDigits(dgg::util::to_string(nd) + digits());

               pval = pval / base();
            }

            // pad to specified width

            int nPad = padWidth - digits().length();
            for (int i = 0; i < nPad; i++) setDigits("0" + digits());

            // adjust if negative

            if (val < 0) setDigits("-" + digits());

         } // DgRadixString::convert()

   private:

      unsigned int base_;

      string digits_;

}; // class DgRadixString

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgRadixString& obj)
{
   return stream << "base: " << obj.base() << " val: " << obj.digits();

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/pj_tsfn.cpp<|end_filename|>
/* determine small t */
#include <cmath>
#include "proj4.h"
	long double
pj_tsfn(long double phi, long double sinphi, long double e) {
	sinphi *= e;
	return (std::tan (.5 * (projM_PI_2 - phi)) /
	   std::pow((1. - sinphi) / (1. + sinphi), .5 * e));
}


<|start_filename|>src/DgInShapefile.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgInShapefile.h: DgInShapefile class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGINSHAPEFILE_H
#define DGINSHAPEFILE_H

#include <string>
#include <fstream>
#include "shapefil.h"
#include "DgInLocFile.h"

using namespace std;

class DgLocList;
class DgLocVector;
class DgPolygon;
class DgLocation;
class DgCell;
class DgRFBase;
class DgGeoSphRF;

////////////////////////////////////////////////////////////////////////////////
class DgInShapefile : public DgInLocFile {

   public:

      DgInShapefile (const DgGeoSphRF& geoRFIn,
                     const string* fileNameIn = NULL, 
                     DgReportLevel failLevel = DgBase::Fatal);

      virtual bool open (const string* fileName = NULL,
                 DgReportLevel failLevel = DgBase::Fatal);

      virtual void close (void);

      virtual void rewind (void);

      int numEntities (void) { return numEntities_; }

      bool isEOF (void) { return isEOF_; }

      // pure virtual methods
      virtual DgInLocFile& extract (DgLocList&   list);
      virtual DgInLocFile& extract (DgLocVector& vec);
      virtual DgInLocFile& extract (DgPolygon&   poly);
      virtual DgInLocFile& extract (DgLocation&  loc);
      virtual DgInLocFile& extract (DgCell&      cell);

      const DgGeoSphRF& geoRF (void) const { return geoRF_; }

   protected:

      const DgGeoSphRF& geoRF_;

      virtual void getNextEntity (void);

      SHPHandle shpFile_;
      int numEntities_;
      int nextRecNum_;
      SHPObject* curShpObj_;
      int curRecNum_;
      int curPart_;
      int nextPart_;
      bool isEOF_;
};

inline DgInLocFile& operator>> (DgInShapefile& input, DgLocList& list)
              { return input.extract(list); }

inline DgInLocFile& operator>> (DgInShapefile& input, DgLocVector& vec)
              { return input.extract(vec); }

inline DgInLocFile& operator>> (DgInShapefile& input, DgPolygon& poly)
              { return input.extract(poly); }

inline DgInLocFile& operator>> (DgInShapefile& input, DgLocation& loc)
              { return input.extract(loc); }

inline DgInLocFile& operator>> (DgInShapefile& input, DgCell& cell)
              { return input.extract(cell); }

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgPhysicalRFS2D_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRFS2D_template.h: DgPhysicalRFS2D template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

template<class C>
DgPhysicalRFS2D<C>::DgPhysicalRFS2D (const DgBoundedRFS2D& rfIn, bool allocate)
   : DgPhysicalRF<DgResAdd<DgIVec2D>, C> (rfIn), boundedRFS2D_ (rfIn) 
{
   int nRes = rfIn.grids().size();

   grids_ = new vector<DgPhysicalRF2D<C>*>(nRes);

   for (int i = 0; i < nRes; i++)
   {
      (*grids_)[i] = new DgPhysicalRF2D<C>(*rfIn.grids()[i], allocate);
   }

   initAllCells();

} // DgPhysicalRFS2D<C>::DgPhysicalRFS2D

////////////////////////////////////////////////////////////////////////////////
template<class C> void
DgPhysicalRFS2D<C>::replaceAddContents (const DgResAdd<DgIVec2D>& add, C* cont)
{
   if (!boundedRFS2D().validAddress(add))
   {
      report("DgPhysicalRFS2D<C>::replaceAddContents() invalid address", 
      DgBase::Fatal);
   }

   (*grids_)[add.res()]->replaceAddContents(add.address(), cont);

} // void DgPhysicalRFS2D<C>::replaceAddContents

////////////////////////////////////////////////////////////////////////////////
template<class C> void
DgPhysicalRFS2D<C>::setAddContents (const DgResAdd<DgIVec2D>& add, 
                                    const C& cont)
{
   if (!boundedRFS2D().validAddress(add))
   {
      report("DgPhysicalRFS2D<C>::setAddContents() invalid address", 
      DgBase::Fatal);
   }

   (*grids_)[add.res()]->setAddContents(add.address(), cont);

} // void DgPhysicalRFS2D<C>::setAddContents

////////////////////////////////////////////////////////////////////////////////
template<class C> C*
DgPhysicalRFS2D<C>::getAddContents (const DgResAdd<DgIVec2D>& add, bool allocate) const
{
   if (!boundedRFS2D().validAddress(add))
   {
      report("DgPhysicalRFS2D<C>::getAddContents() invalid address", 
      DgBase::Fatal);
   }

   return (*grids_)[add.res()]->getAddContents(add.address(), allocate);

} // C* DgPhysicalRFS2D<C>::getAddContents

////////////////////////////////////////////////////////////////////////////////
template<class C> void
DgPhysicalRFS2D<C>::deleteAddContents (const DgResAdd<DgIVec2D>& add)
{
   if (!boundedRFS2D().validAddress(add))
   {
      report("DgPhysicalRFS2D<C>::deleteAddContents() invalid address",
             DgBase::Fatal);
   }

   (*grids_)[add.res()]->deleteAddContents(add.address());

} // void DgPhysicalRFS2D<C>::deleteAddContents

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgBoundedIDGG.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedIDGG.cpp: DgBoundedIDGG class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cstdint>

#include "DgBoundedIDGG.h"
#include "DgBoundedRF2D.h"
#include "DgBoundedHexC2RF2D.h"
#include "DgIDGG.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgBoundedIDGG::DgBoundedIDGG (const DgIDGG& IDGGin)
   : DgBoundedRF<DgQ2DICoord, DgGeoCoord, long double> (IDGGin, IDGGin.firstAdd(), 
          IDGGin.lastAdd(), IDGGin.undefAddress(), false), IDGG_ (IDGGin), 
          bnd2D_ (0)
{
   // create the surrogate boundedRF2D

   if (idgg().gridTopo() == "HEXAGON" && !idgg().isClassI())
   {
      bnd2D_ = new DgBoundedHexC2RF2D(idgg().grid2D(), DgIVec2D(0, 0), 
                                      DgIVec2D(idgg().maxI(), idgg().maxJ()));
   }
   else
   {
      bnd2D_ = new DgBoundedRF2D(idgg().grid2D(), DgIVec2D(0, 0), 
                                 DgIVec2D(idgg().maxI(), idgg().maxJ()));
   }

   // calculate the offsetPerQuad

   if (idgg().gridTopo() == "TRIANGLE")
   {
      offsetPerQuad_ = idgg().mag() * (idgg().maxJ() + 1);
   }
   else if (idgg().gridTopo() == "HEXAGON" && idgg().aperture() == 3)
   {
      if (!idgg().isClassI()) 
         offsetPerQuad_ = (idgg().mag() / 3) * idgg().mag();
      else 
         offsetPerQuad_ = idgg().mag() * idgg().mag();
   }
   else
   {
      offsetPerQuad_ = idgg().mag() * idgg().mag();
   }

   // calculate the total size

   size_ = 10 * offsetPerQuad();
   if (firstAdd().quadNum() == 0) size_ += 2;

   // validate the size

   std::uint64_t tmpSize = size();
   if (firstAdd().quadNum() == 0) tmpSize -= 2;
/*
cout << "mag: " << idgg().mag() << ", /3: " << idgg().mag() / 3 << ", size: " << size() << ", tmpSize: " << tmpSize << ", tmpSize / 10: " << tmpSize/10 << endl;
cout  << "quadNum: " << firstAdd().quadNum() << ", offsetPerQuad: " << offsetPerQuad() << endl;
*/
   if ((tmpSize / 10) != offsetPerQuad())
   {
       report("DgBoundedIDGG::DgBoundedIDGG() invalid size setting due to "
              "possible overflow", DgBase::Warning);
       validSize_ = false;
   }
   else validSize_ = true;

} // DgBoundedIDGG::DgBoundedIDGG

////////////////////////////////////////////////////////////////////////////////
bool
DgBoundedIDGG::validAddress (const DgQ2DICoord& add) const
{ 
   if (add == invalidAdd()) return false;

   if (add.quadNum() == 0 || add.quadNum() == 11)
   {
      if (firstAdd().quadNum() == 0)
      {
         if (add.coord() == DgIVec2D(0, 0)) return true;
         else return false; 
      }
      else
         return false;
   }
   else
   {
      return add.coord().i() >= 0 && add.coord().i() <= idgg().maxI() &&
             add.coord().j() >= 0 && add.coord().j() <= idgg().maxJ();

   }

} // DgBoundedIDGG::validAddress

////////////////////////////////////////////////////////////////////////////////
DgQ2DICoord&
DgBoundedIDGG::incrementAddress (DgQ2DICoord& add) const
{
   if (!validAddress(add)) return add = invalidAdd();
   else if (add == lastAdd() || add == endAdd()) return add = endAdd();

   if (add.quadNum() == 0) return add = DgQ2DICoord(1, DgIVec2D(0, 0));

   if (add.coord() == bnd2D().lastAdd())
      return add = DgQ2DICoord(add.quadNum() + 1, DgIVec2D(0, 0));
   else
   {
      DgIVec2D tmpCoord(add.coord());
      bnd2D().incrementAddress(tmpCoord);
      add.setCoord(tmpCoord);
   }

   return add;

} // DgQ2DICoord& DgBoundedIDGG::incrementAddress

////////////////////////////////////////////////////////////////////////////////
DgQ2DICoord&
DgBoundedIDGG::decrementAddress (DgQ2DICoord& add) const
{
   if (!validAddress(add) || add == firstAdd()) return add = invalidAdd();

   if (add.coord() == DgIVec2D(0, 0))
   {
      if (add.quadNum() == 1)
         return add = DgQ2DICoord(0, DgIVec2D(0, 0));

      return add = DgQ2DICoord(add.quadNum() - 1, 
                               DgIVec2D(idgg().maxI(), idgg().maxJ()));
   }
   
   DgIVec2D tmpCoord(add.coord());
   bnd2D().decrementAddress(tmpCoord);
   add.setCoord(tmpCoord);

   return add;

} // DgQ2DICoord& DgBoundedIDGG::decrementAddress

////////////////////////////////////////////////////////////////////////////////
std::uint64_t 
DgBoundedIDGG::seqNumAddress (const DgQ2DICoord& add) const
{
   std::uint64_t offset = 0;
   int q = add.quadNum();

   // get the quad offset

   if (q > 0)
   {
      if (firstAdd().quadNum() == 0) offset++;
      offset += (q - 1) * offsetPerQuad();
   }

   // now account for seqNum within the quad

   std::uint64_t sNum = offset + bnd2D().seqNumAddress(add.coord());

   if (!zeroBased()) 
    sNum++;

   return sNum;

} 

////////////////////////////////////////////////////////////////////////////////
DgQ2DICoord 
DgBoundedIDGG::addFromSeqNum (std::uint64_t sNum) const
{
   if (!zeroBased()) 
    sNum--;

   if (sNum >= size()) 
    return invalidAdd();

   if (sNum == 0) 
    return firstAdd();

   // adjust for quad 0 if applicable

   if (firstAdd().quadNum() == 0) 
    sNum--;

   // determine quad and adjust accordingly

   std::uint64_t q = sNum / offsetPerQuad() + 1; // note int division
   sNum -= (q - 1) * offsetPerQuad();
   
   return DgQ2DICoord((int) q, bnd2D().addFromSeqNum(sNum));
} 



<|start_filename|>src/DgIcosaProj.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIcosaProj.h: DgIcosaProj class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGICOSA_PROJ_H
#define DGICOSA_PROJ_H

#include "DgConverter.h"
#include "Dg2WayConverter.h"
#include "DgGeoSphRF.h"
#include "DgProjTriRF.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgIcosaProj : public Dg2WayConverter {

   protected:

      DgIcosaProj (const DgConverter<DgGeoCoord, long double, 
                            DgProjTriCoord, long double>& forward,
                   const DgConverter<DgProjTriCoord, long double, 
                            DgGeoCoord, long double>& inverse)
         : Dg2WayConverter (forward, inverse) {}
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#endif


<|start_filename|>src/DgRFBase.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRFBase.h: DgRFBase class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGRFBASE_H
#define DGRFBASE_H

#include <string>
#include <vector>
#include <iostream>
#include <cstdint>

#include "DgRFNetwork.h"
#include "DgLocBase.h"
#include "DgDVec2D.h"
#include "DgUtil.h"

using namespace std;

class DgConverterBase;
class DgLocation;
class DgLocVector;
class DgDistanceBase;
class DgAddressBase;

////////////////////////////////////////////////////////////////////////////////
class DgRFBase {

   public:

      virtual ~DgRFBase (void);

      int id (void) const { return id_; }

      string name (void) const { return name_; }

      bool isConnected (void) const { return connectTo_ && connectFrom_; }

      DgRFNetwork& network (void) const { return *network_; }

      ostream& traceToGround (ostream& stream = cout) const;

      const DgRFBase* connectTo   (void) const { return connectTo_; }
      const DgRFBase* connectFrom (void) const { return connectFrom_; }
      
      DgLocation* convert (DgLocation* loc) const; // converts in place

      DgLocVector& convert (DgLocVector& vec) const; // converts in place

      void convert (DgLocBase* loc) const // converts in place
                { loc->convertTo(*this); }

      virtual DgDistanceBase* distance (const DgLocation& loc1, 
                                        const DgLocation& loc2,
                                        bool convert = false) const = 0;

      DgLocation* createLocation (void) const; // creates 0 address

      virtual DgLocation* createLocation (const DgLocation& loc,
                                          bool convert = false) const = 0;

      void setName (const string& nameIn) { name_ = nameIn; }
      
      virtual bool operator== (const DgRFBase& frame) const
               { return (id() == frame.id() && network() == frame.network()); }
              
      virtual bool operator!= (const DgRFBase& frame) const
               { return !operator==(frame); }

      DgRFBase& operator= (const DgRFBase& frame);

      int precision (void) { return precision_; }

      void setPrecision (int precIn) { precision_ = precIn; setFormatStr(); }

      const char* formatStr (void) const { return formatStr_; }

      virtual const DgLocation& undefLoc (void) const { return *undefLoc_; }

      virtual void jumpRF (DgLocation* loc) = 0;

      // the following routines are "back-doors" included for speed;
      // use with care!

      virtual DgAddressBase* vecAddress (const DgDVec2D& v) const
                    { return 0; }

      virtual DgLocation* vecLocation (const DgDVec2D& v) const
                    { return 0; }

      virtual DgDVec2D getVecAddress (const DgAddressBase& add) const
                    { return DgDVec2D::undefDgDVec2D; }

      virtual DgDVec2D getVecLocation (const DgLocation& loc) const
                    { return DgDVec2D::undefDgDVec2D; }

   protected:

      DgRFBase (DgRFNetwork& networkIn, const string& nameIn)
         : network_ (&networkIn), name_ (nameIn), precision_ (6),
           connectTo_ (0), connectFrom_ (0), undefLoc_ (0)
           { id_ = networkIn.generateId(this); setFormatStr(); }

      DgRFBase (const DgRFBase& rf)
         : network_ (&rf.network()), precision_ (6),
           connectTo_ (0), connectFrom_ (0), undefLoc_ (0)
           { id_ = network_->generateId(this); setFormatStr(); }

      virtual DgLocation* buildLocation (DgAddressBase* addIn) const; 
                             // does not make copy

      virtual DgAddressBase* createAddress (void) const = 0;

      virtual DgAddressBase* createAddress 
                                 (const DgAddressBase& addIn) const = 0;

      virtual void copyAddress (const DgAddressBase& from, 
                                      DgAddressBase* to) const = 0;

      virtual bool equalAddress (const DgAddressBase& add1, 
                                 const DgAddressBase& add2) const = 0;

      void forceRF (DgLocBase* loc) { loc->rf_ = this; }

   private:
   
      void setFormatStr (void)
            { sprintf(formatStr_, "%%#.%dLF", precision()); }

      string toString        (const DgLocBase& lb) const;
      string toString        (const DgLocBase& lb, char delimiter) const;
      string toAddressString (const DgLocBase& lb) const;
      string toAddressString (const DgLocBase& lb, char delimiter) const;

      virtual string toString (const DgLocation&     loc)  const = 0;
      virtual string toString (const DgLocVector&    loc)  const = 0;
      virtual string toString (const DgDistanceBase& dist) const = 0;
      virtual long double toDouble (const DgDistanceBase& dist) const = 0;

      virtual std::uint64_t toInt (const DgDistanceBase& dist) const = 0;

      virtual string toAddressString (const DgLocation& loc)     const = 0;
      virtual string toAddressString (const DgLocVector& locVec) const = 0;

      virtual string toString (const DgLocation& loc, char delimiter) const = 0;
      virtual string toString (const DgLocVector& loc, char delimiter) 
                                                                      const = 0;
      virtual string toAddressString (const DgLocation& loc, char delimiter) 
                                                                      const = 0;
      virtual string toAddressString (const DgLocVector& locVec, char delimiter)
                                                                      const = 0;
      virtual const char* fromString (DgLocation& loc, const char* str,
                                      char delimiter) const = 0;

      int id_;

      char formatStr_[20];

      DgRFNetwork* network_;

      string name_;

      int precision_;

      DgRFBase* connectTo_;
      DgRFBase* connectFrom_;

   protected: 
      DgLocation* undefLoc_;

   private:

   friend class DgLocation;
   friend class DgLocVector;
   friend class DgDistanceBase;
   friend class DgConverterBase;
   friend class DgRFNetwork;
   friend class DgIdentityConverter;
};

////////////////////////////////////////////////////////////////////////////////
inline DgRFBase&
DgRFBase::operator= (const DgRFBase& frame)
{
   network_ = &frame.network(); 
   name_ = frame.name();
   id_ = frame.id(); 

   return *this;

} // inline DgRFBase& DgRFBase::operator=

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgRFBase& frame)
            { return stream << frame.name(); }

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBase.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBase.cpp: DgBase class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cstdlib>
#include <stdexcept>

#include "DgBase.h"

////////////////////////////////////////////////////////////////////////////////

const string DgBase::defaultName = "UNDEFNAME";
DgBase::DgReportLevel DgBase::minReportLevel_ = DgBase::Info;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void report (const string& message, DgBase::DgReportLevel level)
//
// Global report function accessible to all objects, even if they are not
// derived from DgBase. If level is Info, the message is printed to stdout
// followed by a newline and flush. If level is Warning, "WARNING" is
// printed to stderr followed by the message, newline, and flush. If level
// is Fatal, "FATAL ERROR" is printed to stderr, followed by the message,
// newline, and flush, and then the program is exited. 
//
////////////////////////////////////////////////////////////////////////////////
{
   if (level < DgBase::minReportLevel()) return;

   switch (level)
   {
      case DgBase::Debug0:
	 //cout << "DEBUG0: " << message << endl;
	 break;

      case DgBase::Debug1:
	 //cout << "DEBUG1: " << message << endl;
	 break;

      case DgBase::Info:

         //cout << message << endl;
         break;

      case DgBase::Warning:

         //cout.flush();  // in case stdout and stderr go to the same place
         //cerr << "WARNING: " << message << endl;
         break;

      case DgBase::Fatal:

         throw std::runtime_error("FATAL ERROR: " + message);
         // cout.flush();  // in case stdout and stderr go to the same place
         // cerr << "FATAL ERROR: " << message << endl;
         //exit(1);

      case DgBase::Silent:

         break;
   }

} // void report

////////////////////////////////////////////////////////////////////////////////
DgBase::~DgBase (void)
{ }

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool
DgBase::testArgEqual (int argc, int expected, const string& message,
                      DgReportLevel level)
{
   if ((argc - 1) != expected)
   {
      ::report(message, level);
      return false;
   }
   else 
   {
      return true;
   }

} // bool DgBase::testArgEqual

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool
DgBase::testArgEqual (int argc, char* argv[], int expected, 
                      const string& message)
{
   if ((argc - 1) != expected)
   {
      string mess(string("usage: ") + string(argv[0]));

      if ((message.c_str())[0] != ' ') mess += " ";

      ::report(mess + message, DgBase::Fatal);

      return false;
   }
   else 
   {
      return true;
   }

} // bool DgBase::testArgEqual

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool
DgBase::testArgMin (int argc, int minExpected, const string& message,
                      DgReportLevel level)
{
   if ((argc - 1) < minExpected)
   {
      ::report(message, level);
      return false;
   }
   else 
   {
      return true;
   }

} // bool DgBase::testArgMin

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool
DgBase::testArgMin (int argc, char* argv[], int minExpected, 
                     const string& message)
{
   if ((argc - 1) < minExpected)
   {
      string mess(string("usage: ") + string(argv[0]));

      if ((message.c_str())[0] != ' ') mess += " ";

      ::report(mess + message, DgBase::Fatal);

      return false;
   }
   else 
   {
      return true;
   }

} // bool DgBase::testArgMin

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgBase::DgBase (const string& instanceName)

   : instanceName_ (instanceName)

{
   debug("DgBase::constructor()");

} // DgBase::DgBase

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgBase::DgBase (const string* instanceName)
{
   debug("DgBase::constructor()");

   if (instanceName)
      instanceName_ = *instanceName;
   else
      instanceName_ = defaultName;

} // DgBase::DgBase

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgBase::report (const string& message, DgReportLevel level) const
//
// Call the global report function preceded with my instanceName.
//
////////////////////////////////////////////////////////////////////////////////
{
   ::report(string("[") + instanceName_ + string("] ") + message, level);

} // void DgBase::report

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgRFNetwork.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRFNetwork.h: DgRFNetwork class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGRFNETWORK_H
#define DGRFNETWORK_H

#include <vector>
#include <cstdint>

#include "DgUtil.h"

using namespace std;

class DgLocation;
class DgRFBase;
class DgConverterBase;

////////////////////////////////////////////////////////////////////////////////
class DgRFNetwork {

   public:

      DgRFNetwork (int chunkSize = 10) 
         : nextId_ (0), chunkSize_ (chunkSize) { reserve(chunkSize_); }

      DgRFNetwork (const DgRFNetwork& net) { operator=(net); }

     ~DgRFNetwork (void);

      std::uint64_t size (void) const { return frames_.size(); }

      bool existsConverter (const DgRFBase& fromFrame,
                            const DgRFBase& toFrame) const;

      const DgConverterBase* getConverter (const DgLocation& fromLoc, 
                                       const DgRFBase& toFrame) const;

      const DgConverterBase* getConverter (const DgRFBase& fromFrame,
                                       const DgRFBase& toFrame) const;

      void update (void);

      DgRFNetwork& operator= (const DgRFNetwork& net) 
            { chunkSize_ = net.chunkSize_; return *this; }

      bool operator== (const DgRFNetwork& net) const
                           { return (this == &net); }

      bool operator!= (const DgRFNetwork& net) const
                           { return (this != &net); }

      // memory management methods

      size_t capacity (void) const { return frames_.capacity(); }
      void reserve (const size_t& capacity);

      int chunkSize (void) const { return chunkSize_; }
      void setChunkSize (int chunkSize) { chunkSize_ = chunkSize; }

   private:

      int nextId_;

      int chunkSize_;

      vector< DgRFBase* > frames_;

      vector< vector<DgConverterBase*> > matrix_;
      
      int generateId (DgRFBase* frame);

   friend class DgConverterBase;
   friend class DgRFBase;
   friend class DgSeriesConverter;
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgInShapefileAtt.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgInShapefileAtt.h: DgInShapefileAtt class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGINSHAPEFILEATT_H
#define DGINSHAPEFILEATT_H

#include <string>
#include <set>
#include "shapefil.h"
#include "DgInShapefile.h"

using namespace std;

class DgLocList;
class DgLocVector;
class DgPolygon;
class DgLocation;
class DgCell;
class DgRFBase;

////////////////////////////////////////////////////////////////////////////////
class DgDBFfield {

   public:

      DgDBFfield (const string& fieldNameIn, DBFFieldType typeIn,
                 int fieldNumIn, int widthIn, int precisionIn)
         : fieldName_(fieldNameIn), type_(typeIn), fieldNum_(fieldNumIn),
           width_(widthIn), precision_(precisionIn)
      { }

      const string& fieldName (void) const { return fieldName_; }
      DBFFieldType  type      (void) const { return type_; } 
      int           fieldNum  (void) const { return fieldNum_; }
      int           width     (void) const { return width_; }
      int           precision (void) const { return precision_; }

      friend bool operator== (const DgDBFfield& f1, const DgDBFfield& f2);
      friend bool operator!= (const DgDBFfield& f1, const DgDBFfield& f2);
      friend bool operator<  (const DgDBFfield& f1, const DgDBFfield& f2);
      friend bool operator<= (const DgDBFfield& f1, const DgDBFfield& f2);
      friend bool operator>  (const DgDBFfield& f1, const DgDBFfield& f2);
      friend bool operator>= (const DgDBFfield& f1, const DgDBFfield& f2);

      friend ostream& operator<< (ostream& stream, const DgDBFfield& pt);

   protected:

      string fieldName_;
      DBFFieldType type_;
      int fieldNum_;
      int width_;
      int precision_;
};

////////////////////////////////////////////////////////////////////////////////
class DgInShapefileAtt : public DgInShapefile {

   public:

      DgInShapefileAtt (const DgGeoSphRF& geoRFIn,
                     const string* fileNameIn = NULL, 
                     DgReportLevel failLevel = DgBase::Fatal);

      virtual bool open (const string* fileName = NULL,
                 DgReportLevel failLevel = DgBase::Fatal);

      virtual void close (void);

      const set<DgDBFfield>& fields (void) const { return fields_; }

      int numFields (void) const { return numFields_; }

      const set<DgDBFfield>& curObjFields (void) const 
                                             { return curObjFields_; }

   protected:

      virtual void getNextEntity (void);

      DBFHandle dbfFile_;
      int numFields_;
      set<DgDBFfield> fields_;
      set<DgDBFfield> curObjFields_; // non-null fields in the curShpObj_
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline bool
operator== (const DgDBFfield& f1, const DgDBFfield& f2)
{
   return (f1.fieldName().compare(f2.fieldName()) == 0);

} // bool operator==

////////////////////////////////////////////////////////////////////////////////
inline bool
operator!= (const DgDBFfield& f1, const DgDBFfield& f2)
{
   return (f1.fieldName().compare(f2.fieldName()) != 0);

} // bool operator!=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator> (const DgDBFfield& f1, const DgDBFfield& f2)
{
   return (f1.fieldName().compare(f2.fieldName()) > 0);

} // bool operator>

////////////////////////////////////////////////////////////////////////////////
inline bool
operator>= (const DgDBFfield& f1, const DgDBFfield& f2)
{
   return (f1.fieldName().compare(f2.fieldName()) >= 0);

} // bool operator>=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator< (const DgDBFfield& f1, const DgDBFfield& f2)
{
   return (f1.fieldName().compare(f2.fieldName()) < 0);

} // bool operator<

////////////////////////////////////////////////////////////////////////////////
inline bool
operator<= (const DgDBFfield& f1, const DgDBFfield& f2)
{
   return (f1.fieldName().compare(f2.fieldName()) <= 0);

} // bool operator<=

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgDBFfield& f)
{
   stream << "field: " << f.fieldName();

   char type;
   switch (f.type())
   {
      case FTString: type = 'C'; break;
      case FTInteger: type = 'I'; break;
      case FTDouble: type = 'D'; break;
      case FTLogical: type = 'B'; break;
      case FTInvalid: type = 'X'; break;
      default: type = 'X'; break;
   }
   return stream << " type: " << type << " #" << f.fieldNum() 
                 << " (" << f.width() << "" << f.precision() << ")";

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgPhysicalRFBase_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRFBase_template.h: DgPhysicalRFBase template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

template<class C>
DgPhysicalRFBase<C>::~DgPhysicalRFBase (void)
{
   // virtual destructor

} // DgPhysicalRFBase<C>::~DgPhysicalRFBase<C>

////////////////////////////////////////////////////////////////////////////////
template<class C> void
DgPhysicalRFBase<C>::initAllCells (void)
{
   for (DgLocation loc = boundedRFBase().first(); loc != boundedRFBase().end();
           boundedRFBase().incrementLocation(loc))
   {
      C* c = getContents(loc, false, true);
      if (c) initCell(c, loc);
   }

} // void DgPhysicalRFBase<C>::initAllCells

////////////////////////////////////////////////////////////////////////////////
template<class C> ostream& operator<< (ostream& stream,
                                       const DgPhysicalRFBase<C>& rfIn)
{ 
   return stream << "Phys-" << rfIn.boundedRFBase(); 

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////



<|start_filename|>src/DgSeriesConverter.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSeriesConverter.h: DgSeriesConverter class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSERIESCONVERTER_H
#define DGSERIESCONVERTER_H

#include <iostream>

#include "DgConverterBase.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgSeriesConverter : public DgConverterBase {

   public:

      DgSeriesConverter (const vector<const DgConverterBase*>& series,
                         bool userGenerated = false);
                         
      DgSeriesConverter (const DgRFBase& fromFrame, 
                         const DgRFBase& toFrame,
                         bool userGenerated = false);

      DgSeriesConverter (const DgSeriesConverter& con) 
         : DgConverterBase (con) { operator=(con); }

      virtual ~DgSeriesConverter (void);
      
      int size (void) const { return series_.size(); }

      const DgConverterBase& converter (int ndx) const;

      DgSeriesConverter& operator= (const DgSeriesConverter& con)
         { copy(con.series_.begin(), con.series_.end(), series_.begin()); 
           return *this; }
   
   private:
   
      vector<const DgConverterBase*> series_;

      virtual DgAddressBase* createConvertedAddress
                              (const DgAddressBase& addIn) const;

};

////////////////////////////////////////////////////////////////////////////////
ostream& operator<< (ostream& stream, const DgSeriesConverter& con);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgPhysicalRF2D_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRF2D_template.h: DgPhysicalRF2D template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgBoundedRF2D.h"

////////////////////////////////////////////////////////////////////////////////
template<class C>
DgPhysicalRF2D<C>::DgPhysicalRF2D (const DgBoundedRF2D& rfIn, bool allocate)
   : DgPhysicalRF<DgIVec2D, C> (rfIn), boundedRF2D_ (rfIn) 
{
   matrix_ = new (C (**[boundedRF2D().numI()]));
   for (int i = 0; i < boundedRF2D().numI(); i++)
   {
      matrix_[i] = new (C (*[boundedRF2D().numJ()]));

      if (allocate)
      {
         for (int j = 0; j < boundedRF2D().numJ(); j++) matrix_[i][j] = new C();
      }
      else
      {
         for (int j = 0; j < boundedRF2D().numJ(); j++) matrix_[i][j] = 0;
      }
   }

   initAllCells();

} // DgPhysicalRF2D<C>::DgPhysicalRF2D

////////////////////////////////////////////////////////////////////////////////
template<class C> void
DgPhysicalRF2D<C>::replaceAddContents (const DgIVec2D& add, C* cont)
{
   if (!boundedRF2D().validAddress(add))
   {
      report("DgPhysicalRF2D<C>::replaceAddContents() invalid address", 
      DgBase::Fatal);
   }

   DgIVec2D tmp = add - boundedRF2D().lowerLeft();
   deleteAddContents(tmp);
   matrix_[tmp.i()][tmp.j()] = cont;

} // void DgPhysicalRF2D<C>::replaceAddContents

////////////////////////////////////////////////////////////////////////////////
template<class C> void
DgPhysicalRF2D<C>::setAddContents (const DgIVec2D& add, const C& cont)
{
   if (!boundedRF2D().validAddress(add))
   {
      report("DgPhysicalRF2D<C>::setAddContents() invalid address", 
      DgBase::Fatal);
   }

   DgIVec2D tmp = add - boundedRF2D().lowerLeft();
   if (!matrix_[tmp.i()][tmp.j()]) 
   {
      matrix_[tmp.i()][tmp.j()] = new C();

      DgLocation* tmpLoc = discRF().makeLocation(add);
      initCell(matrix_[tmp.i()][tmp.j()], *tmpLoc);
      delete tmpLoc;
   }
   *matrix_[tmp.i()][tmp.j()] = cont;

} // void DgPhysicalRF2D<C>::setAddContents

////////////////////////////////////////////////////////////////////////////////
template<class C> C*
DgPhysicalRF2D<C>::getAddContents (const DgIVec2D& add, bool allocate) const
{
   if (!boundedRF2D().validAddress(add))
   {
      report("DgPhysicalRF2D<C>::getAddContents() invalid address", 
      DgBase::Fatal);
   }

   DgIVec2D tmp = add - boundedRF2D().lowerLeft();
   if (matrix_[tmp.i()][tmp.j()] == 0 && allocate) 
   {
      matrix_[tmp.i()][tmp.j()] = new C();
      DgLocation* tmpLoc = discRF().makeLocation(add);
      const_cast<DgPhysicalRF2D<C>*>(this)->
            initCell(matrix_[tmp.i()][tmp.j()], *tmpLoc);
      delete tmpLoc;
   }

   return matrix_[tmp.i()][tmp.j()];

} // C* DgPhysicalRF2D<C>::getAddContents

////////////////////////////////////////////////////////////////////////////////
template<class C> void
DgPhysicalRF2D<C>::deleteAddContents (const DgIVec2D& add)
{
   if (!boundedRF2D().validAddress(add))
   {
      report("DgPhysicalRF2D<C>::deleteAddContents() invalid address",
             DgBase::Fatal);
   }

   DgIVec2D tmp = add - boundedRF2D().lowerLeft();
   delete matrix_[tmp.i()][tmp.j()];

} // void DgPhysicalRF2D<C>::deleteAddContents

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDiscRFS_template.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDiscRFS_template.h: DgDiscRFS template class definition.
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgRF.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRFS<A, B, DB>::setAddNeighbors (const DgResAdd<A>& add, 
                                            DgLocVector& vec) const
{
   grids()[add.res()]->convert(vec);
   grids()[add.res()]->setAddNeighbors(add.address(), vec);
   this->convert(vec);

} // void DgDiscRFS<A, B, DB>::setAddNeighbors

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRFS<A, B, DB>::setParents (int res, const DgLocation& loc, 
                                                DgLocVector& vec) const
{
   vec.clearAddress(); 
   this->convert(vec);

   if (res > 0 && res < nRes())
   {
      DgLocation tmpLoc(loc);
      grids()[res]->convert(&tmpLoc);
      this->convert(&tmpLoc);
      setAddParents(*(this->getAddress(tmpLoc)), vec);
   }

} // void DgDiscRFS::setParents

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRFS<A, B, DB>::setInteriorChildren (int res, const DgLocation& loc, 
                                   DgLocVector& vec) const
{
   vec.clearAddress(); 
   this->convert(vec);

   if (res >= 0 && res < (nRes() - 1))
   {
      DgLocation tmpLoc(loc);
      grids()[res]->convert(&tmpLoc);
      this->convert(&tmpLoc);
      setAddInteriorChildren(*(this->getAddress(tmpLoc)), vec);
   }

} // void DgDiscRFS::setInteriorChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRFS<A, B, DB>::setBoundaryChildren (int res, const DgLocation& loc, 
                                   DgLocVector& vec) const
{
   vec.clearAddress(); 
   this->convert(vec); 
   if (res >= 0 && res < (nRes() - 1))
   {
      DgLocation tmpLoc(loc);
      grids()[res]->convert(&tmpLoc);
      this->convert(&tmpLoc);
      setAddBoundaryChildren(*(this->getAddress(tmpLoc)), vec);
   }

} // void DgDiscRFS::setBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> void
DgDiscRFS<A, B, DB>::setAllChildren (int res, const DgLocation& loc, 
                              DgLocVector& vec) const
{
   vec.clearAddress(); 
   this->convert(vec);

   if (res >= 0 && res < (nRes() - 1))
   {
      DgLocation tmpLoc(loc);
      grids()[res]->convert(&tmpLoc);
      this->convert(&tmpLoc);
      setAddAllChildren(*(this->getAddress(tmpLoc)), vec);
   }

} // void DgDiscRFS::setAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> const char*
DgDiscRFS<A, B, DB>::str2add (DgResAdd<A>* add, const char* str,
                              char delimiter) const
{
   if (!add) add = new DgResAdd<A>();

   char delimStr[2];
   delimStr[0] = delimiter;
   delimStr[1] = '\0';

   char* tmpStr = new char[strlen(str) + 1];
   strcpy(tmpStr, str);

   char* tok;

   // get the resolution

   tok = strtok(tmpStr, delimStr);
   int res;
   if (sscanf(tok, "%d", &res) != 1)
   {
      ::report("DgDiscRFS<A, B, DB>::str2add() invalid res string " +
               string(tok), DgBase::Fatal);
   }

   // now get the address

   const char* tmp = &(str[strlen(tok) + 1]);
   DgLocation tloc(*grids()[res]);
   tmp = tloc.fromString(tmp, delimiter);
   const A& subAdd = *grids()[res]->getAddress(tloc);
   *add = DgResAdd<A>(subAdd, res);

   return tmp;

} // const char* DgDiscRFS::str2add

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgOutputStream.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutputStream.h: DgOutputStream class definition
//
//   This class provides wrappers around some basic output stream functionality
//   to increase ease of use. 
//
// Version 6.2 - <NAME>, 9/10/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGOUTPUTSTREAM_H
#define DGOUTPUTSTREAM_H

#include <string>
#include <fstream>

using namespace std;

#include "DgBase.h"

////////////////////////////////////////////////////////////////////////////////
class DgOutputStream : public ofstream, public DgBase {

   public:

      DgOutputStream (void) : DgBase ("DgOutputStream") {}

      DgOutputStream (const string& fileName,
                      const string& suffix    = string(""), 
                      DgReportLevel failLevel = DgBase::Fatal);

     ~DgOutputStream (void) { close(); }

      bool open (string fileName, DgReportLevel failLevel = DgBase::Fatal);

      virtual void close (void) { ofstream::close(); }

      void setSuffix (const string& suffix) { suffix_ = suffix; }

      const string& fileName (void) { return fileName_; }
      const string& suffix   (void) { return suffix_; }

   protected:

      string fileName_;
      string suffix_;
};

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgSqrD4Grid2DS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSqrD4Grid2DS.h: DgSqrD4Grid2DS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSQRD4GRID2DS_H 
#define DGSQRD4GRID2DS_H 

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgDiscRFS2D.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgSqrD4Grid2DS : public DgDiscRFS2D {

   public:

      DgSqrD4Grid2DS (DgRFNetwork& networkIn, 
                 const DgRF<DgDVec2D, long double>& backFrameIn,
                 int nRes = 1, unsigned int apertureIn = 4, 
                 bool isCongruentIn = true, bool isAlignedIn = false,
                 const string& nameIn = "4S4");

      DgSqrD4Grid2DS (const DgSqrD4Grid2DS& rf);

     ~DgSqrD4Grid2DS (void);

      DgSqrD4Grid2DS& operator= (const DgSqrD4Grid2DS& rf);

      int radix (void) const { return radix_; }

   protected:

      int radix_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgIVec2D>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgIVec2D>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIVec2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIVec2D.h: DgIVec2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIVEC2D_H
#define DGIVEC2D_H

#include <cmath>
#include <string>
#include <cstdint>

#include "DgUtil.h"
#include "DgConstants.h"
#include "DgDVec2D.h"

////////////////////////////////////////////////////////////////////////////////
class DgIVec2D {

   public:

      static DgIVec2D midPoint (const DgIVec2D& pt1, const DgIVec2D& pt2)
                       { return pt1 * 0.5L + pt2 * 0.5L; }

      static DgIVec2D fracPoint (const DgIVec2D& pt1, const DgIVec2D& pt2, 
                                long double fraction)
                       { return pt2 * fraction + pt1 * (1 - fraction); }

      static const DgIVec2D& undefDgIVec2D;

      DgIVec2D (std::int64_t i = 0, std::int64_t j = 0) 
       : i_(i), j_(j)
      {}

      DgIVec2D (const DgIVec2D& pt) 
       : i_ (pt.i_), j_ (pt.j_) 
      {}

      DgIVec2D (const DgDVec2D&  pt) 
       : i_ (dgg::util::lrint(pt.x())),  
         j_ (dgg::util::lrint(pt.y())) 
      {}

      void setI (std::int64_t i) { i_ = i; }
      void setJ (std::int64_t j) { j_ = j; }

      long double distance (const DgIVec2D& pt) const
              { return (pt - *this).magnitude(); }

      std::int64_t i (void) const { return i_; }
      std::int64_t j (void) const { return j_; }
      
      long double magnitude (void) const 
              { return sqrt((long double) (i_ * i_ + j_ * j_)); }

      DgIVec2D diffVec (const DgIVec2D& pt0) const
                          { return DgIVec2D(*this - pt0); }

      DgIVec2D absDiffVec (const DgIVec2D& pt0) const
                          { return DgIVec2D(abs(i_ - pt0.i()),
                                            abs(j_ - pt0.j())); }

      const char* fromString (const char* str, char delimiter);

      inline DgIVec2D& scale (long double xScaleFactor, long double yScaleFactor);
      inline DgIVec2D& rotate (long double degrees);

      //inline operator XPoint   (void) const;
      inline operator string (void) const;
      inline operator DgDVec2D  (void) const;

      inline DgIVec2D& operator=  (const DgIVec2D& pt);
      inline DgIVec2D& operator+= (const DgIVec2D& pt);
      inline DgIVec2D& operator-= (const DgIVec2D& pt);

      inline DgIVec2D& operator*= (long double scaleFactor);

      friend DgIVec2D operator*  (const DgIVec2D& pt, long double scaleFactor);
      friend DgIVec2D operator*  (long double scaleFactor, const DgIVec2D& pt);
      friend DgIVec2D operator%  (const DgIVec2D& pt, int modulo);
      friend DgIVec2D operator+  (const DgIVec2D& pt1, const DgIVec2D& pt2);
      friend DgIVec2D operator-  (const DgIVec2D& pt1, const DgIVec2D& pt2);

      friend bool operator== (const DgIVec2D& pt1, const DgIVec2D& pt2);
      friend bool operator!= (const DgIVec2D& pt1, const DgIVec2D& pt2);
      friend bool operator<  (const DgIVec2D& pt1, const DgIVec2D& pt2);
      friend bool operator<= (const DgIVec2D& pt1, const DgIVec2D& pt2);
      friend bool operator>  (const DgIVec2D& pt1, const DgIVec2D& pt2);
      friend bool operator>= (const DgIVec2D& pt1, const DgIVec2D& pt2);

      friend ostream& operator<< (ostream& stream, const DgIVec2D& pt);

   private:

      std::int64_t i_;
      std::int64_t j_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D&
DgIVec2D::scale (long double xScaleFactor, long double yScaleFactor)
//
// Scale me by xScaleFactor in the x direction and yScaleFactor in the y
// direction.
//
////////////////////////////////////////////////////////////////////////////////
{
   i_ = (std::int64_t) dgg::util::lrint(i_ * xScaleFactor);
   j_ = (std::int64_t) dgg::util::lrint(j_ * yScaleFactor);

   return *this;

} // void DgIVec2D::scale

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D&
DgIVec2D::rotate (long double degrees)
//
// Rotate me about the origin degrees degrees in a counter-clockwise
// direction.
//
////////////////////////////////////////////////////////////////////////////////
{
   long double rotAng = degrees * dgM_PI_180;
   long double cosAng = cos(rotAng);
   long double sinAng = sin(rotAng);
   std::int64_t i = i_;
   std::int64_t j = j_;

   i_ = (std::int64_t) dgg::util::lrint(i * cosAng - j * sinAng);
   j_ = (std::int64_t) dgg::util::lrint(i * sinAng + j * cosAng);

   return *this;

} // void DgIVec2D::rotate

/*
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D::operator XPoint (void) const
//
// XPoint conversion function. Note that the values may be truncated.
//
////////////////////////////////////////////////////////////////////////////////
{
   XPoint Xpt;

   Xpt.x = (short) i_;
   Xpt.y = (short) j_;

   return Xpt;

} // DgIVec2D::operator XPoint
*/

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D::operator DgDVec2D (void) const
//
// DgDVec2D conversion function. 
//
////////////////////////////////////////////////////////////////////////////////
{
   return DgDVec2D((long double) i_, (long double) j_);

} // DgIVec2D::operator DgDVec2D

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D::operator string (void) const
{
   return "(" + dgg::util::to_string(i_) + ", " + dgg::util::to_string(j_) + ")";

} // DgIVec2D::operator string

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D&
DgIVec2D::operator= (const DgIVec2D& pt)
{
   if (&pt != this)
   {
      i_ = pt.i_;
      j_ = pt.j_;
   }
   return *this;

} // DgIVec2D& DgIVec2D::operator=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D&
DgIVec2D::operator*= (long double scaleFactor)
{
   scale(scaleFactor, scaleFactor);

   return *this;

} // DgIVec2D& DgIVec2D::operator*=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D&
DgIVec2D::operator+= (const DgIVec2D& pt)
{
   i_ += pt.i_;
   j_ += pt.j_;

   return *this;

} // DgIVec2D& DgIVec2D::operator+=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D&
DgIVec2D::operator-= (const DgIVec2D& pt)
{
   i_ -= pt.i_;
   j_ -= pt.j_;

   return *this;

} // DgIVec2D& DgIVec2D::operator-=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D
operator* (const DgIVec2D& pt, long double scaleFactor)
{
   DgIVec2D result(pt);
   result.scale(scaleFactor, scaleFactor);

   return result;

} // bool operator*

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D
operator* (long double scaleFactor, const DgIVec2D& pt)
{
   DgIVec2D result(pt);
   result.scale(scaleFactor, scaleFactor);

   return result;

} // bool operator*

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D
operator% (const DgIVec2D& pt, int modulo)
{
   return DgIVec2D(pt.i() % modulo, pt.j() % modulo);

} // bool operator%

////////////////////////////////////////////////////////////////////////////////
inline bool
operator== (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   return (pt1.i_ == pt2.i_ && pt1.j_ == pt2.j_);

} // bool operator==

////////////////////////////////////////////////////////////////////////////////
inline bool
operator!= (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   return !operator==(pt1, pt2);

} // bool operator!=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator> (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   if (pt1.i_ != pt2.i_)
      return (pt1.i_ > pt2.i_);
   else // i's are equal
      return (pt1.j_ > pt2.j_);

} // bool operator>

////////////////////////////////////////////////////////////////////////////////
inline bool
operator>= (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   return (pt1 > pt2 || pt1 == pt2);

} // bool operator>=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator< (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   if (pt1.i_ != pt2.i_)
      return (pt1.i_ < pt2.i_);
   else // i's are equal
      return (pt1.j_ < pt2.j_);

} // bool operator<

////////////////////////////////////////////////////////////////////////////////
inline bool
operator<= (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   return (pt1 < pt2 || pt1 == pt2);

} // bool operator<=

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D
operator+ (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   DgIVec2D result(pt1);
   result += pt2;

   return result;

} // bool operator+

////////////////////////////////////////////////////////////////////////////////
inline DgIVec2D
operator- (const DgIVec2D& pt1, const DgIVec2D& pt2)
{
   DgIVec2D result(pt1);
   result -= pt2;

   return result;

} // bool operator-

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgIVec2D& pt)
{
   return stream << string(pt);

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgConstants.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgConstants.h: DgConstants class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGCONSTANTS_H 
#define DGCONSTANTS_H

/* precise 12 digits after dec pt */
#define M_EPSILON   0.00000000000050000000000000000000000000000L
#define M_ZERO      0.00000000000000000000000000000000000000000L
#define M_ONE       1.00000000000000000000000000000000000000000L
#define M_HALF      0.50000000000000000000000000000000000000000L
#define M_2PI       6.28318530717958647692528676655900576839433L
#define M_SQRT3     1.7320508075688772935274463415058723669428L
#define M_1_SQRT3   0.5773502691896257645091487805019574556476L
#define M_SQRT3_2   0.8660254037844386467637231707529361834714L
#define M_SQRT5     2.2360679774997896964091736687312762354406L
#define M_SQRT8     2.8284271247461900976033774484193961571393L
#define M_SQRT10    3.16227766016837933199889354443271853371955L
#define M_SQRT15    3.8729833462074168851792653997823996108329L
#define M_PHI       1.618033988749894848204586834365638117720309L
#define M_SIN60     M_SQRT3_2
#define M_COS60     0.50000000000000000000000000000000000000000L
#define M_SIN30     M_COS60
#define M_COS30     M_SIN60
#define M_ATAN2     1.1071487177940905030170654601785370400700476L
#define M_ATAN2_2   0.5535743588970452515085327300892685200350238L
// atan(1/2)
#define M_ATAN_HALF 0.46364760900080611621425623146121440202853705L
#define M_PI_180    0.0174532925199432957692369076848861271111L
#define M_180_PI    57.29577951308232087679815481410517033240547L

#define dgM_PI_180   0.017453292519943295769236907684886L
#define dgM_PI_4     0.785398163397448309615660845819875721L
#define dgM_PI_2     1.570796326794896619231321691639751442L
#define dgM_PI       3.141592653589793238462643383279502884L
#define dgTWOPI      6.28318530717958647692528676655900576L

// some spherical earth datum radii
#define WGS84_MEAN_RADIUS_KM      6371.0087714L
#define WGS84_EQUATOR_RADIUS_KM   6378.137L
#define WGS84_AUTHALIC_RADIUS_KM  6371.007180918475L
#define DEFAULT_RADIUS_KM         WGS84_AUTHALIC_RADIUS_KM

// misc

#define DEFAULT_PRECISION  7

#endif


<|start_filename|>src/util.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// util.h: util class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef __DGG_UTIL_HPP
 #define __DGG_UTIL_HPP

#include <string>
#include <vector>
#include <cstring>

namespace dgg { namespace util {

void ssplit(const char *& src, std::vector<std::string>& dest, const char *delim = " ");
void ssplit(const std::string& src, std::vector<std::string>& dest, const char *delim = " ");

}} // namespace dgg::util

#endif



<|start_filename|>src/DgSuperfund.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSuperfund.h: DgSuperfund class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSUPERFUND_H
#define DGSUPERFUND_H

int sfRes2actualRes (int sfRes);
int actualRes2sfRes (int actualRes);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgSqrD8Grid2DS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSqrD8Grid2DS.h: DgSqrD8Grid2DS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSQRD8GRID2DS_H 
#define DGSQRD8GRID2DS_H 

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgDiscRFS2D.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgSqrD8Grid2DS : public DgDiscRFS2D {

   public:

      DgSqrD8Grid2DS (DgRFNetwork& networkIn, 
                 const DgRF<DgDVec2D, long double>& backFrameIn,
                 int nRes = 1, unsigned int apertureIn = 4, 
                 bool isCongruentIn = true, bool isAlignedIn = false,
                 const string& nameIn = "8S4");

      DgSqrD8Grid2DS (const DgSqrD8Grid2DS& rf);

     ~DgSqrD8Grid2DS (void);

      DgSqrD8Grid2DS& operator= (const DgSqrD8Grid2DS& rf);

      int radix (void) const { return radix_; }

   protected:

      int radix_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgIVec2D>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgIVec2D>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgHexC1Grid2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgHexC1Grid2D.h: DgHexC1Grid2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGHEXC1GRID2D_H 
#define DGHEXC1GRID2D_H

#include <cmath>
#include <cstdint>

#include "DgDiscRF2D.h"
#include "DgDVec2D.h"
#include "DgIVec2D.h"

class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgHexC1Grid2D : public DgDiscRF2D {

   public:

      DgHexC1Grid2D (DgRFNetwork& networkIn, 
                     const DgRF<DgDVec2D, long double>& ccFrameIn,
                     const string& nameIn = "HexC12D")
         : DgDiscRF2D (networkIn, ccFrameIn, nameIn, 1.0 / sqrt(3.0), 
                       1.0 / sqrt(3.0), sqrt(3.0) / 2.0, 1.0) 
           { area_ = c(); }

      DgHexC1Grid2D (const DgHexC1Grid2D& grd) : DgDiscRF2D (grd) {}

      DgHexC1Grid2D& operator= (const DgHexC1Grid2D& grd)
           { DgDiscRF2D::operator=(grd); return *this; }

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const
           { DgIVec2D diff = add2 - add1;
             if ((diff.i() >= 0 && diff.j() <= 0) ||
                 (diff.i() <= 0 && diff.j() >= 0))   /* different signs */
             {
                return abs(diff.i()) + abs(diff.j());
             }
             else /* same signs */
             {
                diff.setI(abs(diff.i()));
                diff.setJ(abs(diff.j()));
                return (diff.i() > diff.j()) ? diff.i() : diff.j();
             }}

   protected:

      static const long double sin60_;

      virtual void setAddVertices (const DgIVec2D& add, DgPolygon& vec) const;
      virtual void setAddNeighbors 
                                  (const DgIVec2D& add, DgLocVector& vec) const;

      virtual DgIVec2D quantify (const DgDVec2D& point) const;

      virtual DgDVec2D invQuantify (const DgIVec2D& add) const
               { return DgDVec2D(add.i() - 0.5 * add.j(), 
                                 add.j() * 1.5 * r()); }

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgLocVector.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgLocVector.h: DgLocVector class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGLOCVECTOR_H
#define DGLOCVECTOR_H

#include <string>
#include <vector>
#include <iostream>

#include "DgLocation.h"

using namespace std;

class DgAddressBase;

////////////////////////////////////////////////////////////////////////////////
class DgLocVector : public DgLocBase {

   public:

      DgLocVector (void) { }

      DgLocVector (const DgLocVector& vec)    // deep copy
         : DgLocBase (vec.rf()) { *this = vec; }

      DgLocVector (const DgRFBase& rfIn, int sizeIn = 0);

     ~DgLocVector (void) { clearAddress(); }

      DgLocVector& operator= (const DgLocVector& vec); // deep copy

      bool operator== (const DgLocVector& vec) const;

      bool operator!= (const DgLocVector& vec) const
            { return !operator==(vec); }

      void setLoc (int ndx, const DgLocation& loc, bool conv = true);

      int size (void) const { return (int) vec_.size(); }

      void resize (int n) { vec_.resize(n, 0); }

      int capacity (void) const { return (int) vec_.capacity(); }

      void reserve (int n) { vec_.reserve(n); }

      const DgLocation& operator[] (int ndx) const
       { tmpLoc_.rf_ = rf_; tmpLoc_.address_ = vec_[ndx]; return tmpLoc(); }

      void push_back (const DgLocation& loc, bool conv = true);

      vector<DgAddressBase*>& addressVec (void) { return vec_; }

      const vector<DgAddressBase*>& addressVec (void) const { return vec_; }

      const DgLocation& tmpLoc (void) const { return tmpLoc_; }

      virtual string asString (void) const
               { return rf().toString(*this); }

      virtual string asString (char delimiter) const
               { return rf().toString(*this, delimiter); }

      virtual string asAddressString (void) const
               { return rf().toAddressString(*this); }

      virtual string asAddressString (char delimiter) const
               { return rf().toAddressString(*this, delimiter); }

      virtual const char* fromString (const char* str, char delimiter);

      virtual void clearAddress (void);

      virtual int cardinality (void) const { return size(); } 

   protected:

      mutable DgLocation tmpLoc_;

      virtual void convertTo (const DgRFBase& rf) { rf.convert(*this); }

   private:

      vector<DgAddressBase*> vec_;

   friend class DgRFBase;
   friend class DgConverterBase;
   friend class DgPoly;
   template <class A, class D> friend class DgRF;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgLocVector& vec)
{
   stream << vec.rf().name() << " {\n";

/* ccw
   for (int i = 0; i < vec.size(); i++) stream << vec[i] << "\n";
*/
   for (int i = vec.size() - 1; i >= 0; i--) stream << vec[i] << "\n";

   return stream << "}" << endl;

} // inline ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
inline DgLocVector& 
DgLocVector::operator= (const DgLocVector& vec)
{
   if (this != &vec)
   {
      clearAddress();
      
      rf_ = &vec.rf();
      resize(vec.size());

      for (int i = 0; i < size(); i++) 
      {
         vec_[i] = rf().createAddress(*vec.vec_[i]);
      }
   }

   return *this;

} // DgLocVector& DgLocVector::operator=

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgConverterBase.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgConverterBase.h: DgConverterBase class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGCONVERTERBASE_H
#define DGCONVERTERBASE_H

#include <vector>

using namespace std;

#include "DgRFBase.h"
#include "DgLocation.h"

////////////////////////////////////////////////////////////////////////////////
class DgConverterBase {

   public:
      virtual ~DgConverterBase (void);
     
      static bool isTraceOn (void) { return isTraceOn_; }
      static bool setTraceOn (bool traceOnIn) 
                     { isTraceOn_ = traceOnIn; return isTraceOn(); }
      //static void setTraceStream (ostream& stream = cout) 
      //                     { traceStream_ = &stream; }
      //static ostream& traceStream (void) { return *traceStream_; }

      virtual DgLocation* convert (DgLocation* loc) const; // convert in place

      void forceConnectFrom (bool verify = true) const;
      void forceConnectTo   (bool verify = true) const;

      const DgRFBase& fromFrame (void) const { return *fromFrame_; }
      const DgRFBase& toFrame   (void) const { return *toFrame_; }
      
      bool userGenerated (void) const { return userGenerated_; }

   protected:

      DgConverterBase (const DgRFBase& fromFrame, 
                       const DgRFBase& toFrame, bool userGenerated = true);

      DgConverterBase (const DgConverterBase& con) { operator=(con); }

      DgConverterBase& operator= (const DgConverterBase& con);

      virtual DgAddressBase* createConvertedAddress 
                              (const DgAddressBase& addIn) const = 0;

      static bool isTraceOn_;
      //static ostream* traceStream_;

      DgRFBase* fromFrame_;
      DgRFBase* toFrame_;
      
      bool userGenerated_;

   friend class DgRFBase;
   friend class DgSeriesConverter;
};

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgConverterBase& con)
            { return stream << "{" << con.fromFrame().name()
                            << "->" << con.toFrame().name() << "}"; }

////////////////////////////////////////////////////////////////////////////////
class DgIdentityConverter : public DgConverterBase {

   public:

      DgIdentityConverter (const DgRFBase& frame)
          : DgConverterBase(frame, frame, false) {}

      virtual DgLocation* convert (DgLocation* loc) const { return loc; }

   protected:

      virtual DgAddressBase* createConvertedAddress 
                                  (const DgAddressBase& addIn) const
              { return fromFrame().createAddress(addIn); }

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIDGG.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGG.cpp: DgIDGG class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <limits>
#include <cstdint>

#include "DgUtil.h"
#include "DgIDGG.h"
#include "DgDmdD4Grid2DS.h"
#include "DgHexGrid2DS.h"
#include "DgTriGrid2DS.h"
#include "DgSeriesConverter.h"
#include "DgRadixString.h"
#include "DgBoundedIDGG.h"
#include "DgProjISEA.h"
#include "DgProjFuller.h"

const DgQ2DICoord DgQ2DICoord::undefDgQ2DICoord(-1, 
                                     DgIVec2D(std::numeric_limits<std::int64_t>::max(), std::numeric_limits<std::int64_t>::max()));
const DgQ2DDCoord DgQ2DDCoord::undefDgQ2DDCoord(-1, 
                                     DgDVec2D(std::numeric_limits<long double>::max(), std::numeric_limits<long double>::max()));

////////////////////////////////////////////////////////////////////////////////
DgVertTriVals DgVertex2DDRF::vertTable_[12][6] = {  

   {  // vert 0

      DgVertTriVals(  2,  1, 0, true,  DgDVec2D(-M_HALF, -M_SIN60),  3 ), 
      DgVertTriVals(  1,  0, 1, true,  DgDVec2D(-M_ONE,   M_ZERO ),  2 ), 
      DgVertTriVals(  5,  4, 2, true,  DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals( -1, -1, 3, false, DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals(  4,  3, 4, true,  DgDVec2D( M_ONE,   M_ZERO ), -1 ), 
      DgVertTriVals(  3,  2, 5, true,  DgDVec2D( M_HALF, -M_SIN60), -2 )  
   },

   {  // vert 1

      DgVertTriVals(  1,  0, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  1,  5, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals( 10, 14, 2, true,  DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals( -1, -1, 3, false, DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals(  5,  9, 4, true,  DgDVec2D( M_ZERO,  M_ZERO),  3 ), 
      DgVertTriVals(  5,  4, 5, true,  DgDVec2D( M_ONE,   M_ZERO),  0 )  
   },

   {  // vert 2

      DgVertTriVals(  2,  1, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  2,  6, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals( 10, 10, 2, true,  DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals( -1, -1, 3, false, DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals(  1,  5, 4, true,  DgDVec2D( M_ZERO,  M_ZERO),  3 ), 
      DgVertTriVals(  1,  0, 5, true,  DgDVec2D( M_ONE,   M_ZERO),  0 )  
   },

   {  // vert 3

      DgVertTriVals(  3,  2, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  3,  7, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  7, 11, 2, true,  DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals( -1, -1, 3, false, DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals(  2,  6, 4, true,  DgDVec2D( M_ZERO,  M_ZERO),  3 ), 
      DgVertTriVals(  2,  1, 5, true,  DgDVec2D( M_ONE,   M_ZERO),  0 )  
   },

   {  // vert 4

      DgVertTriVals(  4,  3, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  4,  8, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  8, 12, 2, true,  DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals( -1, -1, 3, false, DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals(  3,  7, 4, true,  DgDVec2D( M_ZERO,  M_ZERO),  3 ), 
      DgVertTriVals(  3,  2, 5, true,  DgDVec2D( M_ONE,   M_ZERO),  0 )  
   },

   {  // vert 5

      DgVertTriVals(  5,  4, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  5,  9, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  9, 13, 2, true,  DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals( -1, -1, 3, false, DgDVec2D(-M_HALF,  M_SIN60), 1 ), 
      DgVertTriVals(  4,  8, 4, true,  DgDVec2D( M_ZERO,  M_ZERO),  3 ), 
      DgVertTriVals(  4,  3, 5, true,  DgDVec2D( M_ONE,   M_ZERO),  0 )  
   },

   {  // vert 6

      DgVertTriVals(  6, 10, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),   1 ), 
      DgVertTriVals(  6, 15, 1, true,  DgDVec2D(-M_HALF, -M_SIN60),  4 ), 
      DgVertTriVals( 10, 19, 2, true,  DgDVec2D( M_ZERO,  M_ZERO),  -1 ), 
      DgVertTriVals( 10, 14, 3, true,  DgDVec2D(-M_HALF,  M_SIN60),  2 ), 
      DgVertTriVals( -1, -1, 4, false, DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals(  1,  5, 5, true,  DgDVec2D( M_HALF, -M_SIN60),  4 )  
   },

   {  // vert 7

      DgVertTriVals(  7, 11, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),   1 ), 
      DgVertTriVals(  7, 16, 1, true,  DgDVec2D(-M_HALF, -M_SIN60),  4 ), 
      DgVertTriVals(  6, 15, 2, true,  DgDVec2D( M_ZERO,  M_ZERO),  -1 ), 
      DgVertTriVals(  6, 10, 3, true,  DgDVec2D(-M_HALF,  M_SIN60),  2 ), 
      DgVertTriVals( -1, -1, 4, false, DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals(  2,  6, 5, true,  DgDVec2D( M_HALF, -M_SIN60),  4 )  
   },

   {  // vert 8

      DgVertTriVals(  8, 12, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),   1 ), 
      DgVertTriVals(  8, 17, 1, true,  DgDVec2D(-M_HALF, -M_SIN60),  4 ), 
      DgVertTriVals(  7, 16, 2, true,  DgDVec2D( M_ZERO,  M_ZERO),  -1 ), 
      DgVertTriVals(  7, 11, 3, true,  DgDVec2D(-M_HALF,  M_SIN60),  2 ), 
      DgVertTriVals( -1, -1, 4, false, DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals(  3,  7, 5, true,  DgDVec2D( M_HALF, -M_SIN60),  4 )  
   },

   {  // vert 9

      DgVertTriVals(  9, 13, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),   1 ), 
      DgVertTriVals(  9, 18, 1, true,  DgDVec2D(-M_HALF, -M_SIN60),  4 ), 
      DgVertTriVals(  8, 17, 2, true,  DgDVec2D( M_ZERO,  M_ZERO),  -1 ), 
      DgVertTriVals(  8, 12, 3, true,  DgDVec2D(-M_HALF,  M_SIN60),  2 ), 
      DgVertTriVals( -1, -1, 4, false, DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals(  4,  8, 5, true,  DgDVec2D( M_HALF, -M_SIN60),  4 )  
   },

   {  // vert 10

      DgVertTriVals( 10, 14, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),   1 ), 
      DgVertTriVals( 10, 19, 1, true,  DgDVec2D(-M_HALF, -M_SIN60),  4 ), 
      DgVertTriVals(  9, 18, 2, true,  DgDVec2D( M_ZERO,  M_ZERO),  -1), 
      DgVertTriVals(  9, 13, 3, true,  DgDVec2D(-M_HALF,  M_SIN60),  2 ), 
      DgVertTriVals( -1, -1, 4, false, DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals(  5,  9, 5, true,  DgDVec2D( M_HALF, -M_SIN60),  4 )  
   },

   {  // vert 11 

      DgVertTriVals(  8, 17, 0, true,  DgDVec2D(-M_HALF, -M_SIN60),  3 ), 
      DgVertTriVals(  9, 18, 1, true,  DgDVec2D(-M_ONE,   M_ZERO),   2 ), 
      DgVertTriVals( 10, 19, 2, true,  DgDVec2D(-M_HALF,  M_SIN60),  1 ), 
      DgVertTriVals(  6, 15, 3, true,  DgDVec2D( M_HALF,  M_SIN60),  0 ), 
      DgVertTriVals( -1, -1, 4, false, DgDVec2D( M_ZERO,  M_ZERO),   0 ), 
      DgVertTriVals(  7, 16, 5, true,  DgDVec2D( M_HALF, -M_SIN60), -2 )  
   }

};

////////////////////////////////////////////////////////////////////////////////
const DgVertTriVals DgVertex2DDRF::triTable_[20] = {

      DgVertTriVals(  1,  0, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  2,  1, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  3,  2, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  4,  3, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  5,  4, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  1,  5, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  2,  6, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  3,  7, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  4,  8, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  5,  9, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  6, 10, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  7, 11, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  8, 12, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  9, 13, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals( 10, 14, 0, true,  DgDVec2D( M_ZERO,  M_ZERO),  1 ), 
      DgVertTriVals(  6, 15, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  7, 16, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  8, 17, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals(  9, 18, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
      DgVertTriVals( 10, 19, 1, true,  DgDVec2D(-M_HALF, -M_SIN60), 4 ), 
};

////////////////////////////////////////////////////////////////////////////////
const DgQuadEdgeCells DgIDGG::edgeTable_[12] = {

   DgQuadEdgeCells(0,  true,  0,  0, 0), // quad 0 should never occur
   DgQuadEdgeCells(1,  true,  0,  2, 6),
   DgQuadEdgeCells(2,  true,  0,  3, 7),
   DgQuadEdgeCells(3,  true,  0,  4, 8),
   DgQuadEdgeCells(4,  true,  0,  5, 9),
   DgQuadEdgeCells(5,  true,  0,  1, 10),
   DgQuadEdgeCells(6,  false, 11, 2, 7),
   DgQuadEdgeCells(7,  false, 11, 3, 8),
   DgQuadEdgeCells(8,  false, 11, 4, 9),
   DgQuadEdgeCells(9,  false, 11, 5, 10),
   DgQuadEdgeCells(10, false, 11, 1, 6),
   DgQuadEdgeCells(11, false, 11, 0, 0)  // quad 11 should never occur

};

////////////////////////////////////////////////////////////////////////////////
const char*
DgQ2DDRF::str2add (DgQ2DDCoord* add, const char* str, char delimiter) const
{
   if (!add) add = new DgQ2DDCoord();

   char delimStr[2];
   delimStr[0] = delimiter;
   delimStr[1] = '\0';

   char* tmpStr = new char[strlen(str) + 1];
   strcpy(tmpStr, str);

   // get the quadNum

   char* tok = strtok(tmpStr, delimStr);
   int q;
   if (sscanf(tok, "%d", &q) != 1)
   {
      ::report("DgQ2DDRF::fromString() invalid value in string " + string(tok), 
               DgBase::Fatal);
   }

   const char* tmp = &(str[strlen(tok) + 1]);
   DgDVec2D vec;
   tmp = vec.fromString(tmp, delimiter);

   *add = DgQ2DDCoord(q, vec);

   return tmp;

} // const char* DgQ2DDRF::str2add

////////////////////////////////////////////////////////////////////////////////
const char*
DgVertex2DDRF::str2add (DgVertex2DDCoord* add, const char* str, char delimiter)                                                                           const
{
   if (!add) add = new DgVertex2DDCoord();

   char delimStr[2];
   delimStr[0] = delimiter;
   delimStr[1] = '\0';

   char* tmpStr = new char[strlen(str) + 1];
   strcpy(tmpStr, str);

   // get the vertNum

   char* tok = strtok(tmpStr, delimStr);
   int vNum;
   if (sscanf(tok, "%d", &vNum) != 1)
   {
      ::report("DgVertex2DDCoord::fromString() invalid value in string " +
               string(tok), DgBase::Fatal);
   }

   // get the triNum

   tok = strtok(NULL, delimStr);
   int tNum;
   if (sscanf(tok, "%d", &tNum) != 1)
   {
      ::report("DgVertex2DDCoord::fromString() invalid value in string " +
               string(tok), DgBase::Fatal);
   }

   // get the keeper

   tok = strtok(NULL, delimStr);

   bool keep = true;;

   if (strcmp(tok, "keep") == 0)
      keep = true;
   else if (strcmp(tok, "nokeep") == 0)
      keep = false;
   else
   {
      ::report("DgVertex2DDCoord::fromString() invalid value in string " +
               string(tok), DgBase::Fatal);
   }

   const char* tmp = &(str[(tok - tmpStr) + strlen(tok) + 1]);
   DgDVec2D vec;
   tmp = vec.fromString(tmp, delimiter);

   *add = DgVertex2DDCoord(keep, vNum, tNum, vec);

   return tmp;

} // const char* DgVertex2DDRF::str2add

////////////////////////////////////////////////////////////////////////////////
const char*
DgInterleaveRF::str2add (DgInterleaveCoord* add, const char* str, 
                         char delimiter) const
{
   if (!add) add = new DgInterleaveCoord();

   char delimStr[2];
   delimStr[0] = delimiter;
   delimStr[1] = '\0';

   char* tmpStr = new char[strlen(str) + 1];
   strcpy(tmpStr, str);
   char* tok = strtok(tmpStr, delimStr);

   add->setValString(tok);

   delete[] tmpStr;

   unsigned int offset = strlen(tok) + 1;
   if (offset >= strlen(str)) return 0;
   else return &str[offset];

} // const char* DgInterleaveRF::str2add

////////////////////////////////////////////////////////////////////////////////
const char*
DgIDGG::str2add (DgQ2DICoord* add, const char* str, char delimiter) const
{
   if (!add) add = new DgQ2DICoord();

   char delimStr[2];
   delimStr[0] = delimiter;
   delimStr[1] = '\0';

   char* tmpStr = new char[strlen(str) + 1];
   strcpy(tmpStr, str);

   // get the quadNum

   char* tok = strtok(tmpStr, delimStr);
   int q;
   if (sscanf(tok, "%d", &q) != 1)
   {
      ::report("DgQ2DIRF::fromString() invalid value in string " +
               string(tok), DgBase::Fatal);
   }

   const char* tmp = &(str[strlen(tok) + 1]);
   DgIVec2D vec;
   tmp = vec.fromString(tmp, delimiter);

   *add = DgQ2DICoord(q, vec);

   return tmp;

} // const char* DgIDGG::str2add

////////////////////////////////////////////////////////////////////////////////
DgQ2DDtoIConverter::DgQ2DDtoIConverter (
   const DgRF<DgQ2DDCoord, long double>& from, const DgRF<DgQ2DICoord, std::int64_t>& to)
  : DgConverter<DgQ2DDCoord, long double, DgQ2DICoord, std::int64_t>(from, to),
    pIDGG_ (0) 
{ 
   pIDGG_ = dynamic_cast<const DgIDGG*>(&toFrame());

   if (!pIDGG_)
   {
      report("DgQ2DDtoIConverter::DgQ2DDtoIConverter(): "
      " toFrame not of type DgIDGG", DgBase::Fatal);
   }

} // DgQ2DDtoIConverter::DgQ2DDtoIConverter

////////////////////////////////////////////////////////////////////////////////
DgQ2DICoord 
DgQ2DDtoIConverter::convertTypedAddress (const DgQ2DDCoord& addIn) const
{
   DgLocation* loc = IDGG().ccFrame().makeLocation(addIn.coord());

#if DGDEBUG
cout << "DgQ2DDtoIConverter::convertTypedAddress loc: " << *loc << endl;
#endif

    IDGG().grid2D().convert(loc);

#if DGDEBUG
cout << " ---> " << *loc << endl;
#endif

   DgIVec2D coord = *IDGG().grid2D().getAddress(*loc);
   delete loc;

   int quadNum = addIn.quadNum();

   const long double nudge = 0.0000001L;
   if (coord.i() < 0 || coord.j() < 0) // maybe round-off error?
   {
      DgDVec2D tmp(addIn.coord());

      tmp.setX(tmp.x() + nudge);
      tmp.setY(tmp.y() + nudge);

      loc = IDGG().ccFrame().makeLocation(tmp);
      IDGG().grid2D().convert(loc);
      coord = *IDGG().grid2D().getAddress(*loc);
      delete loc;
   }

   std::int64_t edgeI = IDGG().maxI() + 1;
   std::int64_t edgeJ = IDGG().maxJ() + 1;
   if (coord.i() > edgeI || coord.j() > edgeJ) // maybe round-off error?
   {
      DgDVec2D tmp(addIn.coord());

      tmp.setX(tmp.x() - nudge);
      tmp.setY(tmp.y() - nudge);

      loc = IDGG().ccFrame().makeLocation(tmp);
      IDGG().grid2D().convert(loc);
      coord = *IDGG().grid2D().getAddress(*loc);
      delete loc;
   }

   if (coord.i() < 0 || coord.j() < 0 || 
       coord.i() > edgeI || coord.j() > edgeJ)
   {
      report("DgQ2DDtoIConverter::convertTypedAddress(): "
             " coordinate out of range: " + (string) coord, DgBase::Fatal);
   }
   else if (coord.i() == edgeI || coord.j() == edgeJ)
   {
      const DgQuadEdgeCells& ec = IDGG().edgeTable(quadNum);

      if (ec.isType0())
      {
         if (coord.j() == edgeJ)
         {
            if (coord.i() == 0)
            {
               quadNum = ec.loneVert();
               coord = DgIVec2D(0, 0);
            }
            else
            {
               quadNum = ec.upQuad();
               coord = DgIVec2D(0, edgeI - coord.i());
            }
         }
         else // i == edgeI
         {
            quadNum = ec.rightQuad();
            coord.setI(0);
         }
      }
      else // type 1
      {
         if (coord.i() == edgeI)
         {
            if (coord.j() == 0)
            {
               quadNum = ec.loneVert();
               coord = DgIVec2D(0, 0);
            }
            else
            {
               quadNum = ec.rightQuad();
               coord = DgIVec2D(edgeJ - coord.j(), 0);
            }
         }
         else // j == edgeJ
         {
            quadNum = ec.upQuad();
            coord.setJ(0);
         }
      }
   } 

   DgQ2DICoord result(quadNum, coord);

   return result;

} // DgQ2DICoord DgQ2DDtoIConverter::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
DgQ2DItoDConverter::DgQ2DItoDConverter (const DgRF<DgQ2DICoord, std::int64_t>& from,
                                        const DgRF<DgQ2DDCoord, long double>& to)
        : DgConverter<DgQ2DICoord, std::int64_t, DgQ2DDCoord, long double> (from, to),
          pIDGG_ (NULL)
{ 
   pIDGG_ = dynamic_cast<const DgIDGG*>(&fromFrame());

   if (!pIDGG_)
   {
      report("DgQ2DItoDConverter::DgQ2DItoDConverter(): "
         " fromFrame not of type DgIDGG", DgBase::Fatal);
   }

} // DgQ2DItoDConverter::DgQ2DItoDConverter 

////////////////////////////////////////////////////////////////////////////////
DgQ2DDCoord 
DgQ2DItoDConverter::convertTypedAddress (const DgQ2DICoord& addIn) const
{
   DgLocation* loc = IDGG().grid2D().makeLocation(addIn.coord());
    IDGG().ccFrame().convert(loc);
    DgDVec2D coord = *IDGG().ccFrame().getAddress(*loc);
   delete loc;

   DgQ2DDCoord result(addIn.quadNum(), coord);
         
   return result;

} // DgQ2DDCoord DgQ2DItoDConverter::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
DgQ2DItoInterleaveConverter::DgQ2DItoInterleaveConverter 
                (const DgRF<DgQ2DICoord, std::int64_t>& from,
                 const DgRF<DgInterleaveCoord, std::int64_t>& to)
        : DgConverter<DgQ2DICoord, std::int64_t, DgInterleaveCoord, std::int64_t> (from, to),
          pIDGG_ (NULL)
{ 
   pIDGG_ = dynamic_cast<const DgIDGG*>(&fromFrame());

   if (!pIDGG_)
   {
      report("DgQ2DItoInterleaveConverter::DgQ2DItoInterleaveConverter(): "
         " fromFrame not of type DgIDGG", DgBase::Fatal);
   }

} // DgQ2DItoInterleaveConverter::DgQ2DItoInterleaveConverter 

////////////////////////////////////////////////////////////////////////////////
DgInterleaveCoord 
DgQ2DItoInterleaveConverter::convertTypedAddress 
                                               (const DgQ2DICoord& addIn) const
{
   string qstr = dgg::util::to_string(addIn.quadNum(), 2);

   int effRes = IDGG().res();       // effective resolution
   int effRadix = IDGG().radix();   // effective radix
   if (IDGG().aperture() == 3)    
   {
       effRadix = 3;
       effRes = (effRes + 1) / 2;
   }

   if (IDGG().gridTopo() == string("TRIANGLE")) effRes++; // adjust for long double j

//cout << "addIn " << addIn << endl;
   DgRadixString rs1(effRadix, addIn.coord().i(), effRes);
   DgRadixString rs2(effRadix, addIn.coord().j(), effRes);

//cout << "rs1 " << rs1 << endl;
//cout << "rs2 " << rs2 << endl;

   string addstr = qstr;
   if (IDGG().aperture() == 3)
   {
     if (IDGG().isClassI()) addstr = addstr + string("0");
     else addstr = addstr + string("1");
   }

   addstr = addstr + DgRadixString::digitInterleave(rs1, rs2);

//cout << "addstr " << addstr << endl;

   DgInterleaveCoord res;
   res.setValString(addstr);
//cout << "res " << res << endl;

   return res;

} // DgInterleaveCoord DgQ2DItoInterleaveConverter::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
DgVertex2DDToQ2DDConverter::DgVertex2DDToQ2DDConverter (
   const DgRF<DgVertex2DDCoord, long double>& from, 
   const DgRF<DgQ2DDCoord, long double>& to)
  : DgConverter<DgVertex2DDCoord, long double, DgQ2DDCoord, long double>(from, to)
{ 

} // DgVertex2DDToQ2DDConverter::DgVertex2DDToQ2DDConverter

////////////////////////////////////////////////////////////////////////////////
DgQ2DDCoord 
DgVertex2DDToQ2DDConverter::convertTypedAddress 
                                      (const DgVertex2DDCoord& addIn) const
{
   DgQ2DDCoord result(addIn.vertNum(), addIn.coord());

   return result;

} // DgQ2DDCoord DgVertex2DDToQ2DDConverter::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
DgQ2DDtoVertex2DDConverter::DgQ2DDtoVertex2DDConverter 
          (const DgRF<DgQ2DDCoord, long double>& from,
           const DgRF<DgVertex2DDCoord, long double>& to)
  : DgConverter<DgQ2DDCoord, long double, DgVertex2DDCoord, long double>(from, to)
{ 

} // DgQ2DDtoVertex2DDConverter::DgQ2DDtoVertex2DDConverter 

////////////////////////////////////////////////////////////////////////////////
// Private helper method to compute subtriangle region:
int 
DgQ2DDtoVertex2DDConverter::compute_subtriangle
                    (const long double& x, const long double& y) const
{
 const long double tol = 0.000000000000001L;

 long double xs = M_SQRT3 * x;

 long double xpp =	 xs + tol,
	xmp =	-xs + tol,
	xpm =	 xs - tol,
	xmm =	-xs - tol;

   if (y >= xmm && y > xpp) 
   {
	return 0;
   }

   if ((fabs(y) <= tol && fabs(x) <= tol)  ||
       (y <= xpp && y >= (0.0 - tol))) 
   {
      return 1;
   }

   if (y < (0.0 - tol) && y > xmp) 
   {
      return 2;
   }

   if (y <= xmp && y < xpm) 
   {
      return 3;
   }

   if (y >= xpm && y < (0.0 - tol)) 
   {
      return 4;
   }

   if (y >= (0.0 - tol) && y < xmm) 
   {
      return 5;
   }

   report("Dg2DDtoVertex2DDConverter value out of hex", DgBase::Fatal);

   return -1;
}

////////////////////////////////////////////////////////////////////////////////
DgVertex2DDCoord 
DgQ2DDtoVertex2DDConverter::convertTypedAddress (const DgQ2DDCoord& addIn) const
{
   int subTri = compute_subtriangle(addIn.coord().x(), addIn.coord().y());

   const DgVertTriVals& st = DgVertex2DDRF::vertTable(addIn.quadNum(), subTri);

   DgVertex2DDCoord newCoord(st.keep());
   if (newCoord.keep())
   {
      newCoord.setVertNum(addIn.quadNum());
      newCoord.setTriNum(subTri);
      newCoord.setCoord(addIn.coord());
   }
   else
   {
      newCoord.setVertNum(-1);
      newCoord.setTriNum(-1);
   }

   return newCoord;

} // DgVertex2DDCoord DgQ2DDtoVertex2DDConverter::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
DgVertex2DDCoord 
DgProjTriToVertex2DD::convertTypedAddress (const DgProjTriCoord& addIn) const
{
   const DgVertTriVals& triVals = DgVertex2DDRF::triTable(addIn.triNum());

   DgVertex2DDCoord newCoord(true, triVals.quadNum(), addIn.triNum());

   DgDVec2D tmpCoord(addIn.coord());
   tmpCoord.rotate(triVals.rot60() * 60.0L);
   tmpCoord -= triVals.trans();

   newCoord.setCoord(tmpCoord);

   return newCoord;

} // DgVertex2DDCoord DgProjTriToVertex2DD::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
DgProjTriCoord 
DgVertex2DDtoProjTri::convertTypedAddress (const DgVertex2DDCoord& addIn) const
{
   const DgVertTriVals& triVal = 
                   DgVertex2DDRF::vertTable(addIn.vertNum(), addIn.triNum());

   //const DgVertTriVals& triVals = DgVertex2DDRF::triTable(addIn.triNum());

   DgDVec2D tmpCoord(addIn.coord());
   tmpCoord += triVal.trans();
   tmpCoord.rotate(triVal.rot60() * -60.0L);

   DgProjTriCoord newCoord(triVal.triNum(), tmpCoord);

   return newCoord;

} // DgProjTriCoord DgVertex2DDtoProjTri::convertTypedAddress

////////////////////////////////////////////////////////////////////////////////
DgPlaneTriProj::DgPlaneTriProj (const DgRF<DgProjTriCoord, long double>& from,
                                const DgRF<DgDVec2D, long double>& to)
         : DgConverter<DgProjTriCoord, long double, DgDVec2D, long double>(from, to),
           pPlaneTriRF_ (0)
{ 
   pPlaneTriRF_= dynamic_cast<const DgPlaneTriRF*>(&toFrame());

   if (!pPlaneTriRF_)
   {
      report("DgPlaneTriProj::DgPlaneTriProj(): "
        " toFrame not of type DgPlaneTriRF", DgBase::Fatal);
   }

} // DgPlaneTriProj::DgPlaneTriProj 

////////////////////////////////////////////////////////////////////////////////
DgDVec2D 
DgPlaneTriProj::convertTypedAddress (const DgProjTriCoord& addIn) const
{
   //DgDVec2D scaledPt(addIn.coord().x() / snyedglen,
                           //addIn.coord().y() / snyedglen);
   DgDVec2D newPt(addIn.coord());
   planeTriRF().icosaMap().translate(addIn.triNum(), &newPt);

   return newPt;

} // DgDVec2D DgPlaneTriProj::convertTypedAddress 

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIDGG::DgIDGG (const DgGeoSphRF& geoRF, const DgGeoCoord& vert0, 
       long double azDegs, unsigned int aperture, int res, const string& name,
       const string& gridTopo, const string& projType, bool isMixed43, 
       int numAp4, bool isSuperfund, int sfRes, unsigned int precision)
   : 
     DgDiscRF<DgQ2DICoord, DgGeoCoord, long double>(geoRF.network(), geoRF, name),
     sphIcosa_(0), geoRF_(geoRF), vert0_(vert0), azDegs_(azDegs),
     gridTopo_(gridTopo), projType_(projType), aperture_(aperture), res_(res),
     isMixed43_(isMixed43), numAp4_(numAp4), isSuperfund_(isSuperfund),
     sfRes_ (sfRes), precision_(precision), grid2D_(0), grid2DS_(0), ccFrame_(0),
     projTriRF_(0), vertexRF_(0), q2ddRF_(0), bndRF_(0), intRF_(0), planeRF_(0)
{ 
   initialize();

} // DgIDGG::DgIDGG

////////////////////////////////////////////////////////////////////////////////
DgIDGG::DgIDGG (const DgIDGG& rfIn)
   : DgDiscRF<DgQ2DICoord, DgGeoCoord, long double> (rfIn), 
        sphIcosa_(0), geoRF_(rfIn.geoRF()), vert0_(rfIn.vert0()), 
        azDegs_(rfIn.azDegs()), gridTopo_(rfIn.gridTopo()), 
        projType_ (rfIn.projType()), aperture_(rfIn.aperture()), 
        res_(rfIn.res()), isMixed43_(rfIn.isMixed43()), numAp4_(rfIn.numAp4()), 
        isSuperfund_(rfIn.isSuperfund()), sfRes_(rfIn.sfRes()), 
        precision_(rfIn.precision()), grid2D_(0), grid2DS_(0), ccFrame_(0), 
        projTriRF_(0), vertexRF_(0), q2ddRF_(0), bndRF_(0), intRF_(0), 
        planeRF_(0)
{ 
   initialize();

} // DgIDGG::DgIDGG

DgIDGG::~DgIDGG()
{
 /* Notice that we do not delete:
	grid2D_, grid2DS_
    ...this is because they are freed elsewhere (by DgHexGrid2DS.C), and a segfault
    will result. It would be good to resolve the "ambiguity" -JFW */

 delete sphIcosa_;

 delete ccFrame_;

 delete projTriRF_;
 delete vertexRF_;
 delete q2ddRF_;
 delete bndRF_;
 delete intRF_;
 delete planeRF_;
}

////////////////////////////////////////////////////////////////////////////////
void
DgIDGG::initialize (void)
{
   // verify parameter validity

   string apErrStr = string("DgIDGG::initialize(): invalid aperture " + 
                         dgg::util::to_string(aperture()) + 
                         string(" for grid topo ") + gridTopo());

   if (gridTopo() == "HEXAGON")
   {
      if (aperture() != 3 && aperture() != 4) 
         report(apErrStr, DgBase::Fatal);
   }
   else if (gridTopo() == "TRIANGLE" || gridTopo() == "DIAMOND")
   {
      if (aperture() != 4) report(apErrStr, DgBase::Fatal);
   }
   else
      report("DgIDGG::initialize(): invalid grid topo '" + gridTopo() + "'", 
             DgBase::Fatal);

   if (isMixed43())
      aperture_ = (res() > numAp4()) ? 3 : 4;

   // create some internal data structures

   undefLoc_ = makeLocation(undefAddress());
   sphIcosa_ = new DgSphIcosa(vert0(), azDegs());

   // setup some parameters

   isClassI_ = true; // default
   radix_ = (int) sqrt((long double) aperture());
   adjRes_ = res();

   if (gridTopo() == "HEXAGON")
   {
      isAligned_ = true;
      isCongruent_ = false;

      if (!isMixed43())
      {
         if (aperture() == 4)
         {
            isClassI_ = true;
            maxD_ = (std::int64_t) pow(2.0L, res()) - 1;
         }
         else // aperture 3
         {
            isClassI_ = !(res() % 2);
            if (!isClassI()) adjRes_ = res() + 1;
            maxD_ = (std::int64_t) pow(3.0L, (adjRes() / 2)) - 1;
         }
      }
      else // mixed43
      {
         if (res() <= numAp4())
         {
            isClassI_ = true;
            maxD_ = (std::int64_t) pow(2.0L, res()) - 1;
         }
         else
         {
            isClassI_ = !((res() - numAp4()) % 2);
            if (!isClassI()) adjRes_ = res() + 1;

            maxD_ = (std::int64_t) (pow(2.0L, numAp4()) *
                      pow(3.0L, ((adjRes() - numAp4()) / 2))) - 1;
         }
         // cout << "MAXD: " << maxD_ << endl;
      }
      maxI_ = maxD();
      maxJ_ = maxD();
      mag_ = maxD() + 1;
      firstAdd_ = DgQ2DICoord(0, DgIVec2D(0, 0));
      lastAdd_ = DgQ2DICoord(11, DgIVec2D(0, 0));
   }
   else
   {
      maxD_ = (std::int64_t) pow((long double) radix(), res()) - 1;
      maxI_ = maxD();
      maxJ_ = maxD();
      mag_ = maxD() + 1;
      if (gridTopo() == "TRIANGLE") 
      {
         isAligned_ = true; // only for aperture 4
         isCongruent_ = true;
         maxJ_ = (mag() * 2) - 1;
      }
      else // topo is DIAMOND
      {
         isAligned_ = false;
         isCongruent_ = true;
      }
      firstAdd_ = DgQ2DICoord(1, DgIVec2D(0, 0));
      lastAdd_ = DgQ2DICoord(10, DgIVec2D(maxI(), maxJ()));
   }

   // set-up local network to scale so that quad (and consequently tri) edge 
   // length is 1.0

   ccFrame_ = new DgContCartRF(locNet_, name() + "CC1");

   if (gridTopo() == "DIAMOND")
   {
      grid2DS_ = new DgDmdD4Grid2DS(locNet_, ccFrame(), res() + 1, aperture(), 
                                    isCongruent(), isAligned());
   }
   else if (gridTopo() == "HEXAGON")
   {
      grid2DS_ = new DgHexGrid2DS(locNet_, ccFrame(), adjRes() + 1, aperture(), 
        isCongruent(), isAligned(), "H2DS", isMixed43(), numAp4(), isSuperfund());
   }
   else if (gridTopo() == "TRIANGLE")
   {
      grid2DS_ = new DgTriGrid2DS(locNet_, ccFrame(), res() + 1, aperture(), 
                                  isCongruent(), isAligned());
   }

   grid2D_ = dynamic_cast<DgDiscRF2D*>(grid2DS().grids()[res()]);
   bndRF_ = new DgBoundedIDGG(*this);

   // create the intermediate RFs

   projTriRF_ = new DgProjTriRF(network(), name() + string("projTri"), 
                sphIcosa_);
   vertexRF_ = new DgVertex2DDRF(network(), name() + string("vertex"));
   q2ddRF_   = new DgQ2DDRF(network(), name() + string("q2dd"));
   intRF_    = new DgInterleaveRF(network(), name() + string("int"));
   planeRF_  = new DgPlaneTriRF(network(), name() + string("plane"));

   // create the converters; for convenience use where they are in overall
   // sequence for name

   DgIcosaProj* icosaProj = NULL; 
   if (projType() == "ISEA")
      icosaProj = new DgProjISEA(geoRF(), projTriRF());
   else if (projType() == "FULLER")
      icosaProj = new DgProjFuller(geoRF(), projTriRF());
   else
      report("DgIDGG::initialize(): invalid projection type " + projType(), 
             DgBase::Fatal);

   const DgConverterBase* c1to2 = &(icosaProj->forward());
   const DgConverterBase* c2to3 = new DgProjTriToVertex2DD(projTriRF(), vertexRF());
   const DgConverterBase* c3to4 = new DgVertex2DDToQ2DDConverter(vertexRF(), q2ddRF());
   const DgConverterBase* c4to5 = new DgQ2DDtoIConverter(q2ddRF(), *this);
   
   const DgConverterBase* c5to4 = new DgQ2DItoDConverter(*this, q2ddRF());
   const DgConverterBase* c4to3 = new DgQ2DDtoVertex2DDConverter(q2ddRF(), vertexRF());
   const DgConverterBase* c3to2 = new DgVertex2DDtoProjTri(vertexRF(), projTriRF());
   const DgConverterBase* c2to1 = &(icosaProj->inverse());

   DgConverterBase* toInt = new DgQ2DItoInterleaveConverter(*this, intRF());
   DgConverterBase* toPlane = new DgPlaneTriProj(projTriRF(), planeRF());

   // create the series converters that will replace the default DgDiscRF
   // converters

   vector<const DgConverterBase*> sc;
   sc.push_back(c1to2);
   sc.push_back(c2to3);
   sc.push_back(c3to4);
   sc.push_back(c4to5);
   new DgSeriesConverter(sc, true);
   sc.resize(0);
   
   sc.push_back(c5to4);
   sc.push_back(c4to3);
   sc.push_back(c3to2);
   sc.push_back(c2to1);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   //// now fill in the other connections; begin with from vertexRF and then
   //// connect to it as needed

   // vertexRF -> geoRF
   sc.push_back(c3to2);
   sc.push_back(c2to1);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // vertexRF -> Q2DI
   sc.push_back(c3to4);
   sc.push_back(c4to5);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // vertexRF -> projTriRF is c3to2 above

   // vertexRF -> planeRF
   sc.push_back(c3to2);
   sc.push_back(toPlane);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // vertexRF -> Q2DD is c3to4 above

   // vertexRF -> intRF
   sc.push_back(c3to4);
   sc.push_back(c4to5);
   sc.push_back(toInt);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   /// now do from projTriRF
   
   // projTriRF -> geoRF is c2to1 above

   // projTriRF -> Q2DI
   sc.push_back(c2to3);
   sc.push_back(network().getConverter(vertexRF(), *this));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // projTriRF -> vertexRF is c2to3 above
   // projTriRF -> planeRF is toPlane above

   // projTriRF -> Q2DD
   sc.push_back(c2to3);
   sc.push_back(c3to4);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // projTriRF -> intRF
   sc.push_back(c2to3);
   sc.push_back(network().getConverter(vertexRF(), intRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   /// do from Q2DD

   // Q2DD -> geoRF
   sc.push_back(c4to3);
   sc.push_back(network().getConverter(vertexRF(), geoRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // Q2DD -> Q2DI is c4to5 above
   // Q2DD -> vertexRF is c4to3 above

   // Q2DD -> projTriRF
   sc.push_back(c4to3);
   sc.push_back(network().getConverter(vertexRF(), projTriRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // Q2DD -> planeRF
   sc.push_back(c4to3);
   sc.push_back(network().getConverter(vertexRF(), planeRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // Q2DD -> intRF
   sc.push_back(c4to3);
   sc.push_back(network().getConverter(vertexRF(), intRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   /// do from Q2DI

   // Q2DI -> geoRF is series converter given above

   // Q2DI -> vertexRF
   sc.push_back(c5to4);
   sc.push_back(c4to3);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // Q2DI -> projTriRF
   sc.push_back(c5to4);
   sc.push_back(network().getConverter(q2ddRF(), projTriRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // Q2DI -> planeRF
   sc.push_back(c5to4);
   sc.push_back(network().getConverter(q2ddRF(), planeRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // Q2DI -> Q2DD is c5to4 above
   // Q2DI -> intRF is toInt above

   /// finally from geoRF

   // geoRF -> Q2DI is series converter given above

   // geoRF -> vertexRF
   sc.push_back(c1to2);
   sc.push_back(c2to3);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // geoRF -> projTriRF is c1to2 above

   // geoRF -> planeRF
   sc.push_back(network().getConverter(geoRF(), vertexRF()));
   sc.push_back(network().getConverter(vertexRF(), planeRF()));
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // geoRF -> Q2DD
   sc.push_back(c1to2);
   sc.push_back(c2to3);
   sc.push_back(c3to4);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   // geoRF -> intRF
   sc.push_back(network().getConverter(geoRF(), *this));
   sc.push_back(toInt);
   new DgSeriesConverter(sc, true);
   sc.resize(0);

   ///// calculate the statistics /////

   gridStats_.setPrecision(precision());
   gridStats_.setNCells(bndRF().size());

   long double tmpLen = DgGeoSphRF::icosaEdgeKM();
   if (gridTopo() == "TRIANGLE") tmpLen /= M_SQRT3;
   if (!isMixed43())
      gridStats_.setCellDistKM(tmpLen / pow(sqrt((long double) aperture()), res()));
   else // mixed43
   {
      if (res() < numAp4())
      {
         tmpLen = tmpLen / pow((long double) 2.0, (long double) res());
      }
      else
      {
         tmpLen = tmpLen / pow((long double) 2.0, (long double) numAp4());
         if (res() > numAp4())
            tmpLen = tmpLen / pow(M_SQRT3, (long double) (res() - numAp4()));
      }
      gridStats_.setCellDistKM(tmpLen);
   }

   if (gridTopo() == "HEXAGON")
   {
      // a = globeArea / ((#cells - 12) + (12 * 5/6))
      //   = globeArea / (#cells - 2);
      gridStats_.setCellAreaKM(DgGeoSphRF::totalAreaKM() / 
                       (gridStats_.nCells() - 2));
   }
   else if (gridTopo() == "DIAMOND")
      gridStats_.setCellAreaKM(DgGeoSphRF::totalAreaKM() / gridStats_.nCells());
   else if (gridTopo() == "TRIANGLE")
      gridStats_.setCellAreaKM(DgGeoSphRF::totalAreaKM() / gridStats_.nCells());

   gridStats_.setCLS(2.0L * 2.0L * DgGeoSphRF::earthRadiusKM() * 
                     asin(sqrt(gridStats_.cellAreaKM() / dgM_PI) / 
                     (2.0L * DgGeoSphRF::earthRadiusKM())));

} // DgIDGG::initialize

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGG::setVertices (const DgLocation& loc, DgPolygon& vec, 
                     int densify) const
{
   vec.clearAddress();
   backFrame().convert(vec);
  
   DgLocation tLoc(loc);
//cout << "*** " << loc << endl;
   convert(&tLoc);
//cout << "**** " << tLoc << endl;

   setAddVertices(*getAddress(tLoc), vec, densify);
   
} // void DgDiscRF::setVertices

////////////////////////////////////////////////////////////////////////////////
void
DgIDGG::setAddVertices (const DgQ2DICoord& add, DgPolygon& vec,
                        int densify) const
{
   DgLocation* tmpLoc = grid2D().makeLocation(add.coord());
//cout << "a: " << *tmpLoc << endl;
    DgPolygon dummy(ccFrame());
    vec = dummy;  // force empty RF to allow for network change
    grid2D().setVertices(*tmpLoc, vec);
   delete tmpLoc;

//cout << "A: " << vec << endl;
   ccFrame().convert(vec);
//cout << "B: " << vec << endl;

   // densify
   vec.densify(densify);
//cout << "C: " << vec << endl;
   
   // kludge to jump nets and add the quad number

   DgPolygon tmpVec(q2ddRF());
   vector<DgAddressBase*>& v = tmpVec.addressVec();
   for (int i = 0; i < vec.size(); i++)
   {
      v.push_back(new DgAddress<DgQ2DDCoord>(DgQ2DDCoord(add.quadNum(),
                       *(ccFrame().getAddress(vec[i])))));
   }
   vec = tmpVec;

//cout << "D: " << vec << endl;

   vertexRF().convert(vec);

//cout << "E: " << vec << endl;
   // do we need to look for non-keepers?

   if (!isCongruent() && add.coord() == DgIVec2D(0, 0))
   {
      // we need to explicitly go to vertexRF to look for non-keepers
      // to clip

      // JFW: possible overflow: keepers is smaller than v.size() below:
      unsigned int keepers = 0;

      vector<DgAddressBase*>& v = vec.addressVec();
      for (unsigned long i = 0; i < v.size(); i++)
      {
         DgAddress<DgVertex2DDCoord>& fullAdd =
                   dynamic_cast< DgAddress<DgVertex2DDCoord>& >(*v[i]);
         DgVertex2DDCoord& add = fullAdd.address();
         if (add.keep())
         {
            if (i > keepers)
            {
               DgAddress<DgVertex2DDCoord>& fullAdd2 =
                   dynamic_cast< DgAddress<DgVertex2DDCoord>& >(*v[keepers]);
               DgVertex2DDCoord& add2 = fullAdd2.address();
               add2 = add;
            }
            keepers++;
         }
      }

      v.resize(keepers);
   }

   // now convert to the geoRF

//cout << "F: " << vec << endl;
   geoRF().convert(&vec);
//cout << "G: " << vec << endl;

   // Release the Kraken... I mean, the vector's pointers:
   dgg::util::release(v);

} // DgIDGG::setAddVertices

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/adjlon.cpp<|end_filename|>
/* reduce argument to range +/- PI */
#include <cmath>
#include "proj4.h"
/* note: PI adjusted high
** approx. true val:	3.14159265358979323844
*/
#define SPI		3.14159265359
	long double
adjlon (long double lon) {
	while ( std::fabs(lon) > SPI )
		lon += lon < 0. ? projTWOPI : -projTWOPI;
	return( lon );
}


<|start_filename|>src/DgIDGGS3H.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS3H.h: DgIDGGS3H class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIDGGS3H_H 
#define DGIDGGS3H_H

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgIDGGS.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgIDGGS3H : public DgIDGGS {

   public:

      DgIDGGS3H (DgRFNetwork& networkIn, const DgGeoSphRF& backFrameIn,
               const DgGeoCoord& vert0, long double azDegs, int nResIn = 1,
               const string& nameIn = "ISEA3H", const string& projType = "ISEA")
         : DgIDGGS (networkIn, backFrameIn, vert0, azDegs, 3, nResIn,
                "HEXAGON", nameIn, projType, false, 0, false) 
           { frequency_ = sqrt((long double) aperture()); }

      DgIDGGS3H (const DgIDGGS3H& rf);

     ~DgIDGGS3H (void);

      DgIDGGS3H& operator= (const DgIDGGS3H& rf);

      long double frequency (void) const { return frequency_; }

   protected:

      long double frequency_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgQ2DICoord>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgQ2DICoord>& add,
                                      DgLocVector& vec) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgPhysicalRFBase.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRFBase.h: DgPhysicalRFBase class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPHYSICALRFBASE_H
#define DGPHYSICALRFBASE_H

#include "DgDiscRF.h"
#include "DgBoundedRFBase.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
template<class C> class DgPhysicalRFBase {

   public:
   
      DgPhysicalRFBase (const DgBoundedRFBase& rfIn)
          : boundedRFBase_ (rfIn) { }
          
      virtual ~DgPhysicalRFBase (void);

      const DgBoundedRFBase& boundedRFBase (void) const 
                                 { return boundedRFBase_; }

      operator const DgBoundedRFBase& (void) const { return boundedRFBase(); }
      
      const DgRFBase& rfBase (void) const { return boundedRFBase().rf(); }
      
      bool operator== (const DgPhysicalRFBase<C>& rfIn) const
                            { return this == &rfIn; }

      bool operator!= (const DgPhysicalRFBase<C>& rfIn) const
                            { return !operator==(rfIn); }

      virtual void initAllCells (void); 

      virtual void initCell (C* cell, const DgLocation& loc) { }

      virtual C* getContents (const DgLocation& loc, bool convert = true,
                              bool allocate = false) const = 0;

      virtual void replaceContents (const DgLocation& loc, C* cont, 
                                    bool convert = true) = 0; // no copy

      virtual void setContents (const DgLocation& loc, const C& cont, 
                                bool convert = true) = 0; // makes copy

      virtual void deleteContents (const DgLocation& loc, 
                                   bool convert = true) = 0;

   private:
   
      const DgBoundedRFBase& boundedRFBase_;
};

#include "DgPhysicalRFBase_template.h"

#endif


<|start_filename|>src/DgOutGeoJSONFile.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutGeoJSONFile.h: DgOutGeoJSONFile class definitions
//
// Version 6.1 - <NAME>, 5/23/13
// - <NAME>, Added GeoJSON support, 10/4/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGOUTGEOJSONFILE_H
#define DGOUTGEOJSONFILE_H

#include <string>
#include <iostream>

#include "DgUtil.h"
#include "DgOutLocTextFile.h"

class DgDVec2D;
class DgPolygon;
class DgGeoSphDegRF;

class DgOutGeoJSONFile : public DgOutLocTextFile
{
   using DgOutLocFile::insert;

   public:

      DgOutGeoJSONFile(const DgGeoSphDegRF& rf,
         const std::string& filename = "", int precision = 7,
         bool isPointFile = false, DgReportLevel failLevel = DgBase::Fatal);

      ~DgOutGeoJSONFile();

      virtual void close(void) { ofstream::close(); }

      virtual DgOutLocFile& insert (DgLocation& loc, const string* label = NULL);
      virtual DgOutLocFile& insert (DgLocVector& vec, const string* label = NULL,
                                const DgLocation* cent = NULL);
      virtual DgOutLocFile& insert (DgPolygon& poly, const string* label = NULL,
                                const DgLocation* cent = NULL);

   protected:

      virtual DgOutLocFile& insert(const DgDVec2D& pt);

      virtual void setFormatStr(void)
      {
          ostringstream os;
          os << "[%#." << getPrecision() << "LF,"
             << "%#." << getPrecision() << "LF,0.0]";

          formatStr_ = os.str();
      }

   private:

      // GeoJSON helpers:
      void preamble();
      void postamble();
};

#endif


<|start_filename|>src/DgCell.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgCell.h: DgCell class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGCELL_H
#define DGCELL_H

#include <string>

#include "DgLocBase.h"
#include "DgLocation.h"
#include "DgPolygon.h"

////////////////////////////////////////////////////////////////////////////////
class DgCell : public DgLocBase {

   public:

      DgCell (void) : region_ (0) {}

      DgCell (const DgRFBase& rfIn, const string& labelIn, 
              const DgLocation& nodeIn, DgPolygon* regionIn = 0)
         : DgLocBase(rfIn), label_ (labelIn), node_ (nodeIn), 
           region_ (regionIn) 
      { rf().convert(&node_); if (hasRegion()) rf().convert(region_); }
  
     ~DgCell (void) { delete region_; }

      const string&     label  (void) const { return label_; }
      const DgLocation& node   (void) const { return node_; }
      const DgPolygon&  region (void) const { return *region_; }

      string&     label  (void) { return label_; }
      DgLocation& node   (void) { return node_; }
      DgPolygon&  region (void) { return *region_; }

      bool hasRegion (void) const { return (region_ != 0); }

      void setLabel (const string& labelIn) { label_ = labelIn; }

      virtual void setNode (const DgLocation& nodeIn)  
           { node_ = nodeIn; if (node_.rf() != rf()) rf().convert(&node_); }

      void setRegion (DgPolygon* regionIn) 
           { 
              delete region_;
              region_ = regionIn; 
              if (hasRegion() && region_->rf() != rf()) rf().convert(region_); 
           }

      DgCell& operator= (const DgCell& cell) // deep copy
      {
         if (this != &cell)
         {
            setLabel(cell.label());
            setNode(cell.node());
            if (cell.hasRegion()) 
            {
               DgPolygon* poly = new DgPolygon(cell.region());
               setRegion(poly);
            }
            else
               setRegion(0);
         }

	 return *this;
      }

      bool operator== (const DgCell& cell) const
           { return (cell.label() == label() && cell.node() == node() &&
              ((cell.hasRegion() && hasRegion() && cell.region() == region())
               || (!cell.hasRegion() && !hasRegion()))); }

      bool operator!= (const DgCell& cell) const
           { return !operator==(cell); }

      virtual string asString (void) const;
      virtual string asString (char delimiter) const;
      virtual string asAddressString (void) const;
      virtual string asAddressString (char delimiter) const;

      virtual const char* fromString (const char* str, char delimiter);

      virtual int cardinality (void) const 
           { return 1 + region().cardinality(); } 

      virtual void clearAddress (void) 
           { node_.clearAddress(); if (hasRegion()) region_->clearAddress(); }

   protected:

      virtual void convertTo (const DgRFBase& rf);

   private:

      string label_;
      DgLocation node_;
      DgPolygon* region_;

   friend class DgInArcGen;
};

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgCell& cell)
            { 
              stream << "[" << cell.label() << ":" << cell.node();
              if (cell.hasRegion()) stream << ":" << cell.region();
              return stream << endl; 
            }

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedRF2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedRF2D.cpp: DgBoundedRF2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <limits>
#include <cstdint>

#include "DgBoundedRF2D.h"
#include "DgDiscRF.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgBoundedRF2D::DgBoundedRF2D (const DgDiscRF<DgIVec2D, DgDVec2D, long double>& rf, 
                              const DgIVec2D& lowerLeftIn, 
                              const DgIVec2D& upperRightIn)
   : DgBoundedRF<DgIVec2D, DgDVec2D, long double> 
                    (rf, lowerLeftIn, upperRightIn, rf.undefAddress()),
     discRF_ (rf), lowerLeft_ (lowerLeftIn), upperRight_ (upperRightIn), 
     numI_ (upperRightIn.i() - lowerLeftIn.i() + 1), 
     numJ_ (upperRightIn.j() - lowerLeftIn.j() + 1)
{ 
   if (numI() <= 0 || numJ() <= 0)
   {
      report("DgBoundedRF2D::DgBoundedRF2D() invalid bounds", DgBase::Fatal);
   }

   size_ = numI() * numJ();
   if ((size_ / numI()) != static_cast<unsigned long>(numJ()))
   {
       report("DgBoundedRF2D::DgBoundedRF2D() invalid size setting due to "
              "possible overflow", DgBase::Warning);
       validSize_ = false;
   }
   else validSize_ = true;
   
} // DgBoundedRF2D::DgBoundedRF2D

////////////////////////////////////////////////////////////////////////////////
DgIVec2D&
DgBoundedRF2D::incrementAddress (DgIVec2D& add) const
{
   if (!validAddress(add)) return add = invalidAdd();
   else if (add == upperRight() || add == endAdd()) return add = endAdd();

   if (add.j() == upperRight().j())
   {
      add = DgIVec2D(add.i() + 1, lowerLeft().j());
   }
   else
   {
      add.setJ(add.j() + 1);
   }

   return add;

} // DgIVec2D& DgBoundedRF2D::incrementAddress

////////////////////////////////////////////////////////////////////////////////
DgIVec2D&
DgBoundedRF2D::decrementAddress (DgIVec2D& add) const
{
   if (!validAddress(add) || add == lowerLeft()) return add = invalidAdd();

   if (add.j() == lowerLeft().j())
   {
      add = DgIVec2D(add.i() - 1, upperRight().j());
   }
   else
   {
      add.setJ(add.j() - 1);
   }

   return add;

} // DgIVec2D& DgBoundedRF2D::decrementAddress

////////////////////////////////////////////////////////////////////////////////
std::uint64_t
DgBoundedRF2D::seqNumAddress (const DgIVec2D& add) const
{
   DgIVec2D tVec = add - lowerLeft();

   std::int64_t sNum = tVec.i() * numJ() + tVec.j();

   if (!zeroBased()) 
    sNum++;

   return sNum;
} // std::uint64_t DgBoundedRF2D::seqNumAddress

////////////////////////////////////////////////////////////////////////////////
DgIVec2D 
DgBoundedRF2D::addFromSeqNum (std::uint64_t sNum) const
{
   DgIVec2D res;

   if (!zeroBased()) 
    sNum--;

   res.setI(sNum / numJ());
   res.setJ(sNum % numJ());

   res += lowerLeft();

   return res;

} // DgIVec2D DgBoundedRF2D::addFromSeqNum

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgIDGGS.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS.cpp: DgIDGGS class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgIDGGS.h"
#include "DgIDGGS3H.h"
#include "DgIDGGS43H.h"
#include "DgIDGGS4H.h"
#include "DgIDGGS4D.h"
#include "DgIDGGS4T.h"
#include "DgSuperfund.h"

////////////////////////////////////////////////////////////////////////////////
const DgIDGGS*
DgIDGGS::makeRF (DgRFNetwork& network, const DgGeoSphRF& backFrame,
          const DgGeoCoord& vert0, long double azDegs, unsigned int apertureIn, 
          int nRes, const string& gridTopo, const string& name,
          const string& projTypeIn, bool isMixed43In, int numAp4In, 
          bool isSuperfundIn)
{
   DgIDGGS* dg0 = 0;

   string apErrStr = string("DgIDGGS::makeRF(): invalid aperture " +
                         dgg::util::to_string(apertureIn) +
                         string(" for grid topo ") + gridTopo);

   string theName = name;
   bool defaultName = (theName == string("IDGGS"));

   if (gridTopo == "HEXAGON")
   {
      if (!isMixed43In)
      {
         if (apertureIn == 4)
         {
            if (defaultName) theName = projTypeIn + string("4H");
            dg0 = new DgIDGGS4H(network, backFrame, vert0, azDegs, nRes, 
                          theName, projTypeIn);
         }
         else if (apertureIn == 3)
         {
            if (defaultName) theName = projTypeIn + string("3H");
            dg0 = new DgIDGGS3H(network, backFrame, vert0, azDegs, nRes, 
                          theName, projTypeIn);
         }
         else
            report(apErrStr, DgBase::Fatal);
      }
      else
      {
         if (defaultName) theName = projTypeIn + string("43H");
         dg0 = new DgIDGGS43H(network, backFrame, vert0, azDegs, nRes, theName,
                        projTypeIn, numAp4In, isSuperfundIn);
      }
   }
   else if (gridTopo == "DIAMOND")
   {
      if (apertureIn == 4)
      {
         if (defaultName) theName = projTypeIn + string("4D");
         dg0 = new DgIDGGS4D(network, backFrame, vert0, azDegs, nRes, 
                       theName, projTypeIn);
      }
      else
            report(apErrStr, DgBase::Fatal);
   }
   else if (gridTopo == "TRIANGLE")
   {
      if (apertureIn == 4)
      {
         if (defaultName) theName = projTypeIn + string("4T");
         dg0 = new DgIDGGS4T(network, backFrame, vert0, azDegs, nRes, 
                       theName, projTypeIn);
      }
      else
            report(apErrStr, DgBase::Fatal);
   }
   else
   {
      report("DgIDGGS::makeRF() invalid or unimplemented grid topology: " +
         gridTopo, DgBase::Fatal);
   }

   return dg0;

} // const DgIDGG& makeRF

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIDGGS::DgIDGGS (DgRFNetwork& network, const DgGeoSphRF& backFrame,
                  const DgGeoCoord& vert0, long double azDegs, 
                  unsigned int aperture, int nRes, const string& gridTopo, 
                  const string& name, const string& projType, bool isMixed43, 
                  int numAp4, bool isSuperfund)
        : DgDiscRFS<DgQ2DICoord, DgGeoCoord, long double> (network, backFrame, 
                  nRes, aperture, true, false, name),
          geoRF_ (backFrame), vert0_ (vert0), azDegs_ (azDegs),
          gridTopo_ (gridTopo), projType_ (projType), isMixed43_ (isMixed43),
          numAp4_ (numAp4), isSuperfund_ (isSuperfund)
{
   
   undefLoc_ = makeLocation(undefAddress());

   // create the DGGs

   for (int i = 0; i < nRes; i++)
   {
      if (!isSuperfund)
         (*grids_)[i] = new DgIDGG(backFrame, vert0, azDegs, aperture, i,
            "DDG", gridTopo, projType, isMixed43, numAp4, isSuperfund);
      else
         (*grids_)[i] = new DgIDGG(backFrame, vert0, azDegs, aperture, i,
            "DDG", gridTopo, projType, isMixed43, numAp4, isSuperfund,
            actualRes2sfRes(i));

      new Dg2WayResAddConverter<DgQ2DICoord, DgGeoCoord, long double> 
                                                   (*this, *(grids()[i]), i);
   }

   isAligned_ = idgg(0).isAligned();
   isCongruent_ = idgg(0).isCongruent();

} // DgIDGGS::DgIDGGS

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgPhysicalRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRF.h: DgPhysicalRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPHYSICALRF_H
#define DGPHYSICALRF_H

#include "DgPhysicalRFBase.h"
#include "DgBoundedRF.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
template<class A, class C, class B, class DB> class DgPhysicalRF 
                                      : public DgPhysicalRFBase<C> {

   public:

      DgPhysicalRF<A, C> (const DgBoundedRF<A, B, DB>& rfIn)
          : DgPhysicalRFBase<C> (rfIn), boundedRF_ (rfIn) { }

      const DgBoundedRF<A, B, DB>& boundedRF (void) const { return boundedRF_; }

      const DgDiscRF<A, B, DB>& discRF (void) const 
                { return boundedRF().discRF(); }
          
      virtual C* getContents (const DgLocation& loc, bool convert = true,
                              bool allocate = false) const;

      virtual void replaceContents (const DgLocation& loc, C* cont, 
                                       bool convert = true); // no copy

      virtual void setContents (const DgLocation& loc, const C& cont, 
                                bool convert = true); // makes copy

      virtual void deleteContents (const DgLocation& loc, bool convert = true);

      // pure virtual functions that must be defined by sub-classes
      
      virtual C* getAddContents (const A& add, bool allocate = false) const = 0;

      virtual void replaceAddContents (const A& add, C* cont) = 0;

      virtual void setAddContents (const A& add, const C& cont) = 0;

      virtual void deleteAddContents (const A& add) = 0;

   private:

      const DgBoundedRF<A, B, DB>& boundedRF_;

};

#include "DgPhysicalRF_template.h"

#endif


<|start_filename|>src/DgDVec3D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDVec3D.h: DgDVec3D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDVEC3D_H
#define DGDVEC3D_H

#include <cmath>
#include <iostream>

#include "DgDVec2D.h"
#include "DgString.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgDVec3D {

   public:

      static DgDVec3D midPoint (const DgDVec3D& pt1, const DgDVec3D& pt2)
                       { return pt1 * 0.5L + pt2 * 0.5L; }

      static DgDVec3D fracPoint (const DgDVec3D& pt1, const DgDVec3D& pt2, 
                                 long double fraction)
                       { return pt2 * fraction + pt1 * (1.0L - fraction); }

      static const DgDVec3D& undefDgDVec3D;

      DgDVec3D (void) { x_ = 0.0L; y_ = 0.0L; z_ = 0.0L; }

      DgDVec3D (long double x, long double y, long double z) { x_ = x; y_ = y; z_ = z; }

      DgDVec3D (const DgDVec3D& pt) : x_ (pt.x()), y_ (pt.y()), z_ (pt.z()) {}

      DgDVec3D (const DgDVec2D& pt) : x_ (pt.x()), y_ (pt.y()), z_ (0.0L) {}

      void setX (long double x) { x_ = x; }
      void setY (long double y) { y_ = y; }
      void setZ (long double z) { z_ = z; }

      long double distance (const DgDVec3D& pt) const
              { return (pt - *this).magnitude(); }

      long double x (void) const { return x_; }
      long double y (void) const { return y_; }
      long double z (void) const { return z_; }
      
      long double magnitude (void) const 
               { return sqrt(x_ * x_ + y_ * y_ + z_ * z_); }

      inline DgDVec3D& scale (long double xScaleFactor, long double yScaleFactor,
                              long double zScaleFactor);
      //inline DgDVec3D& rotate (long double degrees);

      //inline operator XPoint   (void) const;
      inline operator string (void) const;

      inline DgDVec3D& operator=  (const DgDVec3D& pt);
      inline DgDVec3D& operator=  (const DgDVec2D& pt);
      inline DgDVec3D& operator+= (const DgDVec3D& pt);
      inline DgDVec3D& operator-= (const DgDVec3D& pt);

      inline DgDVec3D& operator*= (long double scaleFactor);
      inline DgDVec3D& operator/= (long double scaleFactor);

      friend DgDVec3D operator*  (const DgDVec3D& pt, long double scaleFactor);
      friend DgDVec3D operator*  (long double scaleFactor, const DgDVec3D& pt);
      friend DgDVec3D operator+  (const DgDVec3D& pt1, const DgDVec3D& pt2);
      friend DgDVec3D operator-  (const DgDVec3D& pt1, const DgDVec3D& pt2);

      friend bool operator== (const DgDVec3D& pt1, const DgDVec3D& pt2);
      friend bool operator!= (const DgDVec3D& pt1, const DgDVec3D& pt2);
      friend bool operator<  (const DgDVec3D& pt1, const DgDVec3D& pt2);
      friend bool operator<= (const DgDVec3D& pt1, const DgDVec3D& pt2);
      friend bool operator>  (const DgDVec3D& pt1, const DgDVec3D& pt2);
      friend bool operator>= (const DgDVec3D& pt1, const DgDVec3D& pt2);

      friend ostream& operator<< (ostream& stream, const DgDVec3D& pt);

   private:

      long double x_;
      long double y_;
      long double z_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::scale (long double xScaleFactor, long double yScaleFactor, long double zScaleFactor)
//
// Scale me by xScaleFactor in the x direction, yScaleFactor in the y
// direction, and zScaleFactor in the z direction.
//
////////////////////////////////////////////////////////////////////////////////
{
   x_ *= xScaleFactor;
   y_ *= yScaleFactor;
   z_ *= zScaleFactor;

   return *this;

} // void DgDVec3D::scale

/*
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::rotate (long double degrees)
//
// Rotate me about the origin degrees degrees in a counter-clockwise
// direction.
//
////////////////////////////////////////////////////////////////////////////////
{
   if (fabs(degrees - 0.0L) < M_EPSILON) return *this;

   long double rotAng = degrees * dgM_PI_180;
   long double cosAng = cos(rotAng);
   long double sinAng = sin(rotAng);
   long double x = x_;
   long double y = y_;

   x_ = x * cosAng - y * sinAng;
   y_ = x * sinAng + y * cosAng;

   return *this;

} // void DgDVec3D::rotate
*/

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D::operator string (void) const
{
   return "(" + dgg::util::to_string(x_) + ", " + dgg::util::to_string(y_) + ", " + dgg::util::to_string(z_) + ")";

} // DgDVec3D::operator string

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::operator= (const DgDVec3D& pt)
{
   if (&pt != this)
   {
      x_ = pt.x_;
      y_ = pt.y_;
      z_ = pt.z_;
   }
   return *this;

} // DgDVec3D& DgDVec3D::operator=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::operator= (const DgDVec2D& pt)
{
   x_ = pt.x();
   y_ = pt.y();
   z_ = 0.0L;

   return *this;

} // DgDVec3D& DgDVec3D::operator=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::operator*= (long double scaleFactor)
{
   scale(scaleFactor, scaleFactor, scaleFactor);

   return *this;

} // DgDVec3D& DgDVec3D::operator*=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::operator/= (long double scaleFactor)
{
   x_ /= scaleFactor;
   y_ /= scaleFactor;
   z_ /= scaleFactor;

   return *this;

} // DgDVec3D& DgDVec3D::operator/=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::operator+= (const DgDVec3D& pt)
{
   x_ += pt.x_;
   y_ += pt.y_;
   z_ += pt.z_;

   return *this;

} // DgDVec3D& DgDVec3D::operator+=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D&
DgDVec3D::operator-= (const DgDVec3D& pt)
{
   x_ -= pt.x_;
   y_ -= pt.y_;
   z_ -= pt.z_;

   return *this;

} // DgDVec3D& DgDVec3D::operator-=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D
operator* (const DgDVec3D& pt, long double scaleFactor)
{
   DgDVec3D result(pt);
   result.scale(scaleFactor, scaleFactor, scaleFactor);

   return result;

} // DgDVec3D operator*

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D
operator* (long double scaleFactor, const DgDVec3D& pt)
{
   DgDVec3D result(pt);
   result.scale(scaleFactor, scaleFactor, scaleFactor);

   return result;

} // DgDVec3D operator*

////////////////////////////////////////////////////////////////////////////////
inline bool
operator== (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   return (pt1.x_ == pt2.x_ && pt1.y_ == pt2.y_ && pt1.z_ == pt2.z_);

} // bool operator==

////////////////////////////////////////////////////////////////////////////////
inline bool
operator!= (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   return !operator==(pt1, pt2);

} // bool operator!=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator> (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   return (pt1.x_ > pt2.x_ && pt1.y_ > pt2.y_ && pt1.z_ > pt2.z_);

} // bool operator>

////////////////////////////////////////////////////////////////////////////////
inline bool
operator>= (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   return (pt1.x_ >= pt2.x_ && pt1.y_ >= pt2.y_ && pt1.z_ >= pt2.z_);

} // bool operator>=

////////////////////////////////////////////////////////////////////////////////
inline bool
operator< (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   return (pt1.x_ < pt2.x_ && pt1.y_ < pt2.y_ && pt1.z_ < pt2.z_);

} // bool operator<

////////////////////////////////////////////////////////////////////////////////
inline bool
operator<= (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   return (pt1.x_ <= pt2.x_ && pt1.y_ <= pt2.y_ && pt1.z_ <= pt2.z_);

} // bool operator<=

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D
operator+ (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   DgDVec3D result(pt1);
   result += pt2;

   return result;

} // DgDVec3D operator+

////////////////////////////////////////////////////////////////////////////////
inline DgDVec3D
operator- (const DgDVec3D& pt1, const DgDVec3D& pt2)
{
   DgDVec3D result(pt1);
   result -= pt2;

   return result;

} // DgDVec3D operator-

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgDVec3D& pt)
{
   return stream << string(pt);

} // ostream& operator<<

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgString.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgString.h: DgString class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSTRING_H
#define DGSTRING_H

#include <string>
#include <cstdio>
#include <sstream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <cstdint>
#include <sstream>
#include <stdexcept>

#include "DgUtil.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
// string comparison operators

inline bool operator== (const string& s1, const string& s2)
{ return (s1.compare(s2) == 0); }

inline bool operator!= (const string& s1, const string& s2)
{ return (s1.compare(s2) != 0); }

inline bool operator< (const string& s1, const string& s2)
{ return (s1.compare(s2) < 0); }

inline bool operator<= (const string& s1, const string& s2)
{ return (s1.compare(s2) <= 0); }

inline bool operator> (const string& s1, const string& s2)
{ return (s1.compare(s2) > 0); }

inline bool operator>= (const string& s1, const string& s2)
{ return (s1.compare(s2) >= 0); }

inline bool operator== (const string& s1, const char* s2)
{ return (s1 == string(s2)); }

inline bool operator!= (const string& s1, const char* s2)
{ return (s1 != string(s2)); }

inline bool operator< (const string& s1, const char* s2)
{ return (s1 < string(s2)); }

inline bool operator<= (const string& s1, const char* s2)
{ return (s1 <= string(s2)); }

inline bool operator> (const string& s1, const char* s2)
{ return (s1 > string(s2)); }

inline bool operator>= (const string& s1, const char* s2)
{ return (s1 >= string(s2)); }

inline bool operator== (const char* s1, const string& s2)
{ return (string(s1) == s2); }

inline bool operator!= (const char* s1, const string& s2)
{ return (string(s1) != s2); }

inline bool operator< (const char* s1, const string& s2)
{ return (string(s1) < s2); }

inline bool operator<= (const char* s1, const string& s2)
{ return (string(s1) <= s2); }

inline bool operator> (const char* s1, const string& s2)
{ return (string(s1) > s2); }

inline bool operator>= (const char* s1, const string& s2)
{ return (string(s1) >= s2); }

////////////////////////////////////////////////////////////////////////////////
inline string toLower (const string& strIn)
{
   std::string ret(strIn);
   std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
   return ret;
}

////////////////////////////////////////////////////////////////////////////////
namespace dgg { namespace util {

////////////////////////////////////////////////////////////////////////////////
inline string addCommas (std::uint64_t num)
{
    std::stringstream ss;
    ss << num;
    string s = ss.str();

    string newS = "";
    if (s.length() <= 3)
       newS = s;
    else
    {
       int offset = s.length() % 3; // adjust for different # of digits
    
       for (unsigned int i = 0; i < s.length(); i++)
       {
          if (i && !(i % 3 - offset))
             newS += ",";
          newS += s[i];
       }
   }

   return newS;
}

////////////////////////////////////////////////////////////////////////////////
inline string addCommas (long double num, unsigned int precision)
{
   std::uint64_t intPart = num;

   string newS = addCommas(intPart);

   std::stringstream ss;
   ss << std::fixed << setprecision(precision) << num;
   string s = ss.str();
   size_t ptNdx = s.find_first_of('.');

   if (ptNdx != string::npos)
      newS += s.substr(ptNdx, s.length() - ptNdx);

   return newS;
}

/* Strip away trailing and leading \r\n (no perfect forwarding in C++03!): */
inline void trim(std::string& line, const std::string& candidates = "\n\r")
{
 // Tail:
 size_t pos;
 while(std::string::npos != (pos = candidates.find(line[line.size() - 1])))
  line.erase(line.size() - 1);

 size_t i = 0;

 // Shift ahead to the first non-match:
 for(; std::string::npos != (pos = candidates.find(line[i])); ++i)
  ;

 line.erase(0, i);	// ...and, erase to there.
}

inline void trim(char *line, const std::string& candidates = "\n\r")
{
 // Again, this could be made more efficient, when there's a need:

 size_t len	= std::strlen(line),
        pos	= 0,
        i	= 0;

 while(std::string::npos != (pos = candidates.find(line[len - 1])))
  {
	line[len - 1] = 0;
	--len;
  }

 /* Here, we find the first non-candidate character in the string, starting at the head. Then,
 we shift the remainder of the string left: */
 while(std::string::npos != candidates.find(line[i]))
  ++i;

 // Shift left:
 memcpy(static_cast<void *>(line), static_cast<void *>(&line[i]), len - i); 
 
 line[len - i] = 0;	// add NULL
}

template <class TargetT>
inline TargetT from_string(const std::string& source)
{
 TargetT result;

 std::istringstream os(source);

 os >> result;

 return result;
}

#define GCC_VERSION (__GNUC__ * 10000 \
                               + __GNUC_MINOR__ * 100 \
                               + __GNUC_PATCHLEVEL__)

// JFW: clean up (gcc specific)
template <>
inline
std::int64_t from_string(const std::string& source)
{
 std::int64_t n;
  std::istringstream convert(source);
  convert>>n;
  if(convert.fail())
    throw std::runtime_error("from_string(): Conversion failed on: " + source);
 return n;
}

// JFW: clean up (gcc specific)
template <>
inline 
std::uint64_t from_string(const std::string& source)
{ 
 std::uint64_t n;
  std::istringstream convert(source);
  convert>>n;
  if(convert.fail())
    throw std::runtime_error("from_string(): Conversion failed on: " + source);
 return n;
}

template <class SourceT>
std::string to_string(const SourceT& source)
{
 std::ostringstream os;
 os << source;
 return os.str();
}

// JFW: We should tidy all of this up later:
inline std::string to_string(long double val, const char *formatStr)
{
   char buffer[50];

   sprintf(buffer, formatStr, val);

   return string(buffer);
}

inline std::string to_string(int val, int padWidth)
{
 std::ostringstream os;
 os << std::setw(padWidth) << std::setfill('0') << val;
 return os.str();
}

}} // namespace dgg::util

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgTriGrid2DS.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgTriGrid2DS.cpp: DgTriGrid2DS class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <cstdint>

#include "DgContCartRF.h"
#include "DgIVec2D.h"
#include "DgDiscRF.h"
#include "DgTriGrid2D.h"
#include "DgTriGrid2DS.h"

////////////////////////////////////////////////////////////////////////////////
DgTriGrid2DS::DgTriGrid2DS (DgRFNetwork& networkIn, 
               const DgRF<DgDVec2D, long double>& backFrameIn, int nResIn, 
               unsigned int apertureIn, bool isCongruentIn, bool isAlignedIn,
               const string& nameIn)
        : DgDiscRFS2D (networkIn, backFrameIn, nResIn, apertureIn, 
                       isCongruentIn, isAlignedIn, nameIn) 
{ 
   if (!isCongruent())
   {
      report("DgTriGrid2DS::DgTriGrid2DS() only congruent triangle grid "
             "systems implemented", DgBase::Fatal);
   }

   // determine the radix

   radix_ = static_cast<int>(sqrt(static_cast<float>(aperture())));
   if (static_cast<unsigned int>(radix() * radix()) != aperture())
   {
      report( "DgTriGrid2DS::DgTriGrid2DS() aperture must be a perfect square",
       DgBase::Fatal);
   }

   // do the grids

   long double fac = sqrt(3.0); // scale so e == 1

   DgDVec2D trans;
   trans = DgDVec2D(-sqrt(3.0) / 2.0, -0.5);

   for (int i = 0; i < nRes(); i++)
   {
      string newName = name() + "_" + dgg::util::to_string(i);

      //cout << newName << " " << fac << ' ' << trans << endl;

      DgContCartRF* ccRF = new DgContCartRF(network(), newName + string("bf"));

      new Dg2WayContAffineConverter(backFrame(), *ccRF, (long double) fac, 0.0, 
                                    trans); 

      (*grids_)[i] = new DgTriGrid2D(network(), *ccRF, newName);
      new Dg2WayResAddConverter<DgIVec2D, DgDVec2D, long double>
                                                  (*this, *(grids()[i]), i);

      fac *= radix();
   }

} // DgTriGrid2DS::DgTriGrid2DS

////////////////////////////////////////////////////////////////////////////////
DgTriGrid2DS::DgTriGrid2DS (const DgTriGrid2DS& rf) 
  : DgDiscRFS2D (rf)
{
   report("DgTriGrid2DS::operator=() not implemented yet", DgBase::Fatal);

} // DgTriGrid2DS::DgTriGrid2DS

////////////////////////////////////////////////////////////////////////////////
DgTriGrid2DS::~DgTriGrid2DS (void)
{
   for (unsigned long i = 0; i < grids().size(); i++) 
    delete (*grids_)[i]; 

   delete grids_;

} // DgTriGrid2DS::~DgTriGrid2DS

////////////////////////////////////////////////////////////////////////////////
DgTriGrid2DS&
DgTriGrid2DS::operator= (const DgTriGrid2DS& rf)
{
   report("DgTriGrid2DS::operator=() ", DgBase::Fatal);

   return *this;

} // DgTriGrid2DS& DgTriGrid2DS::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgTriGrid2DS::setAddParents (const DgResAdd<DgIVec2D>& add, 
                               DgLocVector& vec) const
{
//cout << "   setAddParents: " << add << endl;
   if (isCongruent())
   {
      DgLocation* tmpLoc = makeLocation(add);
      grids()[add.res() - 1]->convert(tmpLoc);
      convert(tmpLoc);

      vec.push_back(*tmpLoc);

      delete tmpLoc;
   }
   else
   {
      report("DgTriGrid2DS::DgTriGrid2DS() only congruent triangle grid "
             "systems implemented", DgBase::Fatal);
   }

} // void DgTriGrid2DS::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgTriGrid2DS::setAddInteriorChildren (const DgResAdd<DgIVec2D>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent())
   {
//cout << "Children: " << add << " " << lowerLeft << endl;

      vector<DgAddressBase*>& v = vec.addressVec();

      if (DgTriGrid2D::isUp(add.address()))
      {
         const DgIVec2D lowerLeft((add.address().i() * radix()),
                                  (add.address().j() * radix()));

         std::int64_t maxJ = 0;
         for (int i = 0; i < radix(); i++)
         {
            for (std::int64_t j = 0; j <= maxJ; j++)
            {
               v.push_back(new DgAddress< DgResAdd<DgIVec2D> >(
                           DgResAdd<DgIVec2D>(DgIVec2D(lowerLeft.i() + i, 
                                lowerLeft.j() + j), add.res() + 1)));
            }
            maxJ += 2;
         }
      }
      else // down pointing
      {
         const DgIVec2D upperRight((add.address().i() * radix() + radix() - 1),
                                   (add.address().j() * radix() + radix() - 1));

         std::int64_t maxJ = 0;
         for (int i = 0; i < radix(); i++)
         {
            for (std::int64_t j = 0; j <= maxJ; j++)
            {
               v.push_back(new DgAddress< DgResAdd<DgIVec2D> >(
                           DgResAdd<DgIVec2D>(DgIVec2D(upperRight.i() - i, 
                                upperRight.j() - j), add.res() + 1)));
            }
            maxJ += 2;
         }
      }
   }
   else
   {
      report("DgTriGrid2DS::DgTriGrid2DS() only congruent triangle grid "
             "systems implemented", DgBase::Fatal);
   }
//cout << vec << endl;
   
} // void DgTriGrid2DS::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgTriGrid2DS::setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent())
   {
      // no boundary children in this topology; leave vec empty
   }
   else
   {
      report("DgTriGrid2DS::DgTriGrid2DS() only congruent triangle grid "
             "systems implemented", DgBase::Fatal);
   }

} // void DgTriGrid2DS::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgTriGrid2DS::setAddAllChildren (const DgResAdd<DgIVec2D>& add, 
                                   DgLocVector& vec) const
{
   setAddInteriorChildren(add, vec);

} // void DgTriGrid2DS::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgOutAIGenFile.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutAIGenFile.cpp: DgOutAIGenFile class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <list>
#include <sstream>

#include "DgOutAIGenFile.h"
#include "DgLocList.h"
#include "DgPolygon.h"
#include "DgLocation.h"
#include "DgCell.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutAIGenFile::DgOutAIGenFile (const DgRFBase& rfIn, const string& fileNameIn, 
                          int precision, bool isPointFile,
                          DgReportLevel failLevel)
   : DgOutLocTextFile (fileNameIn, rfIn, isPointFile, "gen", precision, 
                       failLevel)
{
   if (rfIn.vecAddress(DgDVec2D(M_ZERO, M_ZERO)) == 0)
   {
      DgOutputStream::report("DgOutAIGenFile::DgOutAIGenFile(): RF " + rfIn.name() +
             " must override the vecAddress() method", DgBase::Fatal);
   }

   setFormatStr();

} // DgOutAIGenFile::DgOutAIGenFile

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutAIGenFile::insert (const DgDVec2D& pt)
//
// Put the point pt.
//
////////////////////////////////////////////////////////////////////////////////
{
   const int maxBuffSize = 200;
   char buff[maxBuffSize];

   sprintf(buff, formatStr(), pt.x(), pt.y());

   *this << buff;

   return *this;

} // DgOutLocFile& DgOutAIGenFile::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutAIGenFile::insert (DgLocation& loc, const string* label)
//
// Put the point loc.
//
////////////////////////////////////////////////////////////////////////////////
{
   rf().convert(&loc);

   if (label)
     *this << *label << " ";
   else
     *this << "0 ";

   this->insert(rf().getVecLocation(loc));

   return *this;

} // DgOutLocFile& DgOutAIGenFile::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutAIGenFile::insert (DgLocVector& vec, const string* label, 
                     const DgLocation* cent)
//
// Put the polyline vec.
//
////////////////////////////////////////////////////////////////////////////////
{
   rf().convert(vec);

   // output the header line
   if (label)
     *this << *label;
   else
     *this << "0";

   if (cent)
   {
      *this << " ";
      this->insert(rf().getVecLocation(*cent));
   }
   else
      *this << "\n";

   // output the vertices
   const vector<DgAddressBase*>& v = vec.addressVec();
   for (unsigned long i = 0; i < v.size(); i++) 
      this->insert(rf().getVecAddress(*v[i]));

   *this << "END" << endl;

   return *this;

} // DgOutLocFile& DgOutAIGenFile::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutAIGenFile::insert (DgPolygon& poly, const string* label, 
                     const DgLocation* cent)
//
// Put the polygon poly.
//
////////////////////////////////////////////////////////////////////////////////
{
   rf().convert(poly);

   // output the header line
   if (label)
     *this << *label;
   else
     *this << "0";

   if (cent)
   {
      *this << " ";
      this->insert(rf().getVecLocation(*cent));
   }
   else
      *this << "\n";

   // output the vertices in reverse order (clockwise winding)
   const vector<DgAddressBase*>& v = poly.addressVec();
   for (int i = (int) (v.size() - 1); i >= 0; i--) 
      this->insert(rf().getVecAddress(*v[i]));
   
   // rewrite the first vertex
   this->insert(rf().getVecAddress(*v[v.size() - 1]));

   *this << "END" << endl;

   return *this;

} // DgOutLocFile& DgOutAIGenFile::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgLocation.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgLocation.h: DgLocation class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGLOCATION_H
#define DGLOCATION_H

#include <string>
#include <iostream>

#include "DgLocBase.h"
#include "DgAddressBase.h"
#include "DgRFBase.h"

using namespace std;

class DgDistanceBase;

////////////////////////////////////////////////////////////////////////////////
class DgLocation : public DgLocBase {

   public:

      DgLocation (void) : address_ (0) { }

      DgLocation (const DgLocation& loc) 
         : DgLocBase (loc.rf()), 
           address_ (loc.rf().createAddress(*loc.address())) { } 

      DgLocation (const DgRFBase& rfIn) : DgLocBase (rfIn), address_ (0) { }

     ~DgLocation (void);

      DgLocation& operator= (const DgLocation& loc);

      bool operator== (const DgLocation& loc) const
            { return (rf() == loc.rf() &&
                      rf().equalAddress(*address(), *loc.address())); }

      bool operator!= (const DgLocation& loc) const
            { return !operator==(loc); }

      DgDistanceBase* distance (const DgLocation& loc, 
                                bool convert = false) const
               { return rf().distance(*this, loc, convert); }

      virtual string asString (void) const 
               { return rf().toString(*this); }

      virtual string asString (char delimiter) const 
               { return rf().toString(*this, delimiter); }

      virtual string asAddressString (void) const
               { return rf().toAddressString(*this); }

      virtual string asAddressString (char delimiter) const
               { return rf().toAddressString(*this, delimiter); }

      virtual const char* fromString (const char* str, char delimiter) 
               { return rf().fromString(*this, str, delimiter); }

      const DgAddressBase*  address  (void) const { return address_; }

      bool isUndefined (void) const { return operator==(rf().undefLoc()); }

      void setNullAddress (void) { address_ = 0; }

      virtual void clearAddress (void) { delete address_; address_ = 0; }
      
      DgLocation (const DgRFBase& rfIn, DgAddressBase* addIn) : DgLocBase (rfIn), address_ (addIn) {}

   protected:

      virtual void convertTo (const DgRFBase& rf) { rf.convert(this); }


   private:

      DgAddressBase* address_;

   friend class DgRFBase;
   friend class DgConverterBase;
   friend class DgLocVector;

};

////////////////////////////////////////////////////////////////////////////////
inline DgLocation& 
DgLocation::operator= (const DgLocation& loc)
{
   if (this != &loc)
   {
      delete address_;
      
      rf_ = &loc.rf();
      address_ = loc.rf().createAddress(*loc.address());
   }

   return *this;

} // DgLocation& DgLocation::operator=

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedRFS2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedRFS2D.cpp: DgBoundedRFS2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <limits>
#include <cstdint>

#include "DgBoundedRFS2D.h"
#include "DgBoundedHexC2RF2D.h"
#include "DgDiscRFS2D.h"
#include "DgTriGrid2DS.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgBoundedRFS2D::DgBoundedRFS2D (const DgDiscRFS2D& rf, 
                                const DgIVec2D& lowerLeft0, 
                                const DgIVec2D& upperRight0)
   : DgBoundedRF< DgResAdd<DgIVec2D>, DgDVec2D, long double > (rf, 
                  DgResAdd<DgIVec2D> (DgIVec2D(0, 0), 0),
                  DgResAdd<DgIVec2D> (DgIVec2D(0, 0), 0), rf.undefAddress()), 
     discRFS_ (rf)
{ 
   // check to see if current limitations are met

   if (lowerLeft0 != DgIVec2D(0, 0))
   {
      report("DgBoundedRFS2DS::DgBoundedRFS2DS() only lowerLeft0 = (0, 0) "
             "supported", DgBase::Fatal);
   }

   // allocate the grids

   grids_ = new vector<DgBoundedRF2D*>(discRFS().nRes());

   int totTicks = 1;
   std::int64_t numI = upperRight0.i() + 1;
   std::int64_t numJ = upperRight0.j() + 1;
   if (rf.aperture() == 3) // better be hex!
   {
      for (int i = 0; i < discRFS().nRes(); i++)
      {
         bool isClassI = !(i % 2);
         if (isClassI)
         {
            (*grids_)[i] = new DgBoundedRF2D(*rf.grids()[i], DgIVec2D(0, 0),
                      DgIVec2D(totTicks * numI - 1, totTicks * numJ - 1));

            totTicks *= 3;
         }
         else
         {
            (*grids_)[i] = new DgBoundedHexC2RF2D(*rf.grids()[i], 
                                DgIVec2D(0, 0), DgIVec2D(totTicks * numI - 1, 
                                                         totTicks * numJ - 1));
         }
      }
   }
   else
   {
      // check that the aperture is a perfect square

      int sqrtApp = static_cast<int>(sqrt(static_cast<float>(rf.aperture())));
      if (static_cast<unsigned int>(sqrtApp * sqrtApp) != rf.aperture())
      {
         report("DgBoundedRFS2DS::DgBoundedRFS2DS() aperture " + 
                dgg::util::to_string(rf.aperture()) + " is not a perfect square",
                DgBase::Fatal);
      }

      for (int i = 0; i < discRFS().nRes(); i++)
      {
         (*grids_)[i] = new DgBoundedRF2D(*rf.grids()[i], DgIVec2D(0, 0),
                DgIVec2D(totTicks * numI - 1, totTicks * numJ - 1));

/*
         cout << "grid " << i << endl;
         for (DgIVec2D c = (*grids_)[i]->lowerLeft(); 
              c != (*grids_)[i]->invalidAdd();         
              c = (*grids_)[i]->incrementAddress(c)) cout << c << endl;
*/

         totTicks *= sqrtApp;
      }
   }

   // set the correct last address

   int maxRes = discRFS().nRes() - 1;
   DgResAdd<DgIVec2D> last((*grids_)[maxRes]->lastAdd(), maxRes);

   setLastAdd(last);

   // set the size

   size_ = 0;
   for (int i = 0; i < discRFS().nRes(); i++)
   {
      std::uint64_t lastSize = size_;

      const DgBoundedRF2D* g = (*grids_)[i];

      if (g->validSize()) size_ += g->size();

      if (!g->validSize() || size() < lastSize)
      {
         report("DgBoundedRFS2D::DgBoundedRFS2D() invalid size setting due to "
                "possible overflow", DgBase::Warning);
         validSize_ = false;
      }
   }

   validSize_ = true;

} // DgBoundedRFS2D::DgBoundedRFS2D

////////////////////////////////////////////////////////////////////////////////
DgResAdd<DgIVec2D>&
DgBoundedRFS2D::incrementAddress (DgResAdd<DgIVec2D>& add) const
{
   if (!validAddress(add)) return add = invalidAdd();
   else if (add == lastAdd()) return add = endAdd();
   else if (add == endAdd()) return add;

   const DgBoundedRF2D& grid = *(grids()[add.res()]);

   DgIVec2D v(add.address());
   add = DgResAdd<DgIVec2D>(grid.incrementAddress(v), add.res());

   if (add.address() == grid.endAdd())
   {
      if (add.res() == (discRFS().nRes() - 1)) return add = endAdd();
      else 
      {
         int newRes = add.res() + 1;
         add = DgResAdd<DgIVec2D>(grids()[newRes]->firstAdd(), newRes);
      }
   }

   return add;

/*
   if (add.address() == grid.lastAdd() ||
       add.address() == grid.endAdd())
   {
      if (add.res() == (discRFS().nRes() - 1)) return add = endAdd();
      else 
      {
         int newRes = add.res() + 1;
         return add = DgResAdd<DgIVec2D>(grids()[newRes]->firstAdd(), newRes);
      }
   }
   else
   {
      DgIVec2D v(add.address());
      return add = DgResAdd<DgIVec2D>(grid.incrementAddress(v), add.res());
   }
*/

} // DgResAdd<DgIVec2D>& DgBoundedRFS2D::incrementAddress

////////////////////////////////////////////////////////////////////////////////
DgResAdd<DgIVec2D>&
DgBoundedRFS2D::decrementAddress (DgResAdd<DgIVec2D>& add) const
{
   if (!validAddress(add) || add == firstAdd()) return add = invalidAdd();

   const DgBoundedRF2D& grid = *(grids()[add.res()]);

   if (add.address() == grid.firstAdd())
   {
      int newRes = add.res() - 1;
      return add = DgResAdd<DgIVec2D>(grids()[newRes]->lastAdd(), newRes);
   }
   else
   {
      DgIVec2D v(add.address());
      return add = DgResAdd<DgIVec2D>(grid.decrementAddress(v), add.res());
   }

} // DgResAdd<DgIVec2D>& DgBoundedRFS2D::decrementAddress

////////////////////////////////////////////////////////////////////////////////
std::uint64_t 
DgBoundedRFS2D::seqNumAddress (const DgResAdd<DgIVec2D>& add) const
{
   if (!validSize())
   {
      report("DgBoundedRFS2D::seqNumAddress() valid size required",
             DgBase::Fatal);
      return 0;
   }

   std::uint64_t sNum = 0;
   if (!zeroBased()) sNum++;

   for (int i = 0; i < add.res(); i++) sNum += (*grids_)[i]->size();

   sNum += (*grids_)[add.res()]->seqNumAddress(add.address());

   return sNum;

} // std::uint64_t DgBoundedRFS2D::seqNumAddress

////////////////////////////////////////////////////////////////////////////////
DgResAdd<DgIVec2D> 
DgBoundedRFS2D::addFromSeqNum (std::uint64_t sNum) const
{
   if (!validSize())
   {
      report("DgBoundedRFS2D::seqNumAddress() valid size required",
             DgBase::Fatal);
      return DgResAdd<DgIVec2D>();
   }

   if (!zeroBased()) sNum--;

   DgResAdd<DgIVec2D> tmp;
   std::uint64_t n = sNum;
   tmp.setRes(0);

   int r;
   for (r = 0; r < discRFS().nRes(); r++)
   {
      tmp.setRes(r);

      if (n < (*grids_)[r]->size()) break;

      n -= (*grids_)[r]->size();
   }

   if (r == discRFS().nRes()) return invalidAdd();

   tmp.setAddress((*grids_)[tmp.res()]->addFromSeqNum(n));

   return tmp;

} // DgResAdd<DgIVec2D> DgBoundedRFS2D::addFromSeqNum

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgInAIGenFile.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgInAIGenFile.h: DgInAIGenFile class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGINAIGENFILE_H
#define DGINAIGENFILE_H

#include "DgInLocTextFile.h"

class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgInAIGenFile : public DgInLocTextFile {

   public:

      DgInAIGenFile (const DgRFBase& rfIn, const string* fileNameIn = NULL,
                        DgReportLevel failLevel = DgBase::Fatal);

      bool forcePolyLine (void) const { return forcePolyLine_; }
      bool forceCells    (void) const { return forceCells_; }

      void setForcePolyLine (bool forcePolyLine = false)
                 { forcePolyLine_ = forcePolyLine; }

      void setForceCells (bool forceCells = false)
                 { forceCells_ = forceCells; }

      virtual DgInLocFile& extract (DgLocList& list);
      virtual DgInLocFile& extract (DgLocVector& vec);
      virtual DgInLocFile& extract (DgPolygon& poly);
      virtual DgInLocFile& extract (DgLocation& loc);
      virtual DgInLocFile& extract (DgCell& cell);

   private:
      
      bool forcePolyLine_;
      bool forceCells_;

};

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRF.h: DgRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGRF_H
#define DGRF_H

#include <string>
#include <vector>
#include <iostream>
#include <cstdint>

#include "DgRFBase.h"
#include "DgAddress.h"

using namespace std;

class DgConverterBase;
class DgLocation;

////////////////////////////////////////////////////////////////////////////////
template <class A, class D> class DgRF : public DgRFBase {

   public:

      virtual ~DgRF (void);

      DgRF (DgRFNetwork& networkIn, const string& nameIn)
         : DgRFBase (networkIn, nameIn) { }

      DgRF (const DgRF& rf) : DgRFBase (rf) { }

      DgRF& operator= (const DgRF& rf)
          { DgRFBase::operator=(rf); return *this; }

      virtual DgLocation* createLocation (const DgLocation& loc,
                                          bool convert = false) const;

      virtual DgLocation* makeLocation (const A& addIn) const;

      virtual DgDistanceBase* distance (const DgLocation& loc1, 
                                        const DgLocation& loc2,
                                        bool convert = false) const;

      const A* getAddress (const DgLocation& loc) const;

      void buildLocVector (DgLocVector* vec, vector<A*> inVec) const; 

      D getDistance (const DgDistanceBase& dist) const;

      virtual string toString (const DgLocation&     loc)    const;
      virtual string toString (const DgLocVector&    locVec) const;
      virtual string toString (const DgDistanceBase& dist)   const;
      virtual long double toDouble (const DgDistanceBase& dist)   const;
      
      virtual std::uint64_t toInt (const DgDistanceBase& dist) const;

      virtual string toAddressString (const DgLocation&  loc)    const;
      virtual string toAddressString (const DgLocVector& locVec) const;

      virtual string toString (const DgLocation& loc, char delimiter) const;
      virtual string toString (const DgLocVector& loc, char delimiter) const;
      virtual string toAddressString (const DgLocation& loc, char delimiter) 
                                                                         const;
      virtual string toAddressString (const DgLocVector& locVec, char delimiter)
                                                                         const;

      virtual const char* fromString (DgLocation& loc, const char* str, 
                                      char delimiter) const;

      virtual void jumpRF (DgLocation* loc);
      
      // these are the pure virtual functions which subclasses need to define

      virtual D dist (const A& add1, const A& add2) const = 0;

      virtual string add2str  (const A& add)  const = 0;
      virtual string add2str  (const A& add, char delimiter)  const = 0;

      virtual string dist2str (const D& dist) const = 0;
      virtual long double dist2dbl (const D& dist) const = 0;
      virtual std::uint64_t dist2int (const D& dist) const = 0;

      virtual const char* str2add (A* add, const char* str, char delimiter) 
                                                                      const = 0;

      virtual const A& undefAddress (void) const = 0;

   protected:

      // note these assume the addresses are from this system; they are for
      // internal use only

      virtual DgAddressBase* createAddress (void) const 
                                   { return new DgAddress<A>(); }

      virtual DgAddressBase* createAddress (const DgAddressBase& addIn) const
          { return new DgAddress<A>(static_cast<const DgAddress<A>&>(addIn)); }

      virtual void copyAddress (const DgAddressBase& from,
                                      DgAddressBase* to) const
          { *(static_cast<DgAddress<A>*>(to)) = 
                                      static_cast<const DgAddress<A>&>(from); } 

      A& getTypedAddress (DgAddressBase& base) const
          { return (static_cast<DgAddress<A>&>(base)).address(); }

      const A& getTypedAddress (const DgAddressBase& base) const
          { return (static_cast<const DgAddress<A>&>(base)).address(); }

      virtual bool equalAddress (const DgAddressBase& add1, 
                                 const DgAddressBase& add2) const
          { return static_cast<const DgAddress<A>&>(add1).address() ==
                   static_cast<const DgAddress<A>&>(add2).address(); }

   friend class DgInArcGen;
   friend class DgOutAIGenFile;

};

#include "DgRF_template.h"

#endif


<|start_filename|>src/DgProjISEA.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgProjISEA.h: DgProjISEA class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPROJ_ISEA_H
#define DGPROJ_ISEA_H

#include <limits>
#include <iostream>

#include "DgIVec2D.h"
#include "DgDVec2D.h"
#include "DgPolygon.h"
#include "DgRF.h"
#include "DgLocation.h"
#include "DgConverter.h"
#include "Dg2WayConverter.h"
#include "DgContCartRF.h"
#include "DgGeoSphRF.h"
#include "DgProjTriRF.h"
#include "DgEllipsoidRF.h"
#include "DgUtil.h"
#include "DgIcosaProj.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgProjISEAFwd : public DgConverter<DgGeoCoord, long double,
                                        DgProjTriCoord, long double> {

   public:

      DgProjISEAFwd (const DgRF<DgGeoCoord, long double>& geoRF,
                       const DgRF<DgProjTriCoord, long double>& projTriRF);

      const DgProjTriRF& projTriRF (void) const { return *pProjTriRF_; }

      virtual DgProjTriCoord convertTypedAddress (const DgGeoCoord& addIn) 
                                                               const;

   private:

      const DgProjTriRF* pProjTriRF_;

};

////////////////////////////////////////////////////////////////////////////////
class DgProjISEAInv : public DgConverter<DgProjTriCoord, long double, 
                                           DgGeoCoord, long double> {

   public:

      DgProjISEAInv (const DgRF<DgProjTriCoord, long double>& projTriRF,
                          const DgRF<DgGeoCoord, long double>& geoRF);

      const DgProjTriRF& projTriRF (void) const { return *pProjTriRF_; }

      virtual DgGeoCoord convertTypedAddress (const DgProjTriCoord& addIn) 
                                                                      const;

   private:

      const DgProjTriRF* pProjTriRF_;

};

////////////////////////////////////////////////////////////////////////////////
class DgProjISEA : public DgIcosaProj {

   public:

      DgProjISEA (const DgRF<DgGeoCoord, long double>& geoRF,
                    const DgRF<DgProjTriCoord, long double>& projTriRF)
         : DgIcosaProj(*(new DgProjISEAFwd(geoRF, projTriRF)), 
                       *(new DgProjISEAInv(projTriRF, geoRF))) {}
};

/* C projection functions */

Vec2D sllxy (const GeoCoord& Geovect, SphIcosa& sphico, 
             int tri);

IcosaGridPt snyderFwd (const GeoCoord& ll, DgSphIcosa& sphicosa);

GeoCoord snyderInv (const IcosaGridPt& pt, SphIcosa& sphicosa);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#endif


<|start_filename|>src/DgIDGG.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGG.h: DgIDGG class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGIDGG_H 
#define DGIDGG_H

#include <limits>
#include <iostream>
#include <cstdint>

#include "DgIVec2D.h"
#include "DgDVec2D.h"
#include "DgPolygon.h"
#include "DgRF.h"
#include "DgLocation.h"
#include "DgConverter.h"
#include "Dg2WayConverter.h"
#include "DgContCartRF.h"
#include "DgGeoSphRF.h"
#include "DgDiscRF2D.h"
#include "DgDiscRFS2D.h"
#include "DgHexC1Grid2D.h"
#include "DgProjTriRF.h"
#include "DgIcosaProj.h"
#include "DgIcosaMap.h"
#include "DgEllipsoidRF.h"
#include "DgUtil.h"

class DgPolygon;
class DgIDGG;
class DgBoundedIDGG;

using namespace std;

////////////////////////////////////////////////////////////////////////////////
//
//   Coordinate consisting of vertex number and (i, j) coordinates.
//
class DgQ2DICoord  {

   public:

      static const DgQ2DICoord undefDgQ2DICoord;

      DgQ2DICoord (int quadNumIn = -1, const DgIVec2D& coordIn = DgIVec2D())
        : quadNum_ (quadNumIn), coord_ (coordIn) { }

      int quadNum (void) const { return quadNum_; }

      const DgIVec2D& coord (void) const { return coord_; }

      void setVertNum (int quadNumIn)           { quadNum_ = quadNumIn; }
      void setCoord   (const DgIVec2D& coordIn) { coord_ = coordIn; }

      operator string (void) const
         { return string("quadNum: " + dgg::util::to_string(quadNum()) + 
                      ", coord: " + string(coord())); }

      bool operator== (const DgQ2DICoord& qc) const
          { return quadNum() == qc.quadNum() && coord() == qc.coord(); }

      bool operator!= (const DgQ2DICoord& qc) const
          { return !(*this == qc); }

      DgQ2DICoord& operator= (const DgQ2DICoord& add)
          {
             if (add != *this)
             {
                setVertNum(add.quadNum());
                setCoord(add.coord());
             }

             return *this;
          }

   private:

      int quadNum_;
      DgIVec2D coord_;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgQ2DICoord& coord)
{ return stream << string(coord); }

////////////////////////////////////////////////////////////////////////////////
//
//   Coordinate consisting of vertex number and (x, y) coordinates.
//
class DgQ2DDCoord  {

   public:

      static const DgQ2DDCoord undefDgQ2DDCoord;

      DgQ2DDCoord (int quadNumIn = -1,
                   const DgDVec2D& coordIn = DgDVec2D())
        : quadNum_ (quadNumIn), coord_ (coordIn) { }

      int quadNum (void) const { return quadNum_; }

      const DgDVec2D& coord (void) const { return coord_; }

      void setVertNum (int quadNumIn)           { quadNum_ = quadNumIn; }
      void setCoord   (const DgDVec2D& coordIn) { coord_ = coordIn; }

      operator string (void) const
          { return string("quadNum: " + dgg::util::to_string(quadNum()) + ", coord: " 
                          + string(coord())); }

      bool operator== (const DgQ2DDCoord& qc) const
          { return quadNum() == qc.quadNum() && coord() == qc.coord(); }

      bool operator!= (const DgQ2DDCoord& qc) const
          { return !(*this == qc); }

      DgQ2DDCoord& operator= (const DgQ2DDCoord& add)
          {
             if (add != *this)
             {
                setVertNum(add.quadNum());
                setCoord(add.coord());
             }

             return *this;
          }

   private:

      int quadNum_;
      DgDVec2D coord_;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgQ2DDCoord& coord)
{ return stream << string(coord); }

////////////////////////////////////////////////////////////////////////////////
class DgQ2DDRF : public DgRF<DgQ2DDCoord, long double> {

   public:

      DgQ2DDRF (DgRFNetwork& networkIn, const string& nameIn)
         : DgRF<DgQ2DDCoord, long double>(networkIn, nameIn) { }

      virtual long double dist (const DgQ2DDCoord& add1, 
                           const DgQ2DDCoord& add2) const 
                       { return add1.coord().distance(add2.coord()); }

      virtual string add2str (const DgQ2DDCoord& add) const
                       { return string(add); }

      virtual string add2str (const DgQ2DDCoord& add, char delimiter) const
        { return dgg::util::to_string(add.quadNum()) + delimiter + 
                    dgg::util::to_string(add.coord().x(), formatStr()) + delimiter + 
                    dgg::util::to_string(add.coord().y(), formatStr()); }

      virtual const char* str2add (DgQ2DDCoord* add, const char* str, 
                                   char delimiter) const;

      virtual string dist2str (const long double& dist) const
                       { return dgg::util::to_string(dist, formatStr()); }

      virtual long double dist2dbl (const long double& dist) const
                       { return dist; }

      virtual std::uint64_t dist2int (const long double& dist) const
                       { return (std::uint64_t) dist; }

      virtual const DgQ2DDCoord& undefAddress (void) const
                       { static DgQ2DDCoord undef; return undef; }

};

////////////////////////////////////////////////////////////////////////////////
class DgQuadEdgeCells {

   public:

      DgQuadEdgeCells (int quadNumIn, bool isType0In, int loneVertIn,
                      int upQuadIn, int rightQuadIn)
         : isType0_ (isType0In), quadNum_ (quadNumIn), loneVert_ (loneVertIn),
           upQuad_ (upQuadIn), rightQuad_ (rightQuadIn) { }

      bool isType0   (void) const { return isType0_; }
      int  quadNum   (void) const { return quadNum_; }
      int  loneVert  (void) const { return loneVert_; }
      int  upQuad    (void) const { return upQuad_; }
      int  rightQuad (void) const { return rightQuad_; }

   private:

      bool isType0_;

      int quadNum_;
      int loneVert_;
      int upQuad_;
      int rightQuad_;

};

////////////////////////////////////////////////////////////////////////////////
class DgVertTriVals {

   public:

      DgVertTriVals (int quadNum, int triNum, int subTri, bool keep, 
                 const DgDVec2D& trans, int rot60) 
         : quadNum_ (quadNum), triNum_ (triNum), subTri_ (subTri), keep_ (keep),
           trans_ (trans), rot60_ (rot60) { }

      int      quadNum (void) const { return quadNum_; }
      int      triNum  (void) const { return triNum_; }
      int      subTri  (void) const { return subTri_; }
      bool     keep    (void) const { return keep_; }
      int      rot60   (void) const { return rot60_; }

      const DgDVec2D& trans (void) const { return trans_; }
      
      void setQuadNum (int quadNumIn) { quadNum_ = quadNumIn; }
      void setTriNum  (int triNumIn) { triNum_ = triNumIn; }
      void setSubTri  (int subTriIn) { subTri_ = subTriIn; }
      void setKeep    (bool keepIn) { keep_ = keepIn; }
      void setTrans   (const DgDVec2D& transIn) { trans_ = transIn; }
      void setRot60   (int rot60In) { rot60_ = rot60In; }

      operator string (void) const
          { string keeper; if (keep()) keeper = "true"; else keeper = "false";
            return string("keep: " + keeper + ", triNum: " + dgg::util::to_string(triNum())
                      + ", quadNum: " + dgg::util::to_string(quadNum()) + 
           ", subTri: " + dgg::util::to_string(subTri()) + ", rot60: " + dgg::util::to_string(rot60()) + 
           ", trans: " + string(trans())); }

   private:

      int quadNum_;
      int triNum_;
      int subTri_;
      bool keep_;
      DgDVec2D trans_;
      int rot60_; // number of deosil 60 deg rotations after translation

};

////////////////////////////////////////////////////////////////////////////////
inline ostream& 
operator<< (ostream& str, const DgVertTriVals& coord) 
{ return str << string(coord); }

////////////////////////////////////////////////////////////////////////////////
class DgVertex2DDCoord {

   public:

      DgVertex2DDCoord (bool keepIn = true, int vertNumIn = -1, 
           int triNumIn = -1, const DgDVec2D& coordIn = DgDVec2D())
         : vertNum_ (vertNumIn), triNum_ (triNumIn), keep_ (keepIn),
           coord_ (coordIn) { }

      int  vertNum (void) const { return vertNum_; }
      int  triNum  (void) const { return triNum_; }
      bool keep    (void) const { return keep_; }

      const DgDVec2D& coord (void) const { return coord_; }
      
      void setVertNum (int vertNumIn) { vertNum_ = vertNumIn; }
      void setTriNum  (int triNumIn) { triNum_ = triNumIn; }
      void setKeep    (bool keepIn) { keep_ = keepIn; }
      void setCoord   (const DgDVec2D& coordIn) { coord_ = coordIn; }

      operator string (void) const
          { string keeper; if (keep()) keeper = "true"; else keeper = "false";
            return string("keep: " + keeper + ", triNum: " + 
                       dgg::util::to_string(triNum()) + ", vertNum: " + 
                       dgg::util::to_string(vertNum()) + ", coord: " 
                       + string(coord())); }

      bool operator== (const DgVertex2DDCoord& c) const
          { return keep() == c.keep() && triNum() == c.triNum() &&
                   vertNum() == c.vertNum() && coord() == c.coord(); }

   private:

      int vertNum_;
      int triNum_;
      bool keep_;
      DgDVec2D coord_;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream& 
operator<< (ostream& str, const DgVertex2DDCoord& coord) 
{ return str << string(coord); }

////////////////////////////////////////////////////////////////////////////////
class DgVertex2DDRF : public DgRF<DgVertex2DDCoord, long double> {

   public:

      DgVertex2DDRF (DgRFNetwork& networkIn, const string& nameIn)
         : DgRF<DgVertex2DDCoord, long double> (networkIn, nameIn) { }

      //virtual DgLocVector& convert (DgLocVector& vec) const;

      virtual long double dist (const DgVertex2DDCoord& add1,
                           const DgVertex2DDCoord& add2) const
                { return M_ZERO; }

      virtual string add2str (const DgVertex2DDCoord& add) const
                       { return string(add); }

      virtual string add2str (const DgVertex2DDCoord& add, char delimiter) const
          { return dgg::util::to_string(add.vertNum()) + delimiter +
                   dgg::util::to_string(add.triNum()) + delimiter + 
                   ((add.keep()) ? "keep" : "nokeep") + delimiter +
                   dgg::util::to_string(add.coord().x(), formatStr()) + delimiter +
                   dgg::util::to_string(add.coord().y(), formatStr()); }

      virtual const char* str2add (DgVertex2DDCoord* add, const char* str, 
                                   char delimiter) const;

      virtual const DgVertex2DDCoord& undefAddress (void) const
                { static DgVertex2DDCoord undef(false, -1, -1); return undef; }

      virtual string dist2str (const long double& dist) const
                       { return dgg::util::to_string(dist, formatStr()); }

      virtual long double dist2dbl (const long double& dist) const
                       { return dist; }

      virtual std::uint64_t dist2int (const long double& dist) const
                       { return (std::uint64_t) dist; }

      static const DgVertTriVals& vertTable (int vertNum, int subTri) 
                       { return vertTable_[vertNum][subTri]; }

      static const DgVertTriVals& triTable (int triNum)
                       { return triTable_[triNum]; }

   private:

      static DgVertTriVals vertTable_[12][6];
      static const DgVertTriVals triTable_[20];

};

////////////////////////////////////////////////////////////////////////////////
class DgQ2DItoDConverter : 
        public DgConverter<DgQ2DICoord, std::int64_t, DgQ2DDCoord, long double>
{
   public:

      DgQ2DItoDConverter (const DgRF<DgQ2DICoord, std::int64_t>& from,
                          const DgRF<DgQ2DDCoord, long double>& to);

      const DgIDGG& IDGG (void) const { return *pIDGG_; }

      virtual DgQ2DDCoord convertTypedAddress 
                                (const DgQ2DICoord& addIn) const;

   protected:

      const DgIDGG* pIDGG_;

};

////////////////////////////////////////////////////////////////////////////////
class DgQ2DDtoIConverter : 
        public DgConverter<DgQ2DDCoord, long double, DgQ2DICoord, std::int64_t>
{
   public:

      DgQ2DDtoIConverter (const DgRF<DgQ2DDCoord, long double>& from,
                          const DgRF<DgQ2DICoord, std::int64_t>& to);

      const DgIDGG& IDGG (void) const { return *pIDGG_; }

      virtual DgQ2DICoord convertTypedAddress 
                                (const DgQ2DDCoord& addIn) const;

   protected:

      const DgIDGG* pIDGG_;

};

////////////////////////////////////////////////////////////////////////////////
class DgVertex2DDToQ2DDConverter : 
        public DgConverter<DgVertex2DDCoord, long double, DgQ2DDCoord, long double>
{
   public:

      DgVertex2DDToQ2DDConverter (const DgRF<DgVertex2DDCoord, long double>& from,
                                  const DgRF<DgQ2DDCoord, long double>& to);

      virtual DgQ2DDCoord convertTypedAddress 
                                (const DgVertex2DDCoord& addIn) const;
};

////////////////////////////////////////////////////////////////////////////////
class DgQ2DDtoVertex2DDConverter : 
        public DgConverter<DgQ2DDCoord, long double, DgVertex2DDCoord, long double>
{
   public:

      DgQ2DDtoVertex2DDConverter (const DgRF<DgQ2DDCoord, long double>& from,
                                  const DgRF<DgVertex2DDCoord, long double>& to);

      virtual DgVertex2DDCoord convertTypedAddress 
                                (const DgQ2DDCoord& addIn) const;

    private:
        inline int compute_subtriangle(const long double& x, const long double&  y) const;
};

////////////////////////////////////////////////////////////////////////////////
class DgProjTriToVertex2DD :
        public DgConverter<DgProjTriCoord, long double, DgVertex2DDCoord, long double> {

   public:

      DgProjTriToVertex2DD (const DgRF<DgProjTriCoord, long double>& from,
                            const DgRF<DgVertex2DDCoord, long double>& to)
         : DgConverter<DgProjTriCoord, long double, DgVertex2DDCoord, long double>
             (from, to) { }

      virtual DgVertex2DDCoord convertTypedAddress
                                          (const DgProjTriCoord& addIn) const;

};

////////////////////////////////////////////////////////////////////////////////
class DgVertex2DDtoProjTri :
        public DgConverter<DgVertex2DDCoord, long double, DgProjTriCoord, long double> {

   public:

      DgVertex2DDtoProjTri (const DgRF<DgVertex2DDCoord, long double>& from,
                            const DgRF<DgProjTriCoord, long double>& to)
         : DgConverter<DgVertex2DDCoord, long double, DgProjTriCoord, long double> 
             (from, to) { }

      virtual DgProjTriCoord convertTypedAddress
                                          (const DgVertex2DDCoord& addIn) const;
};

////////////////////////////////////////////////////////////////////////////////
class DgPlaneTriRF : public DgContCartRF {

   public:

      DgPlaneTriRF (DgRFNetwork& networkIn, const string& nameIn = "PlaneTri",
                    const DgIcosaMap& icosaMapIn = DgIcosaMap::defIcosaMap)
         : DgContCartRF(networkIn, nameIn), icosaMap_ (icosaMapIn) { }

      const DgIcosaMap& icosaMap (void) const { return icosaMap_; }

   private:

      const DgIcosaMap& icosaMap_;

};

////////////////////////////////////////////////////////////////////////////////
class DgPlaneTriProj : public DgConverter<DgProjTriCoord, long double,
                                          DgDVec2D, long double> {

   public:

      DgPlaneTriProj (const DgRF<DgProjTriCoord, long double>& from,
                      const DgRF<DgDVec2D, long double>& to);

      const DgPlaneTriRF& planeTriRF (void) const { return *pPlaneTriRF_; }

      virtual DgDVec2D convertTypedAddress (const DgProjTriCoord& addIn) const;

   private:

      const DgPlaneTriRF* pPlaneTriRF_;

};

////////////////////////////////////////////////////////////////////////////////
//
//   Coordinate consisting of a string containing quad number, (aperture 3 hex
//        level indicator), and radix string
//
class DgInterleaveCoord  {

   public:

      static const DgInterleaveCoord undefDgInterleaveCoord;

      DgInterleaveCoord (void) { }

      DgInterleaveCoord (const DgInterleaveCoord& coord) 
              { valString_ = coord.valString(); }

      void setValString (const string strIn) { valString_ = strIn; }

      const string& valString (void) const { return valString_; }

      operator string (void) const { return valString(); }

      bool operator== (const DgInterleaveCoord& c) const
          { return valString() == c.valString(); }

      bool operator!= (const DgInterleaveCoord& c) const
          { return !(*this == c); }

      DgInterleaveCoord& operator= (const DgInterleaveCoord& add)
          {
             if (add != *this) setValString(add.valString());

             return *this;
          }

   private:

      string valString_;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgInterleaveCoord& coord)
{ return stream << string(coord); }

////////////////////////////////////////////////////////////////////////////////
class DgInterleaveRF : public DgRF<DgInterleaveCoord, std::int64_t> {

   public:

      DgInterleaveRF (DgRFNetwork& networkIn, const string& nameIn)
         : DgRF<DgInterleaveCoord, std::int64_t>(networkIn, nameIn) { }

      virtual std::int64_t dist (const DgInterleaveCoord& add1, 
                        const DgInterleaveCoord& add2) const 
                       { return 0; }

      virtual string add2str (const DgInterleaveCoord& add) const
                       { return string(add); }

      virtual string add2str (const DgInterleaveCoord& add, char delimiter) 
                                                                         const
                       { return string(add); }

      virtual const char* str2add (DgInterleaveCoord* add, const char* str, 
                                   char delimiter) const;

      virtual string dist2str (const std::int64_t& dist) const
                       { return dgg::util::to_string(dist); }

      virtual long double dist2dbl (const std::int64_t& dist) const
                       { return dist; }

      virtual std::uint64_t dist2int (const std::int64_t& dist) const
                       { return dist; }

      virtual const DgInterleaveCoord& undefAddress (void) const
                       { static DgInterleaveCoord undef; return undef; }

};

////////////////////////////////////////////////////////////////////////////////
class DgQ2DItoInterleaveConverter : 
        public DgConverter<DgQ2DICoord, std::int64_t, DgInterleaveCoord, std::int64_t>
{
   public:

      DgQ2DItoInterleaveConverter (const DgRF<DgQ2DICoord, std::int64_t>& from,
                                   const DgRF<DgInterleaveCoord, std::int64_t>& to);

      const DgIDGG& IDGG (void) const { return *pIDGG_; }

      virtual DgInterleaveCoord convertTypedAddress 
                                (const DgQ2DICoord& addIn) const;

   protected:

      const DgIDGG* pIDGG_;

};

////////////////////////////////////////////////////////////////////////////////
class DgDegConverter : 
               public DgConverter<DgGeoCoord, long double, DgDVec2D, long double> {

   public:

      DgDegConverter (const DgRF<DgGeoCoord, long double>& from,
                       const DgRF<DgDVec2D, long double>& to)
         : DgConverter<DgGeoCoord, long double, DgDVec2D, long double>(from, to) { }

      virtual DgDVec2D convertTypedAddress (const DgGeoCoord& addIn) const
      {
         return DgDVec2D(addIn.lonDegs(), addIn.latDegs());
      }
};

////////////////////////////////////////////////////////////////////////////////
class DgRadConverter : 
               public DgConverter<DgDVec2D, long double, DgGeoCoord, long double> {

   public:

      DgRadConverter (const DgRF<DgDVec2D, long double>& from,
                      const DgRF<DgGeoCoord, long double>& to)
         : DgConverter<DgDVec2D, long double, DgGeoCoord, long double>(from, to) { } 

      virtual DgGeoCoord convertTypedAddress (const DgDVec2D& addIn) const
      {
         return DgGeoCoord(addIn.x(), addIn.y(), false);
      }
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Class to hold statistics on a particular DGG.
//
class DgGridStats {

   public:

      DgGridStats (void)
         : nCells_ (0), cls_ (M_ZERO), cellDistKM_ (M_ZERO), 
           cellAreaKM_ (M_ZERO), precision_ (DEFAULT_PRECISION) { }

      std::uint64_t nCells     (void) const { return nCells_; }
      long double            cls        (void) const { return cls_; }
      long double            cellDistKM (void) const { return cellDistKM_; }
      long double            cellAreaKM (void) const { return cellAreaKM_; }
      unsigned int           precision  (void) const { return precision_; }
   
      void setNCells (std::int64_t nCellsIn) { nCells_ = nCellsIn; }
      void setCLS    (long double clsIn)             { cls_ = clsIn; }
      void setCellDistKM (long double cellDistKMin)  { cellDistKM_ = cellDistKMin; }
      void setCellAreaKM (long double cellAreaIn)    { cellAreaKM_ = cellAreaIn; }
      void setPrecision (unsigned int precisionIn)    { precision_ = precisionIn; }
      
   private:

      std::uint64_t nCells_;
      long double cls_;
      long double cellDistKM_;
      long double cellAreaKM_;
      unsigned int precision_;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream&
operator<< (ostream& stream, const DgGridStats& gs)
{ 
  unsigned int prec = gs.precision();

  stream << "DGG Statistics (calculated in projection space):\n";
  stream << " total #cells: " << dgg::util::addCommas(gs.nCells()) << "\n";
  stream << " intercell distance: " 
         << dgg::util::addCommas(gs.cellDistKM(), prec) << " km\n";
  stream << " cell area: " 
         << dgg::util::addCommas(gs.cellAreaKM(), prec) << " km^2\n";
  stream << " characteristic length scale: " 
         << dgg::util::addCommas(gs.cls(), prec) << " km" << endl;

  return stream;
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
//  Icosahedral DGG class.
//
class DgIDGG : public DgDiscRF<DgQ2DICoord, DgGeoCoord, long double> {

   using DgDiscRF<DgQ2DICoord, DgGeoCoord, long double>::setVertices;

   public:

      DgIDGG (const DgGeoSphRF& geoRFIn, const DgGeoCoord& vert0,
              long double azDegs, unsigned int apertureIn, int resIn, 
              const string& nameIn = "IDGG", 
              const string& gridTopoIn = string("HEXAGON"),
              const string& projType = string("ISEA"),
              bool isMixedApIn = false, int numAp4 = 0, 
              bool isSuperfund = false, int sfRes = 17, 
              unsigned int precisionIn = DEFAULT_PRECISION);

      DgIDGG (const DgIDGG& grd);

      virtual ~DgIDGG();

      const DgGeoSphRF&  geoRF       (void) const { return geoRF_; }
      const DgGeoCoord&  vert0       (void) const { return vert0_; }
      long double        azDegs      (void) const { return azDegs_; }
      unsigned int       aperture    (void) const { return aperture_; }
      bool               isMixed43   (void) const { return isMixed43_; }
      bool               isSuperfund (void) const { return isSuperfund_; }
      int                sfRes       (void) const { return sfRes_; }
      int                numAp4      (void) const { return numAp4_; }
      int                res         (void) const { return res_; }
      int                adjRes      (void) const { return adjRes_; }
      std::int64_t maxI        (void) const { return maxI_; }
      std::int64_t maxJ        (void) const { return maxJ_; }
      std::int64_t mag         (void) const { return mag_; }
      std::int64_t maxD        (void) const { return maxD_; }
      int                radix       (void) const { return radix_; }
      const string&      gridTopo    (void) const { return gridTopo_; }
      const string&      projType    (void) const { return projType_; }
      bool               isClassI    (void) const { return isClassI_; }
      bool               isAligned   (void) const { return isAligned_; }
      bool               isCongruent (void) const { return isCongruent_; }
      const DgQ2DICoord& firstAdd    (void) const { return firstAdd_; }
      const DgQ2DICoord& lastAdd     (void) const { return lastAdd_; }

      int                outputRes   (void) const 
                               { return (isSuperfund_) ? sfRes_ : res_; }

      const DgProjTriRF&    projTriRF (void) const { return *projTriRF_; }
      const DgVertex2DDRF&  vertexRF  (void) const { return *vertexRF_; }
      const DgQ2DDRF&       q2ddRF    (void) const { return *q2ddRF_; }
      const DgBoundedIDGG&  bndRF     (void) const { return *bndRF_; }
      const DgInterleaveRF& intRF     (void) const { return *intRF_; }
      const DgPlaneTriRF&   planeRF   (void) const { return *planeRF_; }

      const DgContCartRF&   ccFrame (void) const { return *ccFrame_; }
      const DgDiscRF2D&     grid2D  (void) const { return *grid2D_; }

      unsigned int          precision (void) const { return precision_; } 

      const DgGridStats& gridStats (void) const { return gridStats_; }

      void setPrecision (unsigned int precisionIn)
        { precision_ = precisionIn;
          gridStats_.setPrecision(precision()); }

      virtual string add2str (const DgQ2DICoord& add) const 
                 { return string(add); }

      virtual string add2str (const DgQ2DICoord& add, char delimiter) const 
        { return dgg::util::to_string(add.quadNum()) + delimiter + 
                 dgg::util::to_string(add.coord().i()) + delimiter + 
                 dgg::util::to_string(add.coord().j()); }

      virtual const char* str2add (DgQ2DICoord* add, const char* str, 
                                   char delimiter) const;

      virtual const DgQ2DICoord& undefAddress (void) const 
                            { return DgQ2DICoord::undefDgQ2DICoord; }

      virtual void setVertices (const DgLocation& loc, DgPolygon& vec,
                                int densify) const;

      virtual void setAddVertices (const DgQ2DICoord& add,
                                   DgPolygon& vec) const
                  { setAddVertices(add, vec, 0); }

      virtual void setAddVertices (const DgQ2DICoord& add,
                                   DgPolygon& vec, int densify) const;

      // we'll give dummy definitions for these since some of our IDGG's may
      // not have defined these yet

      virtual std::int64_t dist (const DgQ2DICoord& add1, 
                                       const DgQ2DICoord& add2) const
           {
              report(string("DgIDGG::dist() this method has not been defined "
                     "for DgIDGG ") + this->name(), DgBase::Fatal);

	      return M_ZERO;
           }

      virtual void setAddNeighbors (const DgQ2DICoord& add,
                                    DgLocVector& vec) const 
           {
              report(string("DgIDGG::setAddNeighbors() this method has not "
                "been defined for DgIDGG ") + this->name(), DgBase::Fatal);
           }

      // give dummy definitions; these will not be used but will be
      // overridden by series converters

      virtual DgQ2DICoord quantify (const DgGeoCoord& add) const
                { DgQ2DICoord v; return v; }

      virtual DgGeoCoord invQuantify (const DgQ2DICoord& add) const
                { DgGeoCoord g; return g; }

      static const DgQuadEdgeCells& edgeTable (int quadNum)
                       { return edgeTable_[quadNum]; }

   protected:

      virtual void initialize (void);

      const DgDiscRFS2D& grid2DS (void) const { return *grid2DS_; }

   private:

      DgSphIcosa* sphIcosa_;

      const DgGeoSphRF& geoRF_;

      DgGeoCoord vert0_;
      long double azDegs_;

      string gridTopo_;
      string projType_;

      unsigned int aperture_;

      int res_;
      int adjRes_;
      bool isClassI_;
      bool isAligned_;
      bool isCongruent_;
      bool isMixed43_;
      int  numAp4_;
      bool isSuperfund_;
      int  sfRes_;

      std::int64_t mag_;
      std::int64_t maxD_;
      int radix_;
      std::int64_t maxI_;
      std::int64_t maxJ_;

      DgQ2DICoord firstAdd_;
      DgQ2DICoord lastAdd_;

      DgGridStats gridStats_;
      unsigned int precision_;

      static const DgQuadEdgeCells edgeTable_[12];

      // local internal network

      DgRFNetwork locNet_;

      DgDiscRF2D* grid2D_;
      DgDiscRFS2D* grid2DS_;
      DgContCartRF* ccFrame_;

      // intermediate RFs

      DgProjTriRF* projTriRF_;
      DgVertex2DDRF* vertexRF_;
      DgQ2DDRF* q2ddRF_;
      DgBoundedIDGG* bndRF_;
      DgInterleaveRF* intRF_;
      DgPlaneTriRF* planeRF_;

   friend class DgQ2DItoDConverter;
   friend class DgQ2DDtoIConverter;
   friend class DgBoundedIDGG;
};

////////////////////////////////////////////////////////////////////////////////
#endif


<|start_filename|>src/DgRFNetwork.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRFNetwork.cpp: DgRFNetwork class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cstdint>

#include "DgBase.h"
#include "DgRFBase.h"
#include "DgLocation.h"
#include "DgSeriesConverter.h"

////////////////////////////////////////////////////////////////////////////////
DgRFNetwork::~DgRFNetwork (void)
{
   for (std::uint64_t i = 0; i < size(); i++)
   {
      for (std::uint64_t j = 0; j < size(); j++) 
      {
         if (matrix_[i][j] && !(matrix_[i][j]->userGenerated()))
         {
            delete matrix_[i][j];
            matrix_[i][j] = 0;
         }
      }
      matrix_[i].clear();
   }

/* 
   for (int i = 0; i < frames_.size(); i++)
   {
      delete frames_[i];
      frames_[i] = 0;
   }
*/

} // DgRFNetwork::~DgRFNetwork

////////////////////////////////////////////////////////////////////////////////
bool
DgRFNetwork::existsConverter (const DgRFBase& fromFrame,
                                    const DgRFBase& toFrame) const
{
   return matrix_[fromFrame.id()][toFrame.id()];

} // bool DgRFNetwork::existsConverter

////////////////////////////////////////////////////////////////////////////////
const DgConverterBase* 
DgRFNetwork::getConverter (const DgLocation& fromLoc, 
                                 const DgRFBase& toFrame) const
{
   return getConverter(fromLoc.rf(), toFrame);

} // const DgConverter* DgRFNetwork::getConverter

////////////////////////////////////////////////////////////////////////////////
const DgConverterBase* 
DgRFNetwork::getConverter (const DgRFBase& fromFrame, 
                                 const DgRFBase& toFrame) const
{
   // check for network match

   if (fromFrame.network() != *this && toFrame.network() != *this)
   {
      report("DgRFNetwork::getConverter() network mismatch",
             DgBase::Fatal);
      return 0;
   }

   // check for existing converter

   if (!matrix_[fromFrame.id()][toFrame.id()]) 
   {
      // attempt to generate a passthrough converter
      
      if (!fromFrame.connectTo() || !toFrame.connectFrom())
      {
         report("DgRFNetwork::getConverter() frames not connected: " +
                 fromFrame.name() + string(" -> ") + toFrame.name(),
                DgBase::Fatal);
         return 0;
      }
      
      const_cast<DgRFNetwork*>(this)->matrix_
                           [fromFrame.id()][toFrame.id()] = 
                                new DgSeriesConverter(fromFrame, toFrame);
   }

   return matrix_[fromFrame.id()][toFrame.id()];

} // const DgConverter* DgRFNetwork::getConverter

////////////////////////////////////////////////////////////////////////////////
void
DgRFNetwork::update (void)
{
   for (std::uint64_t i = 0; i < size(); i++)
   {
      for (std::uint64_t j = 0; j < size(); j++)
      {
         if (i != j && matrix_[i][j] && !matrix_[i][j]->userGenerated())
         {
            delete matrix_[i][j];
            matrix_[i][j] = 0;
            if (frames_[i]->connectTo() && frames_[j]->connectFrom())
            {
               matrix_[i][j] = new DgSeriesConverter(*frames_[i], *frames_[j]);
            }
         }
      }
   }
} // void DgRFNetwork::update

////////////////////////////////////////////////////////////////////////////////
void
DgRFNetwork::reserve (const size_t& capacity)
{
   frames_.reserve(capacity);
   matrix_.reserve(capacity);

   for (unsigned long i = 0; i < matrix_.size(); i++) 
    matrix_[i].reserve(capacity);

} // void DgRFNetwork::reserve

////////////////////////////////////////////////////////////////////////////////
int
DgRFNetwork::generateId (DgRFBase* frame)
{
   std::uint64_t newSize = size() + 1;

   frames_.resize(newSize, 0);
   matrix_.resize(newSize);

   for (std::uint64_t i = 0; i < newSize; i++) 
    matrix_[i].resize(newSize, 0);
   
   frames_[nextId_] = frame;
   
   matrix_[nextId_][nextId_] = new DgIdentityConverter(*frame);
   
   if (nextId_ == 0) 
    frame->connectTo_ = frame->connectFrom_ = frame; // ground

   if (nextId_ == (int) capacity()) 
    reserve(capacity() + chunkSize());
   
   nextId_++;
   
   return (nextId_ - 1);
} 

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDistance.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDistance.h: DgDistance class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDISTANCE_H
#define DGDISTANCE_H

#include <string>
#include <iostream>
#include <cstdint>

#include "DgRFBase.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgDistanceBase {

   public:

      virtual ~DgDistanceBase (void);

      const DgRFBase& rf (void) const { return rf_; }

      string asString (void) const { return rf().toString(*this); }

      long double asDouble (void) const { return rf().toDouble(*this); }

      std::uint64_t asInt (void) const { return rf().toInt(*this); }

   protected:

      DgDistanceBase (const DgRFBase& frame) 
         : rf_ (const_cast<DgRFBase&>(frame)) {}

      DgDistanceBase (const DgDistanceBase& dist)
         : rf_ (const_cast<DgRFBase&>(dist.rf())) {}

      DgDistanceBase& operator= (const DgDistanceBase& dist)
         { rf_ = const_cast<DgRFBase&>(dist.rf()); 
           return *this; }

   private:

      DgRFBase& rf_;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgDistanceBase& dist)
            { return stream << dist.asString(); }

////////////////////////////////////////////////////////////////////////////////
template <class A> class DgDistance : public DgDistanceBase {

   public:

      DgDistance (const DgRFBase& frame) 
         : DgDistanceBase (frame) {}

      DgDistance (const DgDistance<A>& dist) 
         : DgDistanceBase (dist.rf()), distance_ (dist.distance()) {}

      DgDistance (const DgRFBase& frame, const A& distance) 
         : DgDistanceBase (frame), distance_ (distance) {}

      void setDistance (const A& distance) { distance_ = distance; }

      const A& distance (void) const { return distance_; }

      DgDistance& operator= (const DgDistance<A>& dist)
         { DgDistanceBase::operator=(dist); distance_ = dist.distance();
           return *this; }

   private:

      A distance_;
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgOutShapefile.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutShapefile.h: DgOutShapefile class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGOUTSHAPEFILE_H
#define DGOUTSHAPEFILE_H

#include <cstdio>
#include <set>
#include "shapefil.h"

#include "DgInShapefileAtt.h"
#include "DgOutLocFile.h"
#include "DgGeoSphRF.h"

class DgDVec2D;
class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgOutShapefile : public DgOutLocFile {

   using DgOutLocFile::insert;

   public:

      DgOutShapefile (const DgGeoSphDegRF& rfIn, const string& fileNameIn = "",
            int precision = 6, bool isPointFile = false,
            int shapefileIdLen = 11, DgReportLevel failLevel = DgBase::Fatal);

      virtual ~DgOutShapefile (void) { if (good()) close(); }

      int numDigits (void) { return numDigits_; }

      int idLen (void) { return idLen_; }

      bool open (const string& fileName, 
                 DgReportLevel failLevel = DgBase::Fatal);

      virtual void close (void) 
      { 
         DBFClose(dbFile_);
         SHPClose(shpFile_);
      }

      bool good (void) { return dbFile_ && shpFile_; }

      virtual DgOutLocFile& insert (DgLocation& loc, const string* label = NULL);
      virtual DgOutLocFile& insert (DgLocVector& vec, const string* label = NULL, 
                                const DgLocation* cent = NULL);
      virtual DgOutLocFile& insert (DgPolygon& poly, const string* label = NULL, 
                                const DgLocation* cent = NULL);

      void addFields (const set<DgDBFfield>& fields);

      void setCurFields (const set<DgDBFfield>& fields) { curFields_ = fields; }

      const DgGeoSphRF& geoRF (void) const { return geoRF_; }

      int    defIntAttribute (void) const { return defIntAttribute_; }
      double defDblAttribute (void) const { return defDblAttribute_; }
      string defStrAttribute (void) const { return defStrAttribute_; }

      void setDefIntAttribute (int val)    { defIntAttribute_ = val; }
      void setDefDblAttribute (double val) { defDblAttribute_ = val; }
      void setDefStrAttribute (string val) { defStrAttribute_ = val; }

   protected:

      const DgGeoSphRF& geoRF_;

      DBFHandle dbFile_;
      SHPHandle shpFile_;

      string dbFileName_;
      string shpFileName_;

      int recNum_;
      int numDigits_;
      int numFields_;
      int idLen_;

      // default attribute values
      int defIntAttribute_;
      long double defDblAttribute_;
      string defStrAttribute_;

      set<DgDBFfield> curFields_; // non-null fields for current cell being written

      virtual DgOutLocFile& insert (const DgDVec2D& pt);

      void writeDbf (const string& id);
};

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedIDGGS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedIDGGS.h: DgBoundedIDGGS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBOUNDEDIDGGS_H
#define DGBOUNDEDIDGGS_H

#include <cstdint>

#include "DgIDGGS.h"
#include "DgBoundedIDGG.h"
#include "DgIDGG.h"

class DgLocation;
class DgBoundedIDGGS;

////////////////////////////////////////////////////////////////////////////////
class DgBoundedIDGGS 
        : public DgBoundedRF<DgResAdd<DgQ2DICoord>, DgGeoCoord, long double > {

   public:

      DgBoundedIDGGS (const DgIDGGS& rf);
                    
      virtual DgResAdd<DgQ2DICoord>& incrementAddress 
                                      (DgResAdd<DgQ2DICoord>& add) const;

      virtual DgResAdd<DgQ2DICoord>& decrementAddress 
                                      (DgResAdd<DgQ2DICoord>& add) const;

      virtual bool validAddress (const DgResAdd<DgQ2DICoord>& add) const
          { return add == endAdd() || (add.res() >= 0 && 
                   add.res() < IDGGS().nRes() && 
                   grids()[add.res()]->validAddress(add.address())); }

      const DgResAdd<DgQ2DICoord>& invalidAdd (void) const 
              { return IDGGS().undefAddress(); }

      const DgIDGGS& IDGGS (void) const { return IDGGS_; }

      const vector<DgBoundedIDGG*>& grids (void) const { return *grids_; }

      virtual std::uint64_t seqNumAddress 
                                  (const DgResAdd<DgQ2DICoord>& add) const;

      virtual DgResAdd<DgQ2DICoord> addFromSeqNum 
                                  (std::uint64_t sNum) const;

   private:

      const DgIDGGS& IDGGS_;

      vector<DgBoundedIDGG*>* grids_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgOutLocTextFile.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutLocTextFile.h: DgOutLocTextFile class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGOUTLOCTEXTFILE_H
#define DGOUTLOCTEXTFILE_H

#include <string>
#include <fstream>

#include "DgUtil.h"
#include "DgOutputStream.h"
#include "DgOutLocFile.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////
class DgOutLocTextFile : public DgOutputStream, public DgOutLocFile {

   public:

      void setPrecision (int prec) { precision_ = prec; setFormatStr(); }
      int getPrecision (void) { return precision_; }

      const char *formatStr() const { return formatStr_.c_str(); }

      // direct the DgOutLocFile abstract methods to the DgOutputStream ones
      virtual bool open (const string& fileName,
                DgReportLevel failLevel = DgBase::Fatal) 
              { return DgOutputStream::open(fileName, failLevel); }

      virtual void close (void) { DgOutputStream::close(); }


   protected:

      DgOutLocTextFile (const string& fileName, const DgRFBase& rf, 
                        bool isPointFile = false,
                        const string& suffix = string(""), 
			int precision = 7, 
                        DgReportLevel failLevel = DgBase::Fatal);

      virtual void setFormatStr(void) = 0;

      std::string formatStr_;

   private:
      
      int             precision_;
};

inline DgOutLocTextFile& operator<< (DgOutLocTextFile& file, const char* str)
              { ostream& o = file; o << str; return file; }

inline DgOutLocTextFile& operator<< (DgOutLocTextFile& file, const string& str)
              { ostream& o = file; o << str; return file; }

inline DgOutLocTextFile& operator<< (DgOutLocTextFile& file, long double val)
              { ostream& o = file; o << val; return file; }

inline DgOutLocTextFile& operator<< (DgOutLocTextFile& file, float val)
              { ostream& o = file; o << val; return file; }

inline DgOutLocTextFile& operator<< (DgOutLocTextFile& file, int val)
              { ostream& o = file; o << val; return file; }

#endif


<|start_filename|>src/DgEllipsoidRF.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgEllipsoidRF.cpp: DgEllipsoidRF class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cstdint>
#include <iostream>
#include <limits>
#include <stdexcept>

#include "DgEllipsoidRF.h"
#include "DgGeoSphRF.h"
#include "DgPolygon.h"

const DgGeoCoord DgGeoCoord::undefGeoCoord(std::numeric_limits<long double>::max(), std::numeric_limits<long double>::max());
const long double DgGeoCoord::tolerance = 0.0000000005L;

////////////////////////////////////////////////////////////////////////////////
long double 
DgGeoCoord::gcDist (const DgGeoCoord& g1, const DgGeoCoord& g2, 
                    bool rads)
/*
   return great circle distance in radians between g1 and g2.

   CRC Math, 1991, pp. 129-130.

   <NAME>, 3/10/99
*/
{
   // use spherical triangle with g1 at A, g2 at B, and north pole at C

   long double bigC = fabs(g2.lon() - g1.lon());
   
   if (bigC > dgM_PI) // assume we want the complement
   {
      // note that in this case they can't both be negative

      long double lon1 = g1.lon();
      if (lon1 < 0.0L) lon1 += 2.0L * dgM_PI; 
      long double lon2 = g2.lon();
      if (lon2 < 0.0L) lon2 += 2.0L * dgM_PI; 

      bigC = fabs(lon2 - lon1);
   }

   long double b = dgM_PI_2 - g1.lat();
   long double a = dgM_PI_2 - g2.lat();

   // use law of cosines to find c

   long double cosc = cos(a) * cos(b) + sin(a) * sin(b) * cos(bigC);
   if (cosc > 1.0L) cosc = 1.0L;
   if (cosc < -1.0L) cosc = -1.0L;

   long double retVal = acos(cosc);

   if (!rads) retVal *= M_180_PI;
 
   return retVal;

} // long double DgGeoCoord::gcDist

////////////////////////////////////////////////////////////////////////////////
DgGeoCoord 
DgGeoCoord::gcIntersect (const DgGeoCoord& g11, const DgGeoCoord& g12, 
          const DgGeoCoord& g21, const DgGeoCoord& g22)
/*
   Return point of intersection of the two great circle arc segments g11-g12 
   and g21-g22.

   Works by calling Lian Song's routine GCintersect.
*/
{
   GeoCoord sv11, sv12, sv21;
   sv11.lon = g11.lon(); sv11.lat = g11.lat();
   sv12.lon = g12.lon(); sv12.lat = g12.lat();
   sv21.lon = g21.lon(); sv21.lat = g21.lat();
   //sv22.lon = g22.lon(); sv22.lat = g22.lat();

   GeoCoord ans = GCintersect(sv11, sv12, sv21, sv11, 1);
   
   return DgGeoCoord(ans.lon, ans.lat);

} // DgGeoCoord DgGeoCoord::gcIntersect

////////////////////////////////////////////////////////////////////////////////
long double 
DgGeoCoord::geoTriArea (const DgGeoCoord& g1, const DgGeoCoord& g2, 
                        const DgGeoCoord& g3)
/*
   return area in radians.

   CRC Math, 1991, pp. 129-130.

   <NAME>, 3/10/99
*/
{
   // determine the edges

   long double a = DgGeoCoord::gcDist(g2, g3);
   long double b = DgGeoCoord::gcDist(g1, g3);
   long double c = DgGeoCoord::gcDist(g1, g2);

   // determine the angles using half-angle formulas

   long double s = (a + b + c) / 2.0L;

   long double sinsa = sin(s - a);
   long double sinsb = sin(s - b);
   long double sinsc = sin(s - c);

   long double k = sqrt(sinsa * sinsb * sinsc / sin(s));
   
   long double bigA = 2.0L * atan(k / sinsa);
   long double bigB = 2.0L * atan(k / sinsb);
   long double bigC = 2.0L * atan(k / sinsc);

   long double E = bigA + bigB + bigC - dgM_PI;

/*
   cout << "geoTriArea: " << g1 << " " << g2 << " " << g3 << endl
        << " a: " << a 
        << " b: " << b
        << " c: " << c << endl
        << " A: " << bigA 
        << " B: " << bigB
        << " C: " << bigC << endl
        << " E: " << E << " "
        << E / (4.0L * dgM_PI) << endl;
*/

   return E;

} // long double DgGeoCoord::geoTriArea

////////////////////////////////////////////////////////////////////////////////
long double 
DgGeoCoord::geoPolyArea (const DgPolygon& poly, const DgGeoCoord center)
//
// returns area of spherical polygon in radians; 
//
// assumes DgAddressBase for poly is DgGeoCoord
//
// Assumes poly is a "reasonably" convex polygon (i.e. a cell bouncary) and
// that center is an interior point.
//
{
   long double totArea = 0.0L;
   
   const DgGeoSphRF* geoRF = dynamic_cast<const DgGeoSphRF*>(&poly.rf());
   if (geoRF == 0) 
      report("DgGeoCoord::geoPolyArea() non-geo polygon", DgBase::Fatal);

   // do each sub-triangle
   for (int i = 0; i < poly.size(); i++)
   {
      const DgGeoCoord& v1 = *geoRF->getAddress(poly[i]);
      const DgGeoCoord& v2 = *geoRF->getAddress(poly[(i + 1) % poly.size()]);
                              
      totArea += DgGeoCoord::geoTriArea(center, v1, v2);
   }

   return totArea;

} // long double DgGeoCoord::geoPolyArea

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
const char*
DgEllipsoidRF::str2add (DgGeoCoord* add, const char* str, char delimiter) const
{
   if (!add) add = new DgGeoCoord();

   DgDVec2D vec;
   const char* tmp = vec.fromString(str, delimiter);

   *add = DgGeoCoord(vec.x(), vec.y(), false);

   return tmp;

} // const char* DgEllipsoidRF::str2add

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*
   sphTrig.C: vector and spherical trig utilities

   <NAME> and <NAME>, July 24, 1994.

   <NAME>, merged & optimized, July 20, 2001
*/
/******************************************************************************/

#include <stdlib.h> 
#include <stdio.h> 
#include <cmath>

/******************************************************************************/
void sphTriInit (SphTri* tri)
/*
   Initialize tri with UNDEFVAL values. 
*/
{
   int i;

   for (i = 0; i < 3; i++)
   {
      tri->verts[i].lon  = tri->verts[i].lat  = UNDEFVAL;
      tri->edges[i] = tri->angles[i] = UNDEFVAL;
   }
   tri->code = UNDEFINT;
   tri->area = tri->perimeter = UNDEFVAL;
   tri->compactness = UNDEFVAL;

} /* void sphTriInit */

/******************************************************************************/
void planeTriInit (PlaneTri* tri)
/*
   Initialize tri with UNDEFVAL values.
*/
{
   int i;

   for (i = 0; i < 3; i++)
      tri->points[i].x  = tri->points[i].y = UNDEFVAL;
   tri->code = tri->direction =  UNDEFINT;
   tri->cenpoint.x = tri->cenpoint.y = UNDEFVAL;

} /* void planeTriInit */

/******************************************************************************/
void printInt (std::int64_t val)
/*
   Print val or 'UNDEFVAL' to stdout as appropriate.
*/
{
   // if (val == UNDEFVAL)
   //    std::cout<<"UNDEFVAL";
   // else
   //    std::cout<<val;
 
} /* void printInt */

/******************************************************************************/
void printVal (long double val)
/*
   Print val or 'UNDEFVAL' to stdout as appropriate.
*/
{
   // if (val == UNDEFVAL) 
   //    std::cout<<"UNDEFVAL";
   // else 
   //    std::cout<<val;

} /* void printVal */

/******************************************************************************/
void printGeoCoord (const GeoCoord& p)
/*
   Print p to stdout.
*/
{
   /*printVec2D(*((Vec2D*) &p));*/
   // printf("(");
   // printVal(p.lon* M_180_PI);
   // printf(",");
   // printVal(p.lat* M_180_PI);
   // printf(")");

} /* void printGeoCoord */

/******************************************************************************/
void printVec2D (const Vec2D& p)
/*
   Print p to stdout.
*/
{
   // printf("(");
   // printVal(p.x);
   // printf(", ");
   // printVal(p.y);
   // printf(")");

} /* void printVec2D */

/******************************************************************************/
void printVec3D (const Vec3D& p)
/*
   Print p to stdout.
*/
{
   // printf("(");
   // printVal(p.x);
   // printf(", ");
   // printVal(p.y);
   // printf(", ");
   // printVal(p.z);
   // printf(")");

} /* void printVec3D */

/******************************************************************************/
void printSphTri (const SphTri& tri)
/*
   Print tri to stdout.
*/
{
   // int i;

   // printf("{\n  code: "); printInt(tri.code);
   // printf("\n  vertices: ");
   // for (i = 0; i < 3; i++) 
   // {
   //    printf(" ");
   //    printGeoCoord(tri.verts[i]);
   // }
   // printf("\n");
   
   // printf("  A: "); printVal(tri.edges[0]);
   // printf("  B: "); printVal(tri.edges[1]);
   // printf("  C: "); printVal(tri.edges[2]);
   // printf("\n");

   // printf("  a: "); printVal(tri.angles[0]* M_180_PI);
   // printf("  b: "); printVal(tri.angles[1]* M_180_PI);
   // printf("  c: "); printVal(tri.angles[2]* M_180_PI);
   // printf("\n");

   // printf("  area: "); printVal(tri.area);
   // printf("  perimeter: "); printVal(tri.perimeter);
   // printf("  compactness: "); printVal(tri.compactness);
   // printf("\n");

   // printf("}\n");

} /* void printSphTri */

/******************************************************************************/
void printPlaneTri (const PlaneTri& tri)
/*
   Print tri to stdout.
*/
{
   // int i;
 
   // printf("{\n  code: "); printInt(tri.code);
   // printf("\n  vertices: ");
   // for (i = 0; i < 3; i++)
   // {
   //    printf(" ");
   //    printVec2D(tri.points[i]);
   // }
   // printf("\n");
   // printVec2D(tri.cenpoint);
   // printf("\n");
 
   // printf("}\n");
 
} /* void PlaneTri */

/******************************************************************************/
Vec3D vecAdd (const Vec3D& A, const Vec3D& B)
/*
   Calculate and return A + B.
*/
{
   Vec3D C;

   C.x = A.x + B.x;
   C.y = A.y + B.y;
   C.z = A.z + B.z;

   return C;

} /* Vec3D vecAdd */

/******************************************************************************/
Vec3D vecSub (const Vec3D& A, const Vec3D& B)
/*
   Calculate and return A - B.
*/
{
   Vec3D C;

   C.x = A.x - B.x;
   C.y = A.y - B.y;
   C.z = A.z - B.z;

   return C;

} /* Vec3D vecSub */

/******************************************************************************/
Vec3D vecCross (const Vec3D& A, const Vec3D& B)
/*
   Calculate and return A x B.
*/
{
   Vec3D C;

   C.x = A.y * B.z - A.z * B.y;
   C.y = A.z * B.x - A.x * B.z;
   C.z = A.x * B.y - A.y * B.x;

   return C;

} /* Vec3D vecCross */

/******************************************************************************/
long double vecMag (const Vec3D& V)
/* 
   Calculate and return the magnitude of a vector V.
*/
{
   return sqrt(V.x * V.x + V.y * V.y + V.z * V.z);

} /* long double vecMag */

/******************************************************************************/
Vec3D vecNormalize  (const Vec3D& V)
/*
   Return the normalized form of V.
*/
{
   Vec3D C;

   C.x = V.x/sqrt(V.x * V.x + V.y * V.y + V.z * V.z);
   C.y = V.y/sqrt(V.x * V.x + V.y * V.y + V.z * V.z);
   C.z = V.z/sqrt(V.x * V.x + V.y * V.y + V.z * V.z); 

   return C;

}  /* Vec3D vecNormalize */

/******************************************************************************/
long double vecDot (const Vec3D& A, const Vec3D& B)
/*
   Calculate and return the dot product of two vectors.
*/
{
   return A.x * B.x + A.y * B.y + A.z * B.z;

}  /*  long double vecDot */

/******************************************************************************/
long double sqrMetersToExcessD (long double area)
{
   return area * 360.0L / (4.0L * dgM_PI * DgGeoSphRF::earthRadiusKM() * 
          DgGeoSphRF::earthRadiusKM());

} /* long double metersToExcessD */

/******************************************************************************/
long double metersToGCDegrees (long double meters)
{
   long double earthCircum = (2.0L * dgM_PI * DgGeoSphRF::earthRadiusKM());
   return meters * 360.0L / earthCircum;

} /* long double metersToGCDegrees */

/******************************************************************************/
long double maxval(long double val1, long double val2)
/*
  return the maxmum of two variables
*/
 {
  long double maxx;
  if (val1>val2) maxx=val1;
  else maxx=val2;
  return maxx;
 } /* long double maxval */

/******************************************************************************/
long double minval(long double val1, long double val2)
/* 
  return the minmum of two variables
*/ 
 {
  long double minn;
  if (val1<val2) minn=val1;
  else minn=val2;
  return minn;
 } /* long double minval */

/******************************************************************************/
Vec3D llxyz(const GeoCoord& sv)
/*
  Transformation of a point on the sphere from xyz cordinates to latitude and longitude
  Input unit is degree. Output unit regard the earth's radius as one unit.
*/
 {
  Vec3D v;
  v.x=cos(sv.lat)*cos(sv.lon);
  v.y=cos(sv.lat)*sin(sv.lon);
  v.z=sin(sv.lat);

  const long double epsilon = 0.000000000000001L;
  if (fabs(v.x) < epsilon) v.x = 0.0L;
  if (fabs(v.y) < epsilon) v.y = 0.0L;
  if (fabs(v.z) < epsilon) v.z = 0.0L;

  return v;

 } /* Vec3D llxyz */

/******************************************************************************/
GeoCoord xyzll(const Vec3D& v0)
/*
   Transformation of a point on the sphere from xyz cordinates to latitude and 
   longitude Input unit regard the earth's radius as one unit. Output unit is 
   degree.
*/
 {
  GeoCoord sv;
  Vec3D v = v0;

  if (fabs(v.z)-1.0L < PRECISION)
  {
     if (v.z>1.0L) v.z = 1.0L;
     if (v.z<-1.0L) v.z = -1.0L;
     sv.lat=asin(v.z);
     if ((sv.lat== dgM_PI_2) || (sv.lat==-dgM_PI_2)) sv.lon=0.0L;
     else sv.lon=atan2(v.y,v.x);
     return sv;
  }
  else 
  {
     //printf("Error: in function xyzll, asin domain error.\n");
     return sv;
  }

 } /* GeoCoord xyzll */

/******************************************************************************/
GeoCoord sphTricenpoint(GeoCoord sp[3])
/*
   Calculate and return the center point of a sphere triangle 
   Input and output unit is degree.
*/
 {
  Vec3D p[3], cp, cpn;
  GeoCoord cv;
  int i;
 
  for (i=0;i<3;i++) p[i]=llxyz(sp[i]);
  cp.x=(p[0].x+p[1].x+p[2].x)/3;
  cp.y=(p[0].y+p[1].y+p[2].y)/3;
  cp.z=(p[0].z+p[1].z+p[2].z)/3;
  cpn=vecNormalize(cp);
  cv=xyzll(cpn);
  return cv;
 } /* GeoCoord sphTricenpoint */

/******************************************************************************/
long double chorddist(const GeoCoord& ll1, const GeoCoord& ll2)
/*
   Calculate the chord distance between two points on the sphere
   Input unit is degree. Output unit regard the earth's radius as one unit.
*/
 {
  //long double la1,lo1,la2,lo2;
  Vec3D p1,p2;
  p1.x=cos(ll1.lat)*cos(ll1.lon); 
  p1.y=cos(ll1.lat)*sin(ll1.lon); 
  p1.z=sin(ll1.lat);
  p2.x=cos(ll2.lat)*cos(ll2.lon); 
  p2.y=cos(ll2.lat)*sin(ll2.lon); 
  p2.z=sin(ll2.lat);
  return 
    sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)+(p1.z-p2.z)*(p1.z-p2.z));

 } /* long double chorddist */

/******************************************************************************/
long double spheredist(const GeoCoord& ll1, const GeoCoord& ll2)
/*
   Calculate the sphere distance between two points on the sphere
   Input and Output unit is in radius.
*/
 {
  long double sd;
  sd=cos(dgM_PI_2-ll1.lat)*cos(dgM_PI_2-ll2.lat)+
     sin(dgM_PI_2-ll1.lat)*sin(dgM_PI_2-ll2.lat)*cos(ll1.lon-ll2.lon);
  if (sd>1) sd=1;
  if (sd<-1) sd=-1;
  return acos(sd);
 }/* long double spheredist */

/******************************************************************************/
void sphTriSolve(SphTri* tri)
/*
   Input:  three vertices's lat and lon in radius.
   Output: three edges, three angles, area.
	   the unit for length is kilometer, the unit for angle is degree
*/
 {
  int i;
  long double l1[2],l2[2],l3[2],p,mindist;

  mindist=5;
  l1[0]=tri->verts[0].lat; l1[1]=tri->verts[0].lon;
  l2[0]=tri->verts[1].lat; l2[1]=tri->verts[1].lon;
  l3[0]=tri->verts[2].lat; l3[1]=tri->verts[2].lon;
  tri->edges[0]=acos(cos(dgM_PI_2-l2[0])*cos(dgM_PI_2-l3[0])+
               sin(dgM_PI_2-l2[0])*sin(dgM_PI_2-l3[0])*cos(l2[1]-l3[1]));
  tri->edges[1]=acos(cos(dgM_PI_2-l1[0])*cos(dgM_PI_2-l3[0])+
               sin(dgM_PI_2-l1[0])*sin(dgM_PI_2-l3[0])*cos(l1[1]-l3[1]));
  tri->edges[2]=acos(cos(dgM_PI_2-l2[0])*cos(dgM_PI_2-l1[0])+
               sin(dgM_PI_2-l2[0])*sin(dgM_PI_2-l1[0])*cos(l2[1]-l1[1]));
  tri->angles[0]=acos((cos(tri->edges[0])-cos(tri->edges[1])*
               cos(tri->edges[2]))/(sin(tri->edges[1])*sin(tri->edges[2])));
  tri->angles[1]=acos((cos(tri->edges[1])-cos(tri->edges[0])*
               cos(tri->edges[2]))/(sin(tri->edges[0])*sin(tri->edges[2])));
  tri->angles[2]=acos((cos(tri->edges[2])-cos(tri->edges[0])*
               cos(tri->edges[1]))/(sin(tri->edges[0])*sin(tri->edges[1])));
  for (i=0;i<3;i++) tri->edges[i]=tri->edges[i]*DgGeoSphRF::earthRadiusKM();
  if (tri->edges[0]<mindist)
   {
    p=(tri->edges[0]+tri->edges[1]+tri->edges[2])/2;
    tri->area=sqrt(p*(p-tri->edges[0])*(p-tri->edges[1])*(p-tri->edges[2]));
   }
  else tri->area=(tri->angles[0]+tri->angles[1]+tri->angles[2]-dgM_PI)*
              DgGeoSphRF::earthRadiusKM()*DgGeoSphRF::earthRadiusKM();
 
 } /* void sphTriSolve(SphTri* tri) */

/******************************************************************************/
GeoCoord GCmidpoint(const GeoCoord& pp1, const GeoCoord& pp2)
{
  Vec3D pt1,pt2,mpt;
  GeoCoord mp;
  pt1=llxyz(pp1);
  pt2=llxyz(pp2);
  mpt.x = (pt1.x+pt2.x)/2.0L;
  mpt.y = (pt1.y+pt2.y)/2.0L;
  mpt.z = (pt1.z+pt2.z)/2.0L;
  mpt = vecNormalize(mpt);
  mp = xyzll(mpt);
  return mp;
}

/******************************************************************************/
long double Azimuth(const GeoCoord& pt1, const GeoCoord& pt2)
/*
  return the Azimuth of pt2 relatived to pt1  
  output azimuth unit is radius
*/
 {
  long double az;

  az=atan2(cos(pt2.lat)*sin(pt2.lon-pt1.lon), cos(pt1.lat)*sin(pt2.lat)-
     sin(pt1.lat)*cos(pt2.lat)*cos(pt2.lon-pt1.lon));
  return az;
 } /* long double Azimuth */

/******************************************************************************/
GeoCoord GCintersect(const GeoCoord& sv11, const GeoCoord& sv12, 
                     const GeoCoord& sv21, const GeoCoord& sv22, int sign)
/*
  return the intersect point of two great circle
  sign=1: two great circle segment with ends of sv11 and sv12,
          sv21 and sv22 respectively
  sign=0: two whole great circle with one pass sv11 and sv12, one pass 
          sv21 and sv22, return the intersect point on North Hemisphere
*/ 
 {
  GeoCoord pt;
  Vec3D nn1,nn2,
	p11,p12,
	p21,p22,
	pp,pp2;
  long double a,b,maxlon,minlon;
 
/* calculate the intersect point of two great circle */
  p11=llxyz(sv11);
  p12=llxyz(sv12);
  p21=llxyz(sv21);
  p22=llxyz(sv22);
  nn1.x=p11.y*p12.z-p12.y*p11.z;
  nn1.y=-p11.x*p12.z+p12.x*p11.z;
  nn1.z=p11.x*p12.y-p12.x*p11.y;
  nn2.x=p21.y*p22.z-p22.y*p21.z;
  nn2.y=-p21.x*p22.z+p22.x*p21.z;
  nn2.z=p21.x*p22.y-p22.x*p21.y;
  if ((nn2.z*nn1.y-nn1.z*nn2.y)!= 0.0L)
   {
    b=(nn1.x*nn2.y-nn2.x*nn1.y)/(nn2.z*nn1.y-nn1.z*nn2.y);
    a=(nn2.x*nn1.z-nn1.x*nn2.z)/(nn1.y*nn2.z-nn2.y*nn1.z);
    pp.x=1/sqrt(a*a+b*b+1);
    pp.y=a*pp.x;
    pp.z=b*pp.x;
   }
  else if (((nn2.z*nn1.y-nn1.z*nn2.y)==0.0L) &&
         ((nn1.x*nn2.y-nn2.x*nn1.y)==0.0L) && ((nn1.x*nn2.z-nn2.x*nn1.z)==0.0L))   {
    throw std::runtime_error("Error of GCintersect: the two great circle planes are parallel.");
   }  
  else if (((nn2.z*nn1.y-nn1.z*nn2.y)==0.0L) && (nn1.z!=0.0L))
   {  
    pp.x=0.0L;
    pp.y=1.0L/sqrt(1+nn1.y*nn1.y/nn1.z/nn1.z);
    pp.z=-nn1.y/nn1.z*pp.y;
   }  
  else if (((nn2.z*nn1.y-nn1.z*nn2.y)==0.0L) && (nn2.z!=0.0L))
   {  
    pp.x=0.0L;
    pp.y=1.0L/sqrt(1.0L+nn2.y*nn2.y/nn2.z/nn2.z);
    pp.z=-nn2.y/nn2.z*pp.y;
   }  
  else if (((nn2.z*nn1.y-nn1.z*nn2.y)==0.0L) && (nn1.y!=0.0L))
   {  
    pp.x=0.0L;
    pp.z=1/sqrt(1+nn1.z*nn1.z/nn1.y/nn1.y);
    pp.y=-nn1.z/nn1.y*pp.z;
   } 
 else if (((nn2.z*nn1.y-nn1.z*nn2.y)==0.0L) && (nn2.y!=0.0L))
   {
    pp.x=0.0L;
    pp.z=1.0L/sqrt(1.0L+nn2.z*nn2.z/nn2.y/nn2.y);
    pp.y=-nn2.z/nn2.y*pp.z;
   }
    
  if (sign==0)
   {
    if (pp.z<0.0L)
     {
      pp.x=0.0L-pp.x;
      pp.y=-pp.y;
      pp.z=-pp.z;
     }
    pt=xyzll(pp);
    return pt;
   }
  else
  {
   /* judge if the point is on the two great circle segment */
 
  pt=xyzll(pp);
  maxlon=maxval(sv11.lon,sv12.lon);
  minlon=minval(sv11.lon,sv12.lon);
  if ((pt.lon<=maxlon) && (pt.lon>=minlon)) 
   return pt;
  else
   {
    pp2.x=-pp.x;
    pp2.y=-pp.y;
    pp2.z=-pp.z;
    pt=xyzll(pp2);
    if ((pt.lon<=maxlon) && (pt.lat>=minlon)) 
     return pt;
    else
     {
      //printf("Error of GCintersect: the point is not on great circle segment.\n");
      pt.lat=UNDEFVAL; pt.lon=UNDEFVAL;
      return pt;
     }
   }
  } 
 } /* GeoCoord GCintersect */

/******************************************************************************/
long double GCptlat(long double lon, const GeoCoord& sv1, const GeoCoord& sv2)
/*
  return latitude of the point on great circle segment with known longtitude
*/
 {
  long double lat,a,b,c;
  Vec3D p1,p2;
 
  p1.x=cos(sv1.lat)*cos(sv1.lon);
  p1.y=cos(sv1.lat)*sin(sv1.lon);
  p1.z=sin(sv1.lat);
  p2.x=cos(sv2.lat)*cos(sv2.lon);
  p2.y=cos(sv2.lat)*sin(sv2.lon);
  p2.z=sin(sv2.lat);
  
  a=(p1.y*p2.z-p1.z*p2.y)*cos(lon);
  b=(p1.x*p2.z-p1.z*p2.x)*sin(lon);
  c=(p1.x*p2.y-p1.y*p2.x);
  if (c!=0.0L) lat=atan((b-a)/c);
  else { lat = UNDEFVAL;
         //printf("Error of GCptlat: the two end points are at one longitude.\n");
       }
  return(lat);
 } /* long double GCptlat */

/******************************************************************************/
int ptinsphtri(const GeoCoord& pt, GeoCoord sTri[3])
/*
  decide if a point is in a spherical triangle
  return 1 if it is in and return 0 if not
*/
{
   int i;
   long double p0, t0;
   Vec3D pp, ptri[3];

   for (i = 0; i < 3; i++) ptri[i] = llxyz(sTri[i]);
   pp = llxyz(pt);
   p0 = pp.x * (ptri[1].y * ptri[2].z - ptri[2].y * ptri[1].z) -
        pp.y * (ptri[1].x * ptri[2].z - ptri[2].x * ptri[1].z) +
        pp.z * (ptri[1].x * ptri[2].y - ptri[2].x * ptri[1].y);

   t0 = ptri[0].x * (ptri[1].y * ptri[2].z - ptri[2].y * ptri[1].z) -
        ptri[0].y * (ptri[1].x * ptri[2].z - ptri[2].x * ptri[1].z) +
        ptri[0].z * (ptri[1].x * ptri[2].y - ptri[2].x * ptri[1].y);

   if (p0 * t0 < 0.0L) 
   {
      return 0;
   }
   else 
   {
      p0 = pp.x * (ptri[0].y * ptri[2].z - ptri[2].y * ptri[0].z) -
           pp.y * (ptri[0].x * ptri[2].z - ptri[2].x * ptri[0].z) +
           pp.z * (ptri[0].x * ptri[2].y - ptri[2].x * ptri[0].y);

      t0 = ptri[1].x * (ptri[0].y * ptri[2].z - ptri[2].y * ptri[0].z) -
           ptri[1].y * (ptri[0].x * ptri[2].z - ptri[2].x * ptri[0].z) +
           ptri[1].z * (ptri[0].x * ptri[2].y - ptri[2].x * ptri[0].y);

      if (p0 * t0 < 0.0L) 
      {
         return 0;
      }
      else 
      {
         p0 = pp.x * (ptri[0].y * ptri[1].z - ptri[1].y * ptri[0].z) -
              pp.y * (ptri[0].x * ptri[1].z - ptri[1].x * ptri[0].z) +
              pp.z * (ptri[0].x * ptri[1].y - ptri[1].x * ptri[0].y);

         t0 = ptri[2].x * (ptri[0].y * ptri[1].z - ptri[1].y * ptri[0].z) -
              ptri[2].y * (ptri[0].x * ptri[1].z - ptri[1].x * ptri[0].z) +
              ptri[2].z * (ptri[0].x * ptri[1].y - ptri[1].x * ptri[0].y);

         return (p0 * t0 >= 0.0L);
      }
   }

}  /* ptinsphtri */ 

/******************************************************************************/
GeoCoord GCdaz(const GeoCoord& pt, long double distance, long double az)
/*
  compute and return the point whose azimuth (az) and distance 
  (distance) relative to a known point (pt) are given.
  input parameter distance and az are in radius, pt in degree.
*/
 {
  GeoCoord pt2;
  long double sinlat, sinlon, coslon;
 
  if ((fabs(az)<PRECISION) || (fabs(fabs(az)-dgM_PI)<PRECISION))
  {
     if (fabs(az)<PRECISION) pt2.lat = pt.lat + distance;
     else pt2.lat = pt.lat - distance;
     pt2.lon = pt.lon;
     if (fabs(pt2.lat-dgM_PI_2)<PRECISION)
     { 
        pt2.lat = dgM_PI_2;
        pt2.lon = 0.0L;
     } 
     if (fabs(pt2.lat+dgM_PI_2)<PRECISION)
     { 
        pt2.lat = -dgM_PI;
        pt2.lon = 0.0L;
     } 
  }   
  else
  {
     sinlat=sin(pt.lat)*cos(distance)+cos(pt.lat)*sin(distance)*cos(az);
     if (sinlat>1.0L) sinlat=1.0L;
     if (sinlat<-1.0L) sinlat=-1.0L;
     pt2.lat=asin(sinlat);   
     if ((pt2.lat==dgM_PI_2) || (pt2.lat==-dgM_PI_2)) pt2.lon=0.0L;
     else   
      {  
       sinlon=sin(az)*sin(distance)/cos(pt2.lat);
       coslon=(cos(distance)-sin(pt.lat)*sin(pt2.lat))/
	      cos(pt.lat)/cos(pt2.lat); 
       if (sinlon>1.0L) sinlon=1.0L;
       if (sinlon<-1.0L) sinlon=-1.0L;
       if (coslon>1.0L) sinlon=1.0L; 
       if (coslon<-1.0L) sinlon=-1.0L;
       pt2.lon=pt.lon+atan2(sinlon,coslon); 
      }   
     if (pt2.lon>dgM_PI+PRECISION) pt2.lon -=2.0L*dgM_PI;
     if (pt2.lon<-dgM_PI-PRECISION) pt2.lon +=2.0L*dgM_PI;
  }
 
  return pt2;
 } /* GeoCoord GCdaz */

/******************************************************************************/



<|start_filename|>src/DgInLocFile.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgInLocFile.h: DgInLocFile class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGINLOCFILE_H
#define DGINLOCFILE_H

#include <string>

#include "DgBase.h"

using namespace std;

class DgLocList;
class DgLocVector;
class DgPolygon;
class DgLocation;
class DgCell;
class DgRFBase;

////////////////////////////////////////////////////////////////////////////////
class DgInLocFile : public DgBase {

   public:

      DgInLocFile (const DgRFBase& rfIn, const string* fileNameIn = NULL,
           bool isPointFileIn = false, DgReportLevel failLevelIn = DgBase::Fatal)
         : DgBase (fileNameIn),
           rf_ (&rfIn), isPointFile_ (isPointFileIn), failLevel_ (failLevelIn)
      { if (fileNameIn) fileName_ = *fileNameIn; } 

      const DgRFBase& rf (void) const { return *rf_; }

      const string& fileName (void) const { return fileName_; }

      bool isPointFile (void) const { return isPointFile_; }

      void setIsPointFile (bool isPointFile = false)
                 { isPointFile_ = isPointFile; }

      DgReportLevel failLevel (void) { return failLevel_; }

      // pure virtual methods

      virtual bool open (const string* fileName = NULL,
                 DgReportLevel failLevel = DgBase::Fatal) = 0;

      virtual void close (void) = 0;

      virtual bool isEOF (void) = 0;

      virtual DgInLocFile& extract (DgLocList&   list) = 0;
      virtual DgInLocFile& extract (DgLocVector& vec)  = 0;
      virtual DgInLocFile& extract (DgPolygon&   poly) = 0;
      virtual DgInLocFile& extract (DgLocation&  loc)  = 0;
      virtual DgInLocFile& extract (DgCell&      cell) = 0;

   protected:

      string fileName_;

      const DgRFBase* rf_;

      bool isPointFile_;

      DgReportLevel failLevel_;
};

inline DgInLocFile& operator>> (DgInLocFile& input, DgLocList& list)
              { return input.extract(list); }

inline DgInLocFile& operator>> (DgInLocFile& input, DgLocVector& vec)
              { return input.extract(vec); }

inline DgInLocFile& operator>> (DgInLocFile& input, DgPolygon& poly)
              { return input.extract(poly); }

inline DgInLocFile& operator>> (DgInLocFile& input, DgLocation& loc)
              { return input.extract(loc); }

inline DgInLocFile& operator>> (DgInLocFile& input, DgCell& cell)
              { return input.extract(cell); }

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgHexGrid2DS.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgHexGrid2DS.cpp: DgHexGrid2DS class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgContCartRF.h"
#include "DgDiscRF.h"
#include "DgHexC1Grid2D.h"
#include "DgHexC2Grid2D.h"
#include "DgHexGrid2DS.h"

////////////////////////////////////////////////////////////////////////////////
DgHexGrid2DS::DgHexGrid2DS (DgRFNetwork& networkIn, 
               const DgRF<DgDVec2D, long double>& backFrameIn, int nResIn, 
               unsigned int apertureIn, bool isCongruentIn, bool isAlignedIn,
               const string& nameIn, bool isMixed43In, int numAp4In, 
               bool isSuperfundIn)
        : DgDiscRFS2D (networkIn, backFrameIn, nResIn, apertureIn, isCongruentIn, 
                       isAlignedIn, nameIn), 
          isMixed43_ (isMixed43In), numAp4_ (numAp4In), isSuperfund_ (isSuperfundIn) 
{ 
   if (aperture() != 3 && aperture() != 4)
   {
      report(
      "DgHexGrid2DS::DgHexGrid2DS() only apertures 3 and 4 implemented",
       DgBase::Fatal);
   }

   if (isCongruent())
   {
      report(
      "DgHexGrid2DS::DgHexGrid2DS() hex grids cannot be congruent",
       DgBase::Fatal);
   }

   if (!isAligned())
   {
      report(
      "DgHexGrid2DS::DgHexGrid2DS() hex grids must be aligned",
       DgBase::Fatal);
   }

   frequency_ = sqrt((long double) aperture());

   // do the grids

   long double fac = M_ONE;

   for (int i = 0; i < nRes(); i++)
   {
      string newName = name() + "_" + dgg::util::to_string(i);

      //cout << newName << " " << fac << ' ' << trans << endl;

      DgContCartRF* ccRF = new DgContCartRF(network(), newName + string("bf"));

      new Dg2WayContAffineConverter(backFrame(), *ccRF, (long double) fac, M_ZERO, 
                                    DgDVec2D(M_ZERO, M_ZERO)); 

      bool isClassI;
      if (!isMixed43())
      {
         if (aperture() == 4) 
            isClassI = true;
         else // ap 3
            isClassI = !(i % 2);
      }
      else // mixed43
      {
         if (i <= numAp4())
            isClassI = true;
         else
            isClassI = !((i - numAp4()) % 2);
      }

      if (isClassI)
      {
         (*grids_)[i] = new DgHexC1Grid2D(network(), *ccRF, newName);
      }
      else
      {
         (*grids_)[i] = new DgHexC2Grid2D(network(), *ccRF, newName);
      }

      new Dg2WayResAddConverter<DgIVec2D, DgDVec2D, long double>
                                                  (*this, *(grids()[i]), i);
      if (isMixed43())
      {
         if (i < numAp4())
            fac *= 2.0L;
         else
            fac *= M_SQRT3;
      }
      else
         fac *= frequency();
//cout << "i: " << i << " fac: " << fac << endl;
   }
//cout << "** final fac: " << fac << endl;

} // DgHexGrid2DS::DgHexGrid2DS

////////////////////////////////////////////////////////////////////////////////
DgHexGrid2DS::DgHexGrid2DS (const DgHexGrid2DS& rf) 
  : DgDiscRFS2D (rf)
{
   report("DgHexGrid2DS::operator=() not implemented yet", DgBase::Fatal);

} // DgHexGrid2DS::DgHexGrid2DS

////////////////////////////////////////////////////////////////////////////////
DgHexGrid2DS::~DgHexGrid2DS (void)
{
   for (unsigned long i = 0; i < grids().size(); i++) 
    delete (*grids_)[i]; 

   delete grids_;

} // DgHexGrid2DS::~DgHexGrid2DS

////////////////////////////////////////////////////////////////////////////////
DgHexGrid2DS&
DgHexGrid2DS::operator= (const DgHexGrid2DS& rf)
{
   report("DgHexGrid2DS::operator=() ", DgBase::Fatal);

   return *this;

} // DgHexGrid2DS& DgHexGrid2DS::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgHexGrid2DS::setAddParents (const DgResAdd<DgIVec2D>& add, 
                             DgLocVector& vec) const
{
   DgPolygon verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res()]->setVertices(*tmpLoc, verts);
   delete tmpLoc;

   int effectiveAperture = aperture();
   if (isMixed43() && add.res() <= numAp4()) effectiveAperture = 4;

   if (effectiveAperture == 3)
   {
      // vertices lie in parents

      grids()[add.res() - 1]->convert(verts);

      for (int i = 0; i < verts.size(); i++)
      {
         // check if already present

         bool found = false;
         for (int j = 0; j < vec.size(); j++)
         {
            if (vec[j] == verts[i])
            {
               found = true;
               break;
            }
         }

         if (!found) vec.push_back(verts[i]);
      }
   }
   else // must be aligned aperture 4
   {
      // edge midpoints lie in parents

      DgLocVector midPts(verts.rf());
      for (int i = 0; i < verts.size(); i++)
      {
         DgDVec2D pt1 = *(grids()[add.res()]->backFrame().getAddress(verts[i]));

         DgDVec2D pt2 = *(grids()[add.res()]->backFrame().getAddress(
                                              verts[(i + 1) % verts.size()]));

         DgLocation* tmpLoc = 
            grids()[add.res()]->backFrame().makeLocation(
                                              DgDVec2D::midPoint(pt1, pt2));

         midPts.push_back(*tmpLoc);

         delete tmpLoc;
      }

      grids()[add.res() - 1]->convert(midPts);

      for (int i = 0; i < midPts.size(); i++)
      {
         // check if already present

         bool found = false;
         for (int j = 0; j < vec.size(); j++)
         {
            if (vec[j] == midPts[i])
            {
               found = true;
               break;
            }
         }

         if (!found) vec.push_back(midPts[i]);
      }
   }

} // void DgHexGrid2DS::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgHexGrid2DS::setAddInteriorChildren (const DgResAdd<DgIVec2D>& add, 
                                        DgLocVector& vec) const
{
   DgLocVector verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res() + 1]->convert(tmpLoc);
   vec.push_back(*tmpLoc);

   delete tmpLoc;

} // void DgHexGrid2DS::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgHexGrid2DS::setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add, 
                                        DgLocVector& vec) const
{
   DgPolygon verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res()]->setVertices(*tmpLoc, verts);
   delete tmpLoc;

   int effectiveAperture = aperture();
   if (isMixed43() && add.res() <= numAp4()) effectiveAperture = 4;

   if (effectiveAperture == 3)
   {
      // vertices lie in children

      grids()[add.res() + 1]->convert(verts);

      for (int i = 0; i < verts.size(); i++)
      {
         // check if already present

         bool found = false;
         for (int j = 0; j < vec.size(); j++)
         {
            if (vec[j] == verts[i])
            {
               found = true;
               break;
            }
         }

         if (!found) vec.push_back(verts[i]);
      }
   }
   else // must be aligned aperture 4
   {
      // edge midpoints lie in children

      DgLocVector midPts(verts.rf());
      for (int i = 0; i < verts.size(); i++)
      {
         DgDVec2D pt1 = *(grids()[add.res()]->backFrame().getAddress(verts[i]));

         DgDVec2D pt2 = *(grids()[add.res()]->backFrame().getAddress(
                                              verts[(i + 1) % verts.size()]));

         DgLocation* tmpLoc = 
            grids()[add.res()]->backFrame().makeLocation(
                                              DgDVec2D::midPoint(pt1, pt2));

         midPts.push_back(*tmpLoc);

         delete tmpLoc;
      }

      grids()[add.res() + 1]->convert(midPts);

      for (int i = 0; i < midPts.size(); i++)
      {
         // check if already present

         bool found = false;
         for (int j = 0; j < vec.size(); j++)
         {
            if (vec[j] == midPts[i])
            {
               found = true;
               break;
            }
         }

         if (!found) vec.push_back(midPts[i]);
      }
   }

} // void DgHexGrid2DS::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgHexGrid2DS::setAddAllChildren (const DgResAdd<DgIVec2D>& add, 
                                   DgLocVector& vec) const
{
   setAddInteriorChildren(add, vec);

   DgLocVector bndVec(vec.rf());
   setAddBoundaryChildren(add, bndVec);

   for (int i = 0; i < bndVec.size(); i++) vec.push_back(bndVec[i]);

} // void DgHexGrid2DS::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgSqrD4Grid2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSqrD4Grid2D.h: DgSqrD4Grid2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGSQRD4GRID2D_H 
#define DGSQRD4GRID2D_H

#include <cmath>
#include <cstdint>

#include "DgDiscRF2D.h"
#include "DgDVec2D.h"
#include "DgIVec2D.h"

class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgSqrD4Grid2D : public DgDiscRF2D {

   public:

      DgSqrD4Grid2D (DgRFNetwork& networkIn, 
                     const DgRF<DgDVec2D, long double>& contCartFrameIn,
                     const string& nameIn = "Sqr2D")
         : DgDiscRF2D (networkIn, contCartFrameIn, nameIn, 1.0, 1.0,
                       sqrt(2.0), 1.0) 
           { r_ = 1.0 / c(); }

      DgSqrD4Grid2D (const DgSqrD4Grid2D& grd) : DgDiscRF2D (grd) {}

      DgSqrD4Grid2D& operator= (const DgSqrD4Grid2D& grd)
           { DgDiscRF2D::operator=(grd); return *this; }

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const
           { return abs(add2.i() - add1.i()) + abs(add2.j() - add1.j()); }

   protected:

      virtual void setAddVertices (const DgIVec2D& add, DgPolygon& vec) const;
      virtual void setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) 
                                                                          const;

      virtual DgIVec2D quantify (const DgDVec2D& point) const
           { return DgIVec2D((std::int64_t) floor(point.x() + 0.5), 
                             (std::int64_t) floor(point.y() + 0.5)); }

      virtual DgDVec2D invQuantify (const DgIVec2D& add) const
           { return DgDVec2D(add.i(), add.j()); }

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIcosaMap.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIcosaMap.cpp: DgIcosaMap class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////
//
//   Projects points in geographic form (longitude and latitude in
//   decimal degrees) to the corresponding ISEA equal area icosahedron
//   projection with the icosahedron unfolded in the standard layout.
//
////////////////////////////////////////////////////////////////////////////////

#include "DgIcosaMap.h"

////////////////////////////////////////////////////////////////////////////////

const DgDVec2D DgIcosaTri::origin_ = DgDVec2D(0.5L, 0.5L / M_SQRT3);

const DgIcosaTri defIcosaTri[20] = {

   DgIcosaTri(true, 0, DgDVec2D(0.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(1.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(2.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(3.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(4.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(1.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(2.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(3.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(4.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(5.0L, 2.0L * M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(0.5L, M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(1.5L, M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(2.5L, M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(3.5L, M_SIN60)),
   DgIcosaTri(true, 0, DgDVec2D(4.5L, M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(1.5L, M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(2.5L, M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(3.5L, M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(4.5L, M_SIN60)),
   DgIcosaTri(true, 3, DgDVec2D(5.5L, M_SIN60))

};

DgIcosaMap DgIcosaMap::defIcosaMap(defIcosaTri);

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIcosaMap::DgIcosaMap (const DgIcosaTri icosaTri[20])
{
   for (int i = 0; i < 20; i++) icosaTri_[i] = icosaTri[i];

} // DgIcosaMap::DgIcosaMap

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgIcosaTri::translate (DgDVec2D* pt) const
{
   // move the origin to the lower left corner

   //*pt += origin_;

   // first rotate 

   long double x0 = pt->x();
   long double y0 = pt->y();
   if (rot60_)
   {
      long double cosAng = cos((rot60_ * 60.0L) * dgM_PI_180);
      long double sinAng = sin((rot60_ * 60.0L) * dgM_PI_180);
      pt->setX(x0 * cosAng - y0 * sinAng);
      pt->setY(x0 * sinAng + y0 * cosAng);
   }

   *pt += offset_;

} // void DgIcosaTri::translate

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgIcosaTri::untranslate (DgDVec2D* pt, bool shiftOrigin) const
{
   // translate to origin

   *pt -= offset_;

   // rotate 

   long double x0 = pt->x();
   long double y0 = pt->y();
   if (rot60_)
   {
      long double cosAng = cos(-1.0L * (rot60_ * 60.0L) * dgM_PI_180);
      long double sinAng = sin(-1.0L * (rot60_ * 60.0L) * dgM_PI_180);
      pt->setX(x0 * cosAng - y0 * sinAng);
      pt->setY(x0 * sinAng + y0 * cosAng);
   }

   if (shiftOrigin) // move the origin from the lower left corner
   {
      *pt -= origin_;
   }

} // void DgIcosaTri::untranslate

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgIcosaMap::translate (int nTri, DgDVec2D* pt) const
{
   icosaTri_[nTri].translate(pt);

} // void DgIcosaMap::translate

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
DgIcosaMap::untranslate (int nTri, DgDVec2D* pt, bool shiftOrigin) const
{
   icosaTri_[nTri].untranslate(pt, shiftOrigin);

} // void DgIcosaMap::untranslate

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgDVec2D
DgIcosaMap::maxOffset (void)
{
   DgDVec2D maxOff(-1.0L, -1.0L);

   for (int i = 0; i < 20; i++)
   {
      if (!icosaTri_[i].mapped_) continue;

      // find the max X and Y offsets for this triangle in edge-length units 

      long double offX = icosaTri_[i].offset_.x();
      long double offY = icosaTri_[i].offset_.y() / M_SIN60;

      switch (icosaTri_[i].rot60_)
      {
         case 0:
         case 5:

            offX += 1.0L;
            break;

         case 1:
         case 4:

            offX += 0.5L;
            break;
      }

      switch (icosaTri_[i].rot60_)
      {
         case 0:
         case 1:
         case 2:

            offY += 1.0L;
            break;
      }

      if (offX > maxOff.x()) maxOff.setX(offX);
      if (offY > maxOff.y()) maxOff.setY(offY);
      
   }

   return maxOff;

} // void DgIcosaMap::maxOffset

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgDmdD4Grid2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDmdD4Grid2D.cpp: DgDmdD4Grid2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgDmdD4Grid2D.h"
#include "DgPolygon.h"

const long double DgDmdD4Grid2D::yOff_ = sqrt(3.0) / 4.0;
const long double DgDmdD4Grid2D::yOff2_ = yOff_ * 2.0;
const long double DgDmdD4Grid2D::xOff_ = 0.25;
const long double DgDmdD4Grid2D::xOffComp_ = 1.0 - xOff_;
const long double DgDmdD4Grid2D::skewFac_ = sqrt(3.0) / 3.0;

////////////////////////////////////////////////////////////////////////////////
void
DgDmdD4Grid2D::setAddVertices (const DgIVec2D& add, DgPolygon& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   // find the center

   DgLocation tmpLoc;
   setAddPoint(add, tmpLoc);
   const DgDVec2D& cent = *(backFrame().getAddress(tmpLoc));

   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-xOff_,     -yOff_)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( xOffComp_, -yOff_)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( xOff_,      yOff_)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-xOffComp_,  yOff_)));

} // void DgDmdD4Grid2D::setAddVertices

////////////////////////////////////////////////////////////////////////////////
void
DgDmdD4Grid2D::setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(), add.j() + 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1, add.j())));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(), add.j() - 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1, add.j())));

} // void DgDmdD4Grid2D::setAddNeighbors

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/proj4.h<|end_filename|>
//
// this is an adapted version of the projects.h file in <NAME>'s 
// USGS PROJ4 projection system
// Version 6.1 - <NAME>, 5/23/13
////////////////////////////////////////////////////////////////////////////////

#ifndef PROJ4_H
#define PROJ4_H

//#include "projUtil.h"
/*
#ifdef __cplusplus
extern "C" {
#endif
*/

#ifndef _proj4_constants_
#define _proj4_constants_

/* some useful constants */

#define projM_PI_180   0.017453292519943295769236907684886L
#define projM_PI_4     0.785398163397448309615660845819875721L
#define projM_PI_2     1.570796326794896619231321691639751442L
#define projM_PI       3.141592653589793238462643383279502884L
#define projTWOPI      6.28318530717958647692528676655900576L

#endif


/* prototype hypot for systems where absent */

extern long double usgs_hypot(long double, long double);

typedef union { long double f; int i; char *s; } PVALUE;

/* procedure prototypes */

long double adjlon(long double);
long double *pj_enfn(long double);
long double pj_mlfn(long double, long double, long double, long double *);
long double pj_inv_mlfn(long double, long double, long double *);
long double pj_qsfn(long double, long double, long double);
long double pj_tsfn(long double, long double, long double);
long double pj_msfn(long double, long double, long double);
long double pj_phi2(long double, long double);
long double *pj_authset(long double);
long double pj_authlat(long double, long double *);

/*
#ifdef __cplusplus
}
#endif
*/

#endif



<|start_filename|>src/DgLabelLoc.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgLabelLoc.h: DgLabelLoc class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGLABELLOC_H
#define DGLABELLOC_H

#include <string>
#include <iostream>

using namespace std;

#include "DgRFBase.h"

////////////////////////////////////////////////////////////////////////////////
class DgLabelLoc {

   public:

      DgLabel (DgLocBase& locIn, string labelIn = "")
         : location_ (locIn), label_ (labelIn) { }

      const string& label (void) const { return label_; }
      const DgLocBase& location (void) const { return location_; }

      void setLabel (const string& labelIn) { label_ = labelIn; }
      void setLocation (DgLocBase& locIn) { label_ = &locIn; }


};

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgLabel& label)
            { return stream << label.label(); }

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgLabelLocBase : public DgLocBase, public DgLabel {

   public:

      

};

////////////////////////////////////////////////////////////////////////////////
#endif


<|start_filename|>src/DgSqrD4Grid2D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSqrD4Grid2D.cpp: DgSqrD4Grid2D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgSqrD4Grid2D.h"
#include "DgPolygon.h"

////////////////////////////////////////////////////////////////////////////////
void
DgSqrD4Grid2D::setAddVertices (const DgIVec2D& add, DgPolygon& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   // find the center

   DgLocation tmpLoc;
   setAddPoint(add, tmpLoc);
   const DgDVec2D& cent = *(backFrame().getAddress(tmpLoc));

   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-0.5, -0.5)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( 0.5, -0.5)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D( 0.5,  0.5)));
   v.push_back(new DgAddress<DgDVec2D>(cent + DgDVec2D(-0.5,  0.5)));

} // void DgSqrD4Grid2D::setAddVertices

////////////////////////////////////////////////////////////////////////////////
void
DgSqrD4Grid2D::setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) const
{
   vector<DgAddressBase*>& v = vec.addressVec();

   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(), add.j() + 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() - 1, add.j())));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i(), add.j() - 1)));
   v.push_back(new DgAddress<DgIVec2D>(DgIVec2D(add.i() + 1, add.j())));

} // void DgSqrD4Grid2D::setAddNeighbors

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgGeoSphRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgGeoSphRF.h: DgGeoSphRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGGEOSPHRF_H 
#define DGGEOSPHRF_H

#include "DgEllipsoidRF.h"
#include "DgContCartRF.h"

////////////////////////////////////////////////////////////////////////////////
class DgGeoSphRF : public DgEllipsoidRF {

   public:

      DgGeoSphRF (DgRFNetwork& networkIn, const string& nameIn = "GeodeticSph",
                  long double earthRadiusKMin = DEFAULT_RADIUS_KM)
         : DgEllipsoidRF (networkIn, nameIn, earthRadiusKMin * 1000L,
                earthRadiusKMin * 1000L) 
           { 
              earthRadiusKM_ = earthRadiusKMin; 
              icosaEdgeRads_ = M_ATAN2;
              icosaEdgeDegs_ = icosaEdgeRads_ * M_180_PI;
              icosaEdgeKM_ = icosaEdgeRads_ * earthRadiusKM_;
              totalAreaKM_ = 4.0L * dgM_PI * earthRadiusKM_ * earthRadiusKM_;
           }

      DgGeoSphRF (const DgGeoSphRF& rf) 
         : DgEllipsoidRF(rf) { /* earthRadius_ = rf.earthRadius(); */ }

      DgGeoSphRF& operator= (const DgGeoSphRF& rf)
         { DgEllipsoidRF::operator=(rf); 
           return *this; }

      // distance in km
      virtual long double dist (const DgGeoCoord& add1, const DgGeoCoord& add2) const
         { return earthRadiusKM() * DgGeoCoord::gcDist(add1, add2); }

      static long double earthRadiusKM (void) { return earthRadiusKM_; } 
      static long double icosaEdgeKM   (void) { return icosaEdgeKM_; } 
      static long double icosaEdgeDegs (void) { return icosaEdgeDegs_; } 
      static long double icosaEdgeRads (void) { return icosaEdgeRads_; } 
      static long double totalAreaKM   (void) { return totalAreaKM_; } 

      // midpoint of great circle connecting two points
      static DgGeoCoord midPoint(const DgGeoCoord& p1, const DgGeoCoord& p2);

      // azimuth from pt1 to pt2
      static long double azimuth(const DgGeoCoord& p1, const DgGeoCoord& p2,
                            bool returnRads = true);

      // point that is distance (rads) from p0 along azimuth (rads)
      static DgGeoCoord travelGC (const DgGeoCoord& p0, long double distance,
                                  long double azimuth, bool inputRads = true);

      // densify polygon in geodetic coordinates
      static void densify (DgPolygon& p, long double maxDist, bool rads = true);

   private:

      static long double earthRadiusKM_;  // earth radius in km
      static long double icosaEdgeKM_;    // spherical icosahedron edge length
      static long double icosaEdgeDegs_;  // spherical icosahedron edge length
      static long double icosaEdgeRads_;  // spherical icosahedron edge length
      static long double totalAreaKM_;    // spherical icosahedron edge length
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgGeoSphDegRF : public DgContCartRF {

   public:

      DgGeoSphDegRF (const DgGeoSphRF& geoRFin, 
                     const string& nameIn = "GeodeticSphDeg");

      const DgGeoSphRF& geoRF (void) const { return geoRF_; }

   protected:

      const DgGeoSphRF& geoRF_;
};

#endif


<|start_filename|>src/DgIDGGS3H.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS3H.cpp: DgIDGGS3H class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgContCartRF.h"
#include "DgDiscRF.h"
#include "DgHexC1Grid2D.h"
#include "DgHexC2Grid2D.h"
#include "DgIDGGS3H.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIDGGS3H::DgIDGGS3H (const DgIDGGS3H& rf) 
  : DgIDGGS (rf)
{
   report("DgIDGGS3H::operator=() not implemented yet", DgBase::Fatal);

} // DgIDGGS3H::DgIDGGS3H

////////////////////////////////////////////////////////////////////////////////
DgIDGGS3H::~DgIDGGS3H (void)
{
   for (unsigned long i = 0; i < grids().size(); i++) 
    delete (*grids_)[i]; 

   delete grids_;

} // DgIDGGS3H::~DgIDGGS3H

////////////////////////////////////////////////////////////////////////////////
DgIDGGS3H&
DgIDGGS3H::operator= (const DgIDGGS3H& rf)
{
   report("DgIDGGS3H::operator=() not implemented", DgBase::Fatal);

   return *this;

} // DgIDGGS3H& DgIDGGS3H::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS3H::setAddParents (const DgResAdd<DgQ2DICoord>& add, 
                             DgLocVector& vec) const
{
   DgPolygon verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res()]->setVertices(*tmpLoc, verts);
   delete tmpLoc;

   // vertices lie in parents

   grids()[add.res() - 1]->convert(verts);

   for (int i = 0; i < verts.size(); i++)
   {
      // check if already present

      bool found = false;
      for (int j = 0; j < vec.size(); j++)
      {
         if (vec[j] == verts[i])
         {
            found = true;
            break;
         }
      }

      if (!found) vec.push_back(verts[i]);
   }

} // void DgIDGGS3H::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS3H::setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   DgLocVector verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res() + 1]->convert(tmpLoc);
   vec.push_back(*tmpLoc);

   delete tmpLoc;

} // void DgIDGGS3H::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS3H::setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   DgPolygon verts;
   DgLocation* tmpLoc = grids()[add.res()]->makeLocation(add.address());
   grids()[add.res()]->setVertices(*tmpLoc, verts);
   delete tmpLoc;

   // vertices lie in children

   grids()[add.res() + 1]->convert(verts);

   for (int i = 0; i < verts.size(); i++)
   {
      // check if already present

      bool found = false;
      for (int j = 0; j < vec.size(); j++)
      {
         if (vec[j] == verts[i])
         {
            found = true;
            break;
         }
      }

      if (!found) vec.push_back(verts[i]);
   }

} // void DgIDGGS3H::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS3H::setAddAllChildren (const DgResAdd<DgQ2DICoord>& add, 
                                   DgLocVector& vec) const
{
   setAddInteriorChildren(add, vec);

   DgLocVector bndVec(vec.rf());
   setAddBoundaryChildren(add, bndVec);

   for (int i = 0; i < bndVec.size(); i++) vec.push_back(bndVec[i]);

} // void DgIDGGS3H::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgIDGGS4D.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS4D.cpp: DgIDGGS4D class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgContCartRF.h"
#include "DgDiscRF.h"
#include "DgIDGGS4D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIDGGS4D::DgIDGGS4D (const DgIDGGS4D& rf) 
  : DgIDGGS (rf)
{
   report("DgIDGGS4D::operator=() not implemented yet", DgBase::Fatal);

} // DgIDGGS4D::DgIDGGS4D

////////////////////////////////////////////////////////////////////////////////
DgIDGGS4D::~DgIDGGS4D (void)
{
   for (unsigned int i = 0; i < grids().size(); i++) 
    delete (*grids_)[i]; 

   delete grids_;

} // DgIDGGS4D::~DgIDGGS4D

////////////////////////////////////////////////////////////////////////////////
DgIDGGS4D&
DgIDGGS4D::operator= (const DgIDGGS4D& rf)
{
   report("DgIDGGS4D::operator=() not implemented", DgBase::Fatal);

   return *this;

} // DgIDGGS4D& DgIDGGS4D::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4D::setAddParents (const DgResAdd<DgQ2DICoord>& add, 
                               DgLocVector& vec) const
{
//cout << "   setAddParents: " << add << endl;
   if (isCongruent() || radix() == 3)
   {
      DgLocation* tmpLoc = makeLocation(add);
      grids()[add.res() - 1]->convert(tmpLoc);
      convert(tmpLoc);

      vec.push_back(*tmpLoc);

      delete tmpLoc;
   }
   else // must be aligned aperture 4
   {
      // vertices lie in parents

      DgLocation* tmpLoc = makeLocation(add);
      DgPolygon* verts = makeVertices(*tmpLoc);
      delete tmpLoc;

//cout << "   verts 1: " << *verts << endl;

      grids()[add.res() - 1]->convert(*verts);
//cout << "   verts 2: " << *verts << endl;
      convert(*verts);
//cout << "   verts 3: " << *verts << endl;

      for (int i = 0; i < verts->size(); i++)
      {
         bool found = false;

         for (int j = 0; j < vec.size(); j++) 
         {
//cout << "  " << i << " " << j << " " << (*verts)[i] << " " << vec[j];
            if ((*verts)[i] == vec[j]) 
            {
//cout << " YES" << endl;
               found = true;
               break;
            }
//cout << " NO" << endl;
         }
         
         if (!found) vec.push_back((*verts)[i]);
      }
//cout << "   parents: " << vec << endl;

      delete verts;
   }

} // void DgIDGGS4D::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4D::setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent() || radix() == 3)
   {
      const DgIVec2D& lowerLeft = add.address().coord() * radix();

      vector<DgAddressBase*>& v = vec.addressVec();
      for (int i = 0; i < radix(); i++)
      {
         for (int j = 0; j < radix(); j++)
         {
            v.push_back(new DgAddress< DgResAdd<DgQ2DICoord> >(
             DgResAdd<DgQ2DICoord>(DgQ2DICoord(add.address().quadNum(),
                       DgIVec2D(lowerLeft.i() + i, lowerLeft.j() + j)), 
                               add.res() + 1)));
         }
      }
   }
   else // must be aligned aperture 4
   {
/*
      // only center square is interior

      DgLocation* tmpLoc = makeLocation(add);
      grids()[add.res() + 1]->convert(tmpLoc);
      vec.push_back(*tmpLoc);

      delete tmpLoc;
*/
   }
   
} // void DgIDGGS4D::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4D::setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   if (isCongruent() || radix() == 3)
   {
      // no boundary children in this topology; leave vec empty
   }
   else // must be aligned aperture 4
   {
/*
      DgLocation* tmpLoc = makeLocation(add);

      // D8 neighbors is what we want

      DgDmdD8Grid2D d8(network(), grids()[add.res() + 1]->backFrame(),
                       "dummyD8");
      d8.convert(tmpLoc);
      d8.setNeighbors(*tmpLoc, vec);

      grids()[add.res() + 1]->convert(vec);
      convert(vec);

      delete tmpLoc;
*/
   }

} // void DgIDGGS4D::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS4D::setAddAllChildren (const DgResAdd<DgQ2DICoord>& add, 
                                   DgLocVector& vec) const
{
   setAddInteriorChildren(add, vec);

/*
   DgLocVector bndVec(vec.rf());
   setAddBoundaryChildren(add, bndVec);

   for (int i = 0; i < bndVec.size(); i++) vec.push_back(bndVec[i]);
*/

} // void DgIDGGS4D::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgSuperfund.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgSuperfund.cpp: DgSuperfund class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgSuperfund.h"
#include "DgBase.h"

////////////////////////////////////////////////////////////////////////////////
int sfRes2actualRes (int sfRes)
{
   int actRes[] = { 1, 2, 4, 6, 8, 10, 12, 14, 16, 17 }; 

   int res = 0;
   if (sfRes < 0 || sfRes > 9)
      ::report( "sfRes2actualRes(): invalid sfRes", DgBase::Fatal);
   else
      res = actRes[sfRes];

   return res;
}

////////////////////////////////////////////////////////////////////////////////
int actualRes2sfRes (int actualRes)
{
   // res #         0  1  2   3  4   5  6   7  8   9 10  11 12  13 14  15 16 17 }; 
   int sfRes[] = { -1, 0, 1, -1, 2, -1, 3, -1, 4, -1, 5, -1, 6, -1, 7, -1, 8, 9 }; 

   int res = 0;
   if (actualRes < 0 || actualRes > 17)
      ::report( "actualRes2sfRes(): invalid actualRes", DgBase::Fatal);
   else
      res = sfRes[actualRes];

   return res;
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////



<|start_filename|>src/DgPhysicalRFS2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPhysicalRFS2D.h: DgPhysicalRFS2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPHYSICALRFS2D_H
#define DGPHYSICALRFS2D_H

#include "DgPhysicalRF.h"
#include "DgPhysicalRF2D.h"
#include "DgBoundedRFS2D.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
template<class C> class DgPhysicalRFS2D : 
          public DgPhysicalRF< DgResAdd<DgIVec2D>, C> {

   public:

      DgPhysicalRFS2D<C> (const DgBoundedRFS2D& rfIn, bool allocate = false);

      const DgBoundedRFS2D& boundedRFS2D (void) const { return boundedRFS2D_; }

      virtual void replaceAddContents (const DgResAdd<DgIVec2D>& add, 
                                       C* cont); // no copy

      virtual void setAddContents (const DgResAdd<DgIVec2D>& add, 
                                   const C& cont); // copy

      virtual C* getAddContents (const  DgResAdd<DgIVec2D>& add, 
                                 bool allocate = false) const;

      virtual void deleteAddContents (const DgResAdd<DgIVec2D>& add);

      const vector<DgPhysicalRF2D<C>*>& grids (void) const { return *grids_; }

   protected:

      const DgBoundedRFS2D& boundedRFS2D_;
      
      vector<DgPhysicalRF2D<C>*>* grids_;

};

#include "DgPhysicalRFS2D_template.h"

#endif


<|start_filename|>src/DgRFBase.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgRFBase.cpp: DgRFBase class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <list>

using namespace std;

#include "DgBase.h"
#include "DgRFBase.h"
#include "DgLocBase.h"
#include "DgLocation.h"
#include "DgLocVector.h"
#include "DgConverterBase.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgRFBase::~DgRFBase (void)
{
   /* JFW: We don't delete connectTo and connectFrom (we don't really own them);
   for that matter, I'm not sure we actually ever touch undefLoc_, below: */
   delete undefLoc_;

} // DgRFBase::~DgRFBase

////////////////////////////////////////////////////////////////////////////////
DgLocation* 
DgRFBase::convert (DgLocation* loc) const
{
   if (loc->rf_ == 0)
   {
      loc->rf_ = this;
      return loc;
   }
   
   if (network() != loc->rf().network())
   {
      report("DgRFBase::convert() from/to network mismatch",
             DgBase::Fatal);
      return 0;
   }

   if (loc->rf() == *this) return loc;

   if (loc->address() == 0)
   {
      loc->rf_ = this;
      return loc;
   }
   
   // if we're here we need to convert

   const DgConverterBase* conv = network().getConverter(loc->rf(), *this);
   if (!conv)
   {
      report("DgRFBase::convert() getConverter error", DgBase::Fatal);
      return 0;
   }

   return conv->convert(loc);

} // DgLocation* DgRFBase::convert

////////////////////////////////////////////////////////////////////////////////
DgLocVector& 
DgRFBase::convert (DgLocVector& vec) const
{
   if (vec.rf_ == 0)
   {
      vec.rf_ = this;
      return vec;
   }
   
   if (network() != vec.rf().network())
   {
      report("DgRFBase::convert() from/to network mismatch",
             DgBase::Fatal);
      return vec;
   }

   if (vec.rf() == *this) return vec;

   if (vec.size() == 0)
   {
      vec.rf_ = this;
      return vec;
   }
   
   // if we're here we need to convert

   const DgConverterBase* conv = network().getConverter(vec.rf(), *this);
   if (!conv)
   {
      report("DgRFBase::convert() getConverter error", DgBase::Fatal);
      return vec;
   }

   vector<DgAddressBase*>& v = vec.addressVec();
   for (unsigned long i = 0; i < v.size(); i++)
   {
      DgAddressBase* addIn = v[i];

      if (addIn) 
       v[i] = conv->createConvertedAddress(*addIn);

      delete addIn;
   }

   vec.rf_ = this;
   vec.tmpLoc_.rf_ = this;

   return vec;

} // DgLocVector& DgRFBase::convert

////////////////////////////////////////////////////////////////////////////////
DgLocation* 
DgRFBase::createLocation (void) const
{
   return new DgLocation(*this, 0);

} // DgLocation* DgRFBase::createLocation

////////////////////////////////////////////////////////////////////////////////
DgLocation* 
DgRFBase::buildLocation (DgAddressBase* addIn) const
{
   return new DgLocation(*this, addIn);

} // DgLocation* DgRFBase::buildLocation

////////////////////////////////////////////////////////////////////////////////
ostream&
DgRFBase::traceToGround (ostream& stream) const
{
   stream << "tracing " << name() << " {";

   if (id() == 0) return stream << " at ground }" << endl;

   if (!connectTo()) return stream << " => NULL }" << endl;

   stream << "\n";

   const DgRFBase* to = connectTo();
   while (true)
   {
      if (!to) return stream << "  => NULL }" << endl;

      // at ground?

      if (to->id() == 0)
      {
         stream << "  => at ground: " << to->name() << "\n";
         break;
      }

      // otherwise continue

      stream << "  => " << to->name() << "\n";
      to = to->connectTo();
   }

   // now go back from ground

   list<const DgRFBase*> rev;
   const DgRFBase* from = connectFrom();
   while (true)
   {
      if (!from) return stream << "  => NULL }" << endl;

      // at ground?

      if (from->id() == 0) break;

      // otherwise continue

      rev.push_front(from);
      from = from->connectFrom();
   }

   list<const DgRFBase*>::iterator it = rev.begin();
   for (; it != rev.end(); it++) stream << "  => " << (*it)->name() << "\n";

   return stream << " => " << name() << " }" << endl;  

} // void DgRFBase::traceToGround

////////////////////////////////////////////////////////////////////////////////
string
DgRFBase::toString (const DgLocBase& lb) const
{
   return lb.asString();

} // string DgRFBase::toString

////////////////////////////////////////////////////////////////////////////////
string
DgRFBase::toAddressString (const DgLocBase& lb) const
{
   return lb.asAddressString();

} // string DgRFBase::toAddressString

////////////////////////////////////////////////////////////////////////////////
string
DgRFBase::toString (const DgLocBase& lb, char delimiter) const
{
   return lb.asString(delimiter);

} // string DgRFBase::toString

////////////////////////////////////////////////////////////////////////////////
string
DgRFBase::toAddressString (const DgLocBase& lb, char delimiter) const
{
   return lb.asAddressString(delimiter);

} // string DgRFBase::toAddressString

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////



<|start_filename|>src/DgUtil.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgUtil.cpp: DgUtil class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgUtil.h"

namespace dgg { namespace util {

long rint(const float& x)
{
 return static_cast<long>(std::ceil(x));
}

}} // namespace dgg::util


<|start_filename|>src/DgOutKMLfile.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutKMLfile.cpp: DgOutKMLfile class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <sstream>
#include <iostream>

#include "DgOutKMLfile.h"
#include "DgLocList.h"
#include "DgPolygon.h"
#include "DgLocation.h"
#include "DgCell.h"
#include "DgGeoSphRF.h"

DgOutKMLfile::DgOutKMLfile(const DgGeoSphDegRF& rf, const std::string& filename, 
    int precision, bool isPointFile, const string& colorIn, int widthIn, 
    const string& nameIn, const string& descIn, DgReportLevel failLevel)
   : DgOutLocTextFile (filename, rf, isPointFile, "kml", precision, failLevel)
{
   if (0 == rf.vecAddress(DgDVec2D()))
   {
      DgOutputStream::report("DgOutKMLfile::DgOutKMLfile(): RF " + rf.name() +
        " must override the vecAddress() method", DgBase::Fatal);
   }

   setColor(colorIn);
   setWidth(widthIn);
   setName(nameIn);
   setDescription(descIn);

   setFormatStr();

   preamble();
}

void 
DgOutKMLfile::setColor (const string& colorIn)
{
   if (colorIn.length() != 8)
      DgOutputStream::report("DgOutKMLfile::setColor(): invalid KML color " + colorIn,
             DgBase::Fatal);

/* can't find regex so not compiling...
   std::regex e("[0-9a-fA-F]*");
   if (!std::regex_match(colrIn, e))
      DgOutputStream::report("DgOutKMLfile::setColor(): invalid KML color " + colorIn,
             DgBase::Fatal);
*/

   for (unsigned int i = 0; i < colorIn.length(); i++)
   {
      char c = colorIn[i];
      if (!(c >= '0' && c <= '9') &&
          !(c >= 'a' && c <= 'f') &&
          !(c >= 'A' && c <= 'F'))
         DgOutputStream::report("DgOutKMLfile::setColor(): invalid KML color " + colorIn,
             DgBase::Fatal);
   }

   color_ = colorIn;
}

void 
DgOutKMLfile::setWidth (int widthIn)
{
   if (widthIn < 1)
      DgOutputStream::report("DgOutKMLfile::setColor(): invalid negative width",
             DgBase::Fatal);

   width_ = widthIn;
}

void 
DgOutKMLfile::setName (const string& nameIn)
{
   name_ = nameIn;
}

void 
DgOutKMLfile::setDescription (const string& descIn)
{
   description_ = descIn;
}

DgOutKMLfile::~DgOutKMLfile()
{
   postamble();
   close();
}

void DgOutKMLfile::preamble()
{
   DgOutKMLfile& o(*this);   // make life a bit easier

   o << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
     << "<kml xmlns=\"http://earth.google.com/kml/2.1\">\n";

   o << "<Folder>\n";

   o << "   <name>dgout</name>\n";
   // if (name_ == "")
   //    o << o.DgOutputStream::fileName();
   // else
   //    o << name_;
   //o << "dgout</name>\n";

   o << "   <description>";
   o << description_;
   o << "</description>\n";

   o << "   <Style id=\"lineStyle1\">\n";
   o << "      <LineStyle id=\"lineStyle2\">\n";
   o << "         <color>" << color_ << "</color>\n";
   o << "         <width>" << width_ << "</width>\n";
   o << "      </LineStyle>\n";
   o << "   </Style>\n";

   o.flush();
}

void DgOutKMLfile::postamble()
{
   DgOutKMLfile& o(*this);   

   o << "</Folder>\n" << "</kml>\n" ;
   o.flush();
}

DgOutLocFile& 
DgOutKMLfile::insert(const DgDVec2D& pt)
{
   DgOutKMLfile& o(*this);

   o << "            "
     << std::setprecision(getPrecision()) << (double) pt.x()
     << ","
     << std::setprecision(getPrecision()) << (double) pt.y()
     << ",0.0\n";

   return o;
}

DgOutLocFile& 
DgOutKMLfile::insert (DgLocation& loc, const string* label)
{
   DgOutKMLfile& o(*this);

   rf().convert(&loc);

   o << "   <Placemark>\n";

   if (label)
      o << "      <name>" << *label << "</name>\n";

   o << "      <Point>\n";
   o << "         <coordinates>\n";

   o.insert(rf().getVecLocation(loc));

   o << "         </coordinates>\n";
   o << "      </Point>\n";
   o << "   </Placemark>\n";

   return *this;
}

DgOutLocFile& 
DgOutKMLfile::insert (DgLocVector& vec, const string* label, const DgLocation* cent)
{
   DgOutKMLfile& o(*this);   

   rf().convert(vec);

   o << "<Placemark>\n";

   if (label)
      o << "   <name>" << *label << "</name>\n";

   o << "      <styleUrl>#lineStyle1</styleUrl>\n";
   o << "      <LineString>\n";
   o << "         <tessellate>1</tessellate>\n";
   o << "         <coordinates>\n";

   vector<DgAddressBase *>& v = vec.addressVec();
   for(vector<DgAddressBase *>::iterator i = v.begin(); v.end() != i; ++i)
         o.insert(rf().getVecAddress(*(*i)));

   o << "         </coordinates>\n";
   o << "      </LineString>\n";
   o << "</Placemark>\n";

   o.flush();

   return *this;
}

DgOutLocFile& 
DgOutKMLfile::insert (DgPolygon& poly, const string* label, const DgLocation* cent)
{
   DgOutKMLfile& o(*this);   

   rf().convert(poly);

   o << "<Placemark>\n";

   if (label)
      o << "<name>" << *label << "</name>\n";

   o << "      <styleUrl>#lineStyle1</styleUrl>\n";
   o << "      <LineString>\n";
   o << "         <tessellate>1</tessellate>\n";
   o << "         <coordinates>\n";

   vector<DgAddressBase *>& v = poly.addressVec();
   for(vector<DgAddressBase *>::iterator i = v.begin(); v.end() != i; ++i)
         o.insert(rf().getVecAddress(*(*i)));

   // rewrite first vertex:
   o.insert(rf().getVecAddress(*v[0]));

   o << "         </coordinates>\n";
   o << "      </LineString>\n";
   o << "</Placemark>\n";

   o.flush();

   return *this;
}


<|start_filename|>src/DgProjGnomonicRF.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgProjGnomonicRF.cpp: DgProjGnomonicRF class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgProjGnomonicRF.h"
#include "DgEllipsoidRF.h"
#include "proj4.h"

#define EPS10 1.e-10L
#define N_POLE 0
#define S_POLE 1
#define EQUIT  2
#define OBLIQ  3

////////////////////////////////////////////////////////////////////////////////
DgProjGnomonicRF::DgProjGnomonicRF(DgRFNetwork& networkIn, const string& nameIn,
       const DgGeoCoord& proj0In, long double x0In, long double y0In, long double k0In, 
       long double to_meterIn, long double fr_meterIn)
   : DgGeoProjRF (networkIn, nameIn, proj0In, x0In, y0In, k0In, 
                  to_meterIn, fr_meterIn)
{ 
   if (fabs(fabs(phi0()) - dgM_PI_2) < EPS10)
      mode_ = phi0() < 0.0L ? S_POLE : N_POLE;
   else if (fabs(phi0()) < EPS10)
      mode_ = EQUIT;
   else {
      mode_ = OBLIQ;
      sinph0_ = sin(phi0());
      cosph0_ = cos(phi0());
   }

} // DgProjGnomonicRF::DgProjGnomonicRF

////////////////////////////////////////////////////////////////////////////////
DgDVec2D
DgProjGnomonicRF::projForward (const DgGeoCoord& addIn,
                               const DgEllipsoidRF& e) const
{
   //cout << "gnom projForward: " << *this << " coord: " << addIn << endl;

   DgDVec2D xy(DgDVec2D::undefDgDVec2D);

   long double  coslam, cosphi, sinphi;

   sinphi = sin(addIn.lat());
   cosphi = cos(addIn.lat());
   coslam = cos(addIn.lon());

   switch (mode_) {
   case EQUIT:
      xy.setY(cosphi * coslam);
      break;
   case OBLIQ:
      xy.setY(sinph0_ * sinphi + cosph0_ * cosphi * coslam);
      break;
   case S_POLE:
      xy.setY(- sinphi);
      break;
   case N_POLE:
      xy.setY(sinphi);
      break;
   }

   if (xy.y() <= EPS10) 
   {
      ::report(string("DgProjGnomonicRF::projForward() point out of range\n") +
           string("proj0: ") + string(proj0()) + 
           string("\nprojecting point: ") + string(addIn), DgBase::Fatal);
   }

   xy.setY(1.0L / xy.y());
   xy.setX(xy.y() * cosphi * sin(addIn.lon()));

   switch (mode_) {
   case EQUIT:
      xy.setY(xy.y() * sinphi);
      break;
   case OBLIQ:
      xy.setY(xy.y() * (cosph0_ * sinphi - sinph0_ * cosphi * coslam));
      break;
   case N_POLE:
      coslam = - coslam;
   case S_POLE:
      xy.setY(xy.y() * cosphi * coslam);
      break;
   }

   //cout << "     => " << xy << endl;

   return (xy);

} // DgDVec2D DgProjGnomonicRF::projForward

////////////////////////////////////////////////////////////////////////////////
DgGeoCoord
DgProjGnomonicRF::projInverse (const DgDVec2D& addIn, 
                               const DgEllipsoidRF& e) const
//
// spheroid only; needs to be verified at some point
//
{
   DgDVec2D xy(addIn);
   DgGeoCoord lp;

   long double  rh, cosz, sinz;

   rh = usgs_hypot(xy.x(), xy.y());
   lp.setLat(atan(rh));
   sinz = sin(lp.lat());
   cosz = sqrt(1. - sinz * sinz);
   if (fabs(rh) <= EPS10) {
      lp.setLat(phi0());
      lp.setLon(0.0L);
   } else {
      switch (mode_) {
      case OBLIQ:
         lp.setLat(cosz * sinph0_ + xy.y() * sinz * cosph0_ / rh);
         if (fabs(lp.lat()) >= 1.0L)
            lp.setLat(lp.lat() > 0.0L ? dgM_PI_2 : - dgM_PI_2);
         else
            lp.setLat(asin(lp.lat()));
         xy.setY((cosz - sinph0_ * sin(lp.lat())) * rh);
         xy.setX(xy.x() * sinz * cosph0_);
         break;
      case EQUIT:
         lp.setLat(xy.y() * sinz / rh);
         if (fabs(lp.lat()) >= 1.0L)
            lp.setLat(lp.lat() > 0.0L ? dgM_PI_2 : - dgM_PI_2);
         else
            lp.setLat(asin(lp.lat()));
         xy.setY(cosz * rh);
         xy.setX(xy.x() * sinz);
         break;
      case S_POLE:
         lp.setLat(lp.lat() - dgM_PI_2);
         break;
      case N_POLE:
         lp.setLat(dgM_PI_2 - lp.lat());
         xy.setY(-xy.y());
         break;
      }
      lp.setLon(atan2(xy.x(), xy.y()));
   }
   return (lp);

} // DgGeoCoord DgProjGnomonicRF::projInverse

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgBoundedRFS2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedRFS2D.h: DgBoundedRFS2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBOUNDEDRFS2D_H
#define DGBOUNDEDRFS2D_H

#include <cstdint>

#include "DgDiscRFS2D.h"
#include "DgBoundedRF2D.h"
#include "DgIVec2D.h"

class DgLocation;
class DgBoundedRFS2D;

////////////////////////////////////////////////////////////////////////////////
class DgBoundedRFS2D 
        : public DgBoundedRF<DgResAdd<DgIVec2D>, DgDVec2D, long double > {

   public:

      DgBoundedRFS2D (const DgDiscRFS2D& rf, 
                      const DgIVec2D& lowerLeft0, const DgIVec2D& upperRight0);
                    
      virtual DgResAdd<DgIVec2D>& incrementAddress 
                                      (DgResAdd<DgIVec2D>& add) const;

      virtual DgResAdd<DgIVec2D>& decrementAddress 
                                      (DgResAdd<DgIVec2D>& add) const;

      virtual bool validAddress (const DgResAdd<DgIVec2D>& add) const
          { return add == endAdd() || (add.res() >= 0 && 
                   add.res() < discRFS().nRes() && 
                   grids()[add.res()]->validAddress(add.address())); }

      const DgResAdd<DgIVec2D>& invalidAdd (void) const 
              { return discRFS().undefAddress(); }

      const DgDiscRFS2D& discRFS (void) const { return discRFS_; }

      const vector<DgBoundedRF2D*>& grids (void) const { return *grids_; }

      virtual std::uint64_t seqNumAddress (const DgResAdd<DgIVec2D>& add) 
                                                                        const;

      virtual DgResAdd<DgIVec2D> addFromSeqNum (std::uint64_t sNum) const;

   private:

      const DgDiscRFS2D& discRFS_;

      vector<DgBoundedRF2D*>* grids_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgOutPtsText.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutPtsText.cpp: DgOutPtsText class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <list>
#include <sstream>

#include "DgOutPtsText.h"
#include "DgLocList.h"
#include "DgPolygon.h"
#include "DgLocation.h"
#include "DgCell.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutPtsText::DgOutPtsText (const DgRFBase& rfIn, const string& fileNameIn, 
                          int precision, DgReportLevel failLevel)
   : DgOutLocTextFile (fileNameIn, rfIn, true, "txt", precision, failLevel)
{
   if (rfIn.vecAddress(DgDVec2D(M_ZERO, M_ZERO)) == 0)
   {
      DgOutputStream::report("DgOutPtsText::DgOutPtsText(): RF " + rfIn.name() +
             " must override the vecAddress() method", DgBase::Fatal);
   }

   setFormatStr();

} // DgOutPtsText::DgOutPtsText

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutPtsText::insert (const DgDVec2D& pt)
//
// Put the point pt.
//
////////////////////////////////////////////////////////////////////////////////
{
   const int maxBuffSize = 200;
   char buff[maxBuffSize];

   sprintf(buff, formatStr(), pt.x(), pt.y());

   *this << buff;

   return *this;

} // DgOutLocFile& DgOutPtsText::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutPtsText::insert (DgLocation& loc, const string* label)
//
// Put the point loc.
//
////////////////////////////////////////////////////////////////////////////////
{
   rf().convert(&loc);

   if (label)
     *this << *label << ",";
   else
     *this << "0,";

   this->insert(rf().getVecLocation(loc));

   return *this;

} // DgOutLocFile& DgOutPtsText::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutPtsText::insert (DgLocVector& vec, const string* label, 
                     const DgLocation* cent)
//
// Put the polyline vec.
//
////////////////////////////////////////////////////////////////////////////////
{
   DgOutputStream::report("DgOutPtsText::insert(DgLocVector): not defined.", DgBase::Fatal);
   return *this;

} // DgOutLocFile& DgOutPtsText::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutPtsText::insert (DgPolygon& poly, const string* label, 
                     const DgLocation* cent)
//
// Put the polygon poly.
//
////////////////////////////////////////////////////////////////////////////////
{
   DgOutputStream::report("DgOutPtsText::insert(DgPolygon): not defined.", DgBase::Fatal);
   return *this;

   return *this;

} // DgOutLocFile& DgOutPtsText::insert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/pj_msfn.cpp<|end_filename|>
/* determine constant small m */
#include <cmath>
	long double
pj_msfn(long double sinphi, long double cosphi, long double es) {
	return (cosphi / std::sqrt (1. - es * sinphi * sinphi));
}


<|start_filename|>src/DgBoundedRF.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedRF.h: DgBoundedRF class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBOUNDEDRF_H
#define DGBOUNDEDRF_H

#include <cstdint>

#include "DgBoundedRFBase.h"
#include "DgDiscRF.h"
#include "DgPolygon.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<class A, class B, class DB> class DgBoundedRF 
                                         : public DgBoundedRFBase<B, DB> {

   public:

      DgBoundedRF<A, B, DB> (const DgDiscRF<A, B, DB>& rfIn, 
                             const A& firstAddIn, 
                             const A& lastAddIn, const A& endAddIn,
                             bool zBasedIn = true);
                          
      const DgDiscRF<A, B, DB>& discRF (void) const { return discRF_; }

      virtual bool validLocation (const DgLocation& loc, 
                                  bool convert = true) const;

      virtual DgLocation& incrementLocation (DgLocation& loc, 
                                             bool convert = true) const;
                       
      virtual DgLocation& decrementLocation (DgLocation& loc, 
                                             bool convert = true) const; 

      virtual std::uint64_t seqNum (const DgLocation& loc,
                                        bool convert = true) const;

      virtual DgLocation* locFromSeqNum (std::uint64_t sNum) const;
                                             
      const A& firstAdd (void) const { return firstAdd_; }
      const A& lastAdd  (void) const { return lastAdd_; }
      const A& endAdd   (void) const { return endAdd_; }

      // provide a generic interface to the discrete grid functionality

      virtual const DgRF<B, DB>& backFrame (void) const
                     { return discRF().backFrame(); }

      virtual string dist2str (const std::int64_t& dist) const
                     { return discRF().dist2str(dist); }

      virtual long double dist2dbl (const std::int64_t& dist) const
                     { return discRF().dist2dbl(dist); }

      virtual std::uint64_t dist2int (const std::int64_t& dist) const
                     { return discRF().dist2int(dist); }

      virtual void setPoint (const DgLocation& loc, DgLocation& point) const
                   { discRF().setPoint(loc, point); }

      virtual void setPoint (const DgLocation& loc, const DgRFBase& rf,
                                                       DgLocation& point) const
                   { discRF().setPoint(loc, rf, point); }

      virtual void setPoint (const A& add, const DgRFBase& rf, 
                                                       DgLocation& point) const
                   { discRF().setPoint(add, rf, point); }

      virtual void setPoint (const A& add, DgLocation& pt) const
                   { discRF().setPoint(add, pt); }

      virtual void setVertices (const DgLocation& loc, DgPolygon& vec) const
                   { discRF().setVertices(loc, vec); }

      virtual void setVertices (const DgLocation& loc, const DgRFBase& rf,
                                                        DgPolygon& vec) const
                   { discRF().setVertices(loc, rf, vec); }

      virtual void setVertices (const A& add, const DgRFBase& rf, 
                                                        DgPolygon& vec) const
                   { discRF().setVertices(add, rf, vec); }

      virtual void setNeighbors (const DgLocation& loc, DgLocVector& vec) const
                   { discRF().setNeighbors(loc, vec); }

      virtual void setNeighbors (const A& add, const DgRFBase& rf, 
                                                        DgLocVector& vec) const
                   { discRF().setNeighbors(add, rf, vec); }

      virtual void setNeighbors (const A& add, DgLocVector& vec) const
                   { discRF().setNeighbors(add, vec); }

      virtual void setVertices  (const A& add, DgPolygon& vec) const
                   { discRF().setVertices(add, vec); }

      virtual DgLocation* makePoint (const DgLocation& loc) const
                   { return discRF().makePoint(loc); }

      virtual DgPolygon* makeVertices (const DgLocation& loc) const
                   { return discRF().makeVertices(loc); }

      virtual DgLocVector* makeNeighbors (const DgLocation& loc) const
                   { return discRF().makeNeighbors(loc); }

      // pure virtual functions that must be defined by sub-classes

      virtual bool validAddress (const A& add) const = 0;
      
      virtual A& incrementAddress (A& add) const = 0;
      virtual A& decrementAddress (A& add) const = 0;

      virtual std::uint64_t seqNumAddress (const A& loc) const = 0;

      virtual A addFromSeqNum (std::uint64_t sNum) const = 0;

      virtual bool lessThanAddress (const A& a1, const A& a2) const
                      { return (seqNumAddress(a1) < seqNumAddress(a2)); }
                                             
   protected:

      void setFirstAdd (const A& firstAddIn) { firstAdd_ = firstAddIn; }
      void setLastAdd  (const A& lastAddIn)  { lastAdd_ = lastAddIn; }
      void setEndAdd   (const A& endAddIn)   { endAdd_ = endAddIn; }

   private:

      const DgDiscRF<A, B, DB>& discRF_;
         
      A firstAdd_;
      A lastAdd_;
      A endAdd_;
      
};

#include "DgBoundedRF_template.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgHexGrid2DS.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgHexGrid2DS.h: DgHexGrid2DS class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGHEXGRID2DS_H 
#define DGHEXGRID2DS_H 

#include "DgRF.h"
#include "DgLocVector.h"
#include "DgDiscRFS2D.h"
#include "DgIVec2D.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DgHexGrid2DS : public DgDiscRFS2D {

   public:

      DgHexGrid2DS (DgRFNetwork& network, 
                 const DgRF<DgDVec2D, long double>& backFrame,
                 int nRes = 1, unsigned int aperture = 4, 
                 bool isCongruent = true, bool isAligned = false,
                 const string& name = "6H4", bool isMixed43 = false,
                 int numAp4 = 0, bool isSuperfund = false);

      DgHexGrid2DS (const DgHexGrid2DS& rf);

     ~DgHexGrid2DS (void);

      DgHexGrid2DS& operator= (const DgHexGrid2DS& rf);

      long double frequency     (void) const { return frequency_; }
      bool     isMixed43     (void) const { return isMixed43_; }
      int      numAp4        (void) const { return numAp4_; }
      bool     isSuperfund   (void) const { return isSuperfund_; }

   protected:

      long double frequency_;

      // pure virtual functions from DgDiscRFS

      virtual void setAddParents (const DgResAdd<DgIVec2D>& add,
                                  DgLocVector& vec) const;

      virtual void setAddInteriorChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddBoundaryChildren (const DgResAdd<DgIVec2D>& add,
                                           DgLocVector& vec) const;

      virtual void setAddAllChildren (const DgResAdd<DgIVec2D>& add,
                                      DgLocVector& vec) const;

   private:

      bool isMixed43_;
      int  numAp4_;
      bool isSuperfund_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgLocBase.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgLocBase.h: DgLocBase class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGLOCBASE_H
#define DGLOCBASE_H

#include <string>
#include <iostream>

using namespace std;

class DgRFBase;

////////////////////////////////////////////////////////////////////////////////
class DgLocBase {

   public:

      virtual ~DgLocBase (void);

      const DgRFBase& rf (void) const { return *rf_; }

      virtual int cardinality (void) const { return 1; } // default

      virtual string asString (void) const = 0;

      virtual string asString (char delimiter) const = 0;

      virtual string asAddressString (void) const = 0;

      virtual string asAddressString (char delimiter) const = 0;

      virtual const char* fromString (const char* str, char delimiter) = 0;

      virtual void clearAddress (void) = 0;

   protected:

      DgLocBase (void) : rf_ (0) { }

      DgLocBase (const DgRFBase& rfIn) : rf_ (&rfIn) { }

      const DgRFBase* rf_;

      virtual void convertTo (const DgRFBase& rf) = 0;

   friend class DgRFBase;
   friend class DgConverterBase;
   friend class DgLocList;

};

////////////////////////////////////////////////////////////////////////////////
inline ostream& operator<< (ostream& stream, const DgLocBase& loc)
            { return stream << loc.asString(); }

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgLocVector.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgLocVector.cpp: DgLocVector class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cstdint>

#include "DgLocVector.h"

////////////////////////////////////////////////////////////////////////////////
DgLocVector::DgLocVector (const DgRFBase& rfIn, int sizeIn)
   : DgLocBase (rfIn)
{
   vec_.resize(sizeIn);

   for (std::int64_t i = 0; i < size(); i++) 
     vec_[i] = rf().createAddress();

} // DgLocVector::DgLocVector

////////////////////////////////////////////////////////////////////////////////
void
DgLocVector::clearAddress (void)
{
   tmpLoc_.address_ = 0;

   for (std::int64_t i = 0; i < size(); i++)
   {
      delete vec_[i];
      vec_[i] = 0;
   }

   resize(0);

} // void DgLocVector::clearAddress

////////////////////////////////////////////////////////////////////////////////
bool
DgLocVector::operator== (const DgLocVector& vec) const
{ 
   if (rf() != vec.rf() || vec.size() != size()) 
    return false;

   for (int i = 0; i < size(); i++)
   {
      if (!rf().equalAddress(*vec_[i], *vec[i].address())) 
       return false;
   }

   return true;

} // bool DgLocVector::operator==

////////////////////////////////////////////////////////////////////////////////
void 
DgLocVector::setLoc (int ndx, const DgLocation& loc, bool conv)
{
   if (rf() == loc.rf()) 
   {
      rf().copyAddress(*loc.address(), vec_[ndx]);
      return;
   }

   // otherwise need to convert

   DgLocation newLoc(loc);
   rf().convert(&newLoc);
   rf().copyAddress(*newLoc.address(), vec_[ndx]);

} // void DgLocVector::setLoc

////////////////////////////////////////////////////////////////////////////////
void 
DgLocVector::push_back (const DgLocation& loc, bool conv)
{
   if (rf() == loc.rf()) 
   {
      DgAddressBase* add = rf().createAddress(*loc.address());
      vec_.push_back(add);
      return;
   }

   // otherwise need to convert

   DgLocation newLoc(loc);
   rf().convert(&newLoc);
   DgAddressBase* add = rf().createAddress(*newLoc.address());
   vec_.push_back(add);

} // void DgLocVector::push_back

////////////////////////////////////////////////////////////////////////////////
const char*
DgLocVector::fromString (const char* str, char delimiter)
{
   clearAddress();

   DgLocation tloc(rf());
   const char* tmp = str;
   while (*tmp)
   {
      tmp = tloc.fromString(tmp, delimiter);
      push_back(tloc);  
      if (*tmp == delimiter) 
       tmp++;
   }

   return tmp;

} // DgLocVector::fromString

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgConverterBase.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgConverterBase.cpp: DgConverterBase class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgBase.h"
#include "DgString.h"
#include "DgConverterBase.h"

bool DgConverterBase::isTraceOn_ = false;
//ostream* DgConverterBase::traceStream_ = &cout;

////////////////////////////////////////////////////////////////////////////////
DgConverterBase::~DgConverterBase (void)
{ 
   // virtual destructor 

} // DgConverterBase::~DgConverterBase

////////////////////////////////////////////////////////////////////////////////
DgConverterBase::DgConverterBase (const DgRFBase& fromFrame, 
                                  const DgRFBase& toFrame,
                                  bool userGeneratedIn)
    : fromFrame_ (const_cast<DgRFBase*>(&fromFrame)), 
      toFrame_ (const_cast<DgRFBase*>(&toFrame)),
      userGenerated_ (userGeneratedIn)
{
   // check for network match

   if (fromFrame.network() != toFrame.network())
   {
      report("DgConverterBase::DgConverterBase() from/to network mismatch",
             DgBase::Fatal);
      return;
   }

   if (userGenerated())
   {
      // override any existing converter

      if (fromFrame.network_->existsConverter(fromFrame, toFrame))
      {
         delete const_cast<DgRFNetwork*>(fromFrame.network_)
                           ->matrix_[fromFrame.id()][toFrame.id()];
      }

      // if we're here we're neither a passthrough nor an identity converter
      
      const_cast<DgRFNetwork*>(fromFrame.network_)
                           ->matrix_[fromFrame.id()][toFrame.id()] = this;

      // make any connections this gives us; note we are indirectly changing
      // the const frames here
      
      if (fromFrame_->id() != 0 && fromFrame_->connectTo() == 0 &&
          toFrame_->connectTo()) 
      {
         fromFrame_->connectTo_ = toFrame_; 
      }

      if (toFrame_->id() != 0 && toFrame_->connectFrom() == 0 &&
          fromFrame_->connectFrom()) 
      {
         toFrame_->connectFrom_ = fromFrame_;
      }
   }

} // DgConverterBase::DgConverterBase

////////////////////////////////////////////////////////////////////////////////
DgConverterBase&
DgConverterBase::operator= (const DgConverterBase& con)
{
   fromFrame_ = &const_cast<DgRFBase&>(con.fromFrame());
   toFrame_ = &const_cast<DgRFBase&>(con.toFrame());
   userGenerated_ = con.userGenerated();

   return *this;

} // DgConverterBase& DgConverterBase::operator=

////////////////////////////////////////////////////////////////////////////////
void
DgConverterBase::forceConnectFrom (bool verify) const
{
   if (verify && !fromFrame_->connectFrom())
   {
      report("DgConverter::forceConnectFrom() dangling connection",
              DgBase::Fatal);
   }

   toFrame_->connectFrom_ = fromFrame_;

   const_cast<DgRFNetwork&>(fromFrame_->network()).matrix_
                                    [fromFrame_->id()][toFrame_->id()] 
                                          = const_cast<DgConverterBase*>(this);

} // void DgConverterBase::forceConnectFrom

////////////////////////////////////////////////////////////////////////////////
void
DgConverterBase::forceConnectTo (bool verify) const
{
   if (!toFrame_->connectTo())
   {
      report("DgConverter::forceConnectTo() dangling connection",
              DgBase::Fatal);
   }

   fromFrame_->connectTo_ = toFrame_;

   const_cast<DgRFNetwork&>(fromFrame_->network()).matrix_
                                    [fromFrame_->id()][toFrame_->id()] 
                                          = const_cast<DgConverterBase*>(this);

} // void DgConverterBase::forceConnectTo

////////////////////////////////////////////////////////////////////////////////
DgLocation* 
DgConverterBase::convert (DgLocation* loc) const
{
   // verify grid

   if (loc->rf() != fromFrame())
   {
      report("DgConverter::convert(" + loc->asString() + ") frame " + 
             loc->rf().name() + " does not match fromFrame " + 
             fromFrame().name(), DgBase::Fatal);

      return loc;
   }

   //if (isTraceOn()) traceStream() << *loc;
   
   loc->rf_ = &toFrame();

   DgAddressBase* tmpAdd = createConvertedAddress(*loc->address());
   delete loc->address_;
   loc->address_ = tmpAdd;

   //if (isTraceOn()) traceStream() << "->" << *loc << endl;
  
   return loc;

} // DgLocation* DgConverterBase::convert

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////



<|start_filename|>src/DgPolygon.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgPolygon.h: DgPolygon class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGPOLYGON_H
#define DGPOLYGON_H

#include "DgLocVector.h"

////////////////////////////////////////////////////////////////////////////////
class DgPolygon : public DgLocVector {

   public:

      DgPolygon (void) { }

      DgPolygon (const DgLocVector& vec)    // deep copy
         : DgLocVector (vec) { }

      DgPolygon (const DgPolygon& vec)    // deep copy
         : DgLocVector (vec) { }

      DgPolygon (const DgRFBase& rfIn, int sizeIn = 0)
         : DgLocVector (rfIn, sizeIn) { }

      const DgPolygon& operator= (const DgPolygon& vec) // deep copy
         { return reinterpret_cast<DgPolygon&>(DgLocVector::operator=(vec)); }

      bool operator== (const DgPolygon& vec) const
         { return DgLocVector::operator==(vec); }

      bool operator!= (const DgPolygon& vec) const
            { return !operator==(vec); }

      void densify (int ptsPerEdge);

};

////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/util.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// util.cpp: util class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////
#include "util.h"

#include <iostream>

namespace dgg { namespace util {

void ssplit(const std::string& src, std::vector<std::string>& dest, const char *delim)
{
 for(char *name = strtok(const_cast<char *>(src.c_str()), delim); 0 != name; name = strtok(0, delim))
  dest.push_back(name);
}

void ssplit(const char *src, std::vector<std::string>& dest, const char *delim)
{
 std::string s(src);
 return ssplit(s, dest, delim);
}


}} // namespace dgg::util


<|start_filename|>src/DgDmdD8Grid2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgDmdD8Grid2D.h: DgDmdD8Grid2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGDMDGRIDD82D_H 
#define DGDMDGRIDD82D_H

#include <cstdint>

#include "DgDmdD4Grid2D.h"

////////////////////////////////////////////////////////////////////////////////
class DgDmdD8Grid2D : public DgDmdD4Grid2D {

   public:

      DgDmdD8Grid2D (DgRFNetwork& networkIn, 
                     const DgRF<DgDVec2D, long double>& contCartFrameIn,
                     const string& nameIn = "Dmd2D")
         : DgDmdD4Grid2D (networkIn, contCartFrameIn, nameIn) { }

      DgDmdD8Grid2D (const DgDmdD8Grid2D& grd) 
         : DgDmdD4Grid2D (grd) {}

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const
      { 
	std::uint64_t diffi = abs(add2.i() - add1.i());
	std::uint64_t diffj = abs(add2.j() - add1.j());
        return (diffi >= diffj) ? diffi : diffj; 
      }

   protected:

      virtual void setAddNeighbors (const DgIVec2D& add, DgLocVector& vec) 
                                                                        const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgHexC2Grid2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgHexC2Grid2D.h: DgHexC2Grid2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGHEXC2GRID2D_H 
#define DGHEXC2GRID2D_H

#include <cmath>
#include <cstdint>

#include "DgDiscRF2D.h"
#include "DgDVec2D.h"
#include "DgIVec2D.h"

class DgHexC1Grid2D;
class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgHexC2Grid2D : public DgDiscRF2D {

   public:

      DgHexC2Grid2D (DgRFNetwork& networkIn, 
                     const DgRF<DgDVec2D, long double>& ccFrameIn,
                     const string& nameIn = "HexC12D");

      DgHexC2Grid2D (const DgHexC2Grid2D& grd) : DgDiscRF2D (grd) {}

      DgHexC2Grid2D& operator= (const DgHexC2Grid2D& grd)
           { DgDiscRF2D::operator=(grd); return *this; }

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const;

      const DgHexC1Grid2D& surrogate (void) const { return *surrogate_; }
      const DgHexC1Grid2D& substrate (void) const { return *substrate_; }

   protected:

      static const long double sin60_;

      DgHexC1Grid2D* surrogate_;
      DgHexC1Grid2D* substrate_;

      virtual void setAddVertices (const DgIVec2D& add, DgPolygon& vec) const;

      virtual void setAddNeighbors 
                                  (const DgIVec2D& add, DgLocVector& vec) const;

      virtual DgIVec2D quantify (const DgDVec2D& point) const;

      virtual DgDVec2D invQuantify (const DgIVec2D& add) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgIDGGS43H.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgIDGGS43H.cpp: DgIDGGS43H class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>

#include "DgContCartRF.h"
#include "DgDiscRF.h"
#include "DgHexC1Grid2D.h"
#include "DgHexC2Grid2D.h"
#include "DgIDGGS43H.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgIDGGS43H::DgIDGGS43H (const DgIDGGS43H& rf) 
  : DgIDGGS (rf)
{
   report("DgIDGGS43H::operator=() not implemented yet", DgBase::Fatal);

} // DgIDGGS43H::DgIDGGS43H

////////////////////////////////////////////////////////////////////////////////
DgIDGGS43H::~DgIDGGS43H (void)
{
   for (unsigned int i = 0; i < grids().size(); i++) 
    delete (*grids_)[i]; 

   delete grids_;

} // DgIDGGS43H::~DgIDGGS43H

////////////////////////////////////////////////////////////////////////////////
DgIDGGS43H&
DgIDGGS43H::operator= (const DgIDGGS43H& rf)
{
   report("DgIDGGS43H::operator=() not implemented", DgBase::Fatal);

   return *this;

} // DgIDGGS43H& DgIDGGS43H::operator=

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS43H::setAddParents (const DgResAdd<DgQ2DICoord>& add, 
                             DgLocVector& vec) const
{
   report("DgIDGGS43H::setAddParents()  not implemented yet", DgBase::Fatal);

} // void DgIDGGS43H::setAddParents

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS43H::setAddInteriorChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   report("DgIDGGS43H::setAddInteriorChildren() not implemented yet", 
          DgBase::Fatal);

} // void DgIDGGS43H::setAddInteriorChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS43H::setAddBoundaryChildren (const DgResAdd<DgQ2DICoord>& add, 
                                        DgLocVector& vec) const
{
   report("DgIDGGS43H::setAddBoundaryChildren() not implemented yet", 
          DgBase::Fatal);

} // void DgIDGGS43H::setAddBoundaryChildren

////////////////////////////////////////////////////////////////////////////////
void 
DgIDGGS43H::setAddAllChildren (const DgResAdd<DgQ2DICoord>& add, 
                                   DgLocVector& vec) const
{
   report("DgIDGGS43H::setAddAllChildren() not implemented yet", DgBase::Fatal);

} // void DgIDGGS43H::setAddAllChildren

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgInLocTextFile.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgInLocTextFile.cpp: DgInLocTextFile class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include "DgInLocTextFile.h"

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
DgInLocTextFile::DgInLocTextFile (const DgRFBase& rfIn, 
              const string* fileNameIn, bool isPointFileIn,
              DgReportLevel failLevel)
         : DgInLocFile (rfIn, fileNameIn, isPointFileIn, failLevel)
{
   if (fileNameIn)
      if (!open(NULL, DgBase::Silent))
         report("DgInLocTextFile::DgInLocTextFile() unable to open file " +
                fileName_, failLevel);

} // DgInLocTextFile::DgInLocTextFile

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool 
DgInLocTextFile::open (const string *fileNameIn, DgReportLevel failLevel)
//
// Open fileName as an input file. Report with a report level of failLevel
// if the open is unsuccessful.
//
// Returns true if successful and false if unsuccessful.
//
{
   // make sure we are not already open

   if ((rdbuf())->is_open()) close();
   
   if (fileNameIn)
      fileName_ = *fileNameIn;

   ifstream::open(fileName_.c_str(), ios::in);
   if (good())
   {
      debug("DgInLocTextFile::open() opened file " + fileName_);
      return true;
   }
   else
   {
      report("DgInLocTextFile::open() unable to open file " + fileName_, 
             failLevel);
      return false;
   }
   
} // DgInLocTextFile::open

////////////////////////////////////////////////////////////////////////////////


<|start_filename|>src/DgTriGrid2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgTriGrid2D.h: DgTriGrid2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGTRIGRID2D_H 
#define DGTRIGRID2D_H

#include <cmath>
#include <cstdint>

#include "DgDiscRF2D.h"
#include "DgDVec2D.h"
#include "DgIVec2D.h"
#include "DgConstants.h"

class DgPolygon;

////////////////////////////////////////////////////////////////////////////////
class DgTriGrid2D : public DgDiscRF2D {

   public:

      DgTriGrid2D (DgRFNetwork& networkIn, 
                   const DgRF<DgDVec2D, long double>& ccFrameIn,
                   const string& nameIn = "TriC12D")
         : DgDiscRF2D (networkIn, ccFrameIn, nameIn, M_SQRT3, 1.0L,
                       M_SQRT3_2, 3.0L) 
           { }

      DgTriGrid2D (const DgTriGrid2D& grd) : DgDiscRF2D (grd) {}

      DgTriGrid2D& operator= (const DgTriGrid2D& grd)
           { DgDiscRF2D::operator=(grd); return *this; }

      virtual std::int64_t dist (const DgIVec2D& add1, const DgIVec2D& add2) const;

      static bool isUp (const DgIVec2D& add) { return !(add.j() % 2); }

   protected:

      static const long double sin60_;

      virtual void setAddVertices (const DgIVec2D& add, DgPolygon& vec) const;
      virtual void setAddNeighbors 
                                  (const DgIVec2D& add, DgLocVector& vec) const;

      virtual DgIVec2D quantify (const DgDVec2D& point) const;

      virtual DgDVec2D invQuantify (const DgIVec2D& add) const;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgBoundedHexC2RF2D.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgBoundedHexC2RF2D.h: DgBoundedHexC2RF2D class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGBOUNDEDHEXC2RF2D_H
#define DGBOUNDEDHEXC2RF2D_H

#include <cstdint>

#include "DgBoundedRF2D.h"
#include "DgIVec2D.h"

class DgLocation;

////////////////////////////////////////////////////////////////////////////////
class DgBoundedHexC2RF2D : public DgBoundedRF2D {

   public:

      DgBoundedHexC2RF2D (const DgDiscRF<DgIVec2D, DgDVec2D, long double>& rf, 
                const DgIVec2D& lowerLeft, const DgIVec2D& upperRight);
                    
      virtual DgIVec2D& incrementAddress (DgIVec2D& add) const;
      virtual DgIVec2D& decrementAddress (DgIVec2D& add) const;

      virtual bool validAddress (const DgIVec2D& add) const
          { return add.i() >= lowerLeft().i() && add.i() <= upperRight().i() &&
                   add.j() >= lowerLeft().j() && add.j() <= upperRight().j() &&
                   !((add.i() + add.j()) % 3); }

      virtual std::uint64_t seqNumAddress (const DgIVec2D& add) const;

      virtual DgIVec2D addFromSeqNum (std::uint64_t sNum) const;
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgAddress.h<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgAddress.h: DgAddress class definitions
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#ifndef DGADDRESS_H
#define DGADDRESS_H

#include "DgAddressBase.h"

class DgDistanceBase;

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template <class A> class DgAddress : public DgAddressBase {

   public:

      DgAddress (void) {}
      DgAddress (const DgAddress<A>& add) : address_ (add.address()) {}
      DgAddress (const A& address) : address_ (address) {}

      void setAddress (const A& address) { address_ = address; }

      A& address (void) { return address_; }

      const A& address (void) const { return address_; }

      DgAddress<A>& operator= (const DgAddress<A>& add) 
                                    { address_ = add.address(); return *this; }

   protected:

      virtual ostream& writeTo (ostream& stream) const
                                    { return stream << address_; }

   private:

      A address_;

};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#endif


<|start_filename|>src/DgOutLocFile.cpp<|end_filename|>
////////////////////////////////////////////////////////////////////////////////
//
// DgOutLocFile.cpp: DgOutLocFile class implementation
//
// Version 6.1 - <NAME>, 5/23/13
//
////////////////////////////////////////////////////////////////////////////////

#include <list>
#include <sstream>

#include "DgOutLocFile.h"
#include "DgLocList.h"
#include "DgCell.h"
#include "DgPolygon.h"
#include "DgLocation.h"
#include "DgOutAIGenFile.h"
#include "DgOutKMLfile.h"
#include "DgOutGeoJSONFile.h"
#include "DgOutShapefile.h"
#include "DgOutPtsText.h"
#include "DgGeoSphRF.h"

const string DgOutLocFile::defaultKMLColor = "ffffffff";
const int    DgOutLocFile::defaultKMLWidth = 4;
const string DgOutLocFile::defaultKMLName = "";
const string DgOutLocFile::defaultKMLDescription = "Generated by DGGRID " DGGRID_VERSION;

////////////////////////////////////////////////////////////////////////////////
DgOutLocFile::~DgOutLocFile (void) 
{ 
   // empty destructor
}

////////////////////////////////////////////////////////////////////////////////
DgOutLocFile* 
DgOutLocFile::makeOutLocFile (const string& type, const string& fileName, 
                    const DgRFBase& rf, bool isPointFile, int precision,
                    int shapefileIdLen, const string& kmlColor, int kmlWidth,
                    const string& kmlName, const string& kmlDesc,
                    DgReportLevel failLevelIn)
{
   DgOutLocFile* file = NULL;
   if (!type.compare("AIGEN"))
      file = new DgOutAIGenFile(rf, fileName, precision, isPointFile, 
                                 failLevelIn);
   else if (!type.compare("TEXT"))
      file = new DgOutPtsText(rf, fileName, precision, failLevelIn);
   else // must be KML, GEOJSON or SHAPEFILE
   {
      const DgGeoSphDegRF* geoRF = dynamic_cast<const DgGeoSphDegRF*>(&rf);
      if (geoRF == NULL)
         ::report("DgOutLocFile::makeOutLoc(): invalid RF type", failLevelIn);

      if (!type.compare("KML"))
         file = new DgOutKMLfile(*geoRF, fileName, precision, isPointFile, 
                                 kmlColor, kmlWidth, kmlName, kmlDesc, failLevelIn);
      else if (!type.compare("GEOJSON"))
         file = new DgOutGeoJSONFile(*geoRF, fileName, precision, isPointFile,
                                     failLevelIn);
      else if (!type.compare("SHAPEFILE"))
         file = new DgOutShapefile(*geoRF, fileName, precision, isPointFile, 
                                    shapefileIdLen, failLevelIn);
      else if (type.compare("NONE"))
         ::report("DgOutLocFile::makeOutLoc(): invalid file type " + type, 
                                 failLevelIn);
   }

   return file;

} // DgOutLocFile::makeOutLoc

////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutLocFile::insert (DgLocList& dlist)
//
// Output the drawlist dlist.
//
////////////////////////////////////////////////////////////////////////////////
{
   list<DgLocBase*>::iterator it;
   for (it = dlist.begin(); it != dlist.end(); it++)
   {
      if (DgLocList* d = dynamic_cast<DgLocList*>(*it))
      {
         this->insert(*d);
      }
      else if (DgPolygon* d = dynamic_cast<DgPolygon*>(*it))
      {
         this->insert(*d);
      }
      else if (DgCell* d = dynamic_cast<DgCell*>(*it))
      {
         this->insert(*d);
      }
      else if (DgLocation* d = dynamic_cast<DgLocation*>(*it))
      {
         this->insert(*d);
      }
      else if (DgLocVector* d = dynamic_cast<DgLocVector*>(*it))
      {
         this->insert(*d);
      }
      else
      {
         report("DgOutLocFile::insert() invalid location not inserted", Warning);
      }
   }

   //this->flush();

   return *this;

} // DgOutLocFile& DgOutLocFile::insert

////////////////////////////////////////////////////////////////////////////////
DgOutLocFile&
DgOutLocFile::insert (DgCell& cell)
//
// Put the cell.
//
////////////////////////////////////////////////////////////////////////////////
{
   rf().convert(&cell);

   if (!isPointFile() && cell.hasRegion())
      this->insert(cell.region(), &(cell.label()), &(cell.node()));
   else
      this->insert(cell.node(), &(cell.label()));

   return *this;

} // DgOutLocFile& DgOutLocFile::insert

////////////////////////////////////////////////////////////////////////////////
