Index: src/boundary.cpp
===================================================================
--- src/boundary.cpp	(revision ee1b1672b32e3729acbddd8118c30803b9bca638)
+++ src/boundary.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
@@ -1804,4 +1804,5 @@
  */
 int Tesselation::CheckPresenceOfTriangle(ofstream *out, atom *Candidates[3]) {
+// TODO: use findTriangles here and return result.size();
   LineMap::iterator FindLine;
   PointMap::iterator FindPoint;
@@ -2240,5 +2241,5 @@
   int N[NDIM], Nlower[NDIM], Nupper[NDIM];
 
-  if (LC->SetIndexToAtom(a)) {  // get cell for the starting atom
+  if (LC->SetIndexToAtom(*a)) {  // get cell for the starting atom
     for(int i=0;i<NDIM;i++) // store indices of this cell
       N[i] = LC->n[i];
@@ -2746,5 +2747,6 @@
  */
 bool sortCandidates(CandidateForTesselation* candidate1, CandidateForTesselation* candidate2) {
-	Vector BaseLineVector, OrthogonalVector, helper;
+  // TODO: use get angle and remove duplicate code
+  Vector BaseLineVector, OrthogonalVector, helper;
 	if (candidate1->BaseLine != candidate2->BaseLine) {  // sanity check
 	  cout << Verbose(0) << "ERROR: sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
@@ -2784,4 +2786,302 @@
 	// return comparison
 	return phi < psi;
+}
+
+/**
+ * Checks whether the provided atom is within the tesselation structure.
+ *
+ * @param atom of which to check the position
+ * @param tesselation structure
+ *
+ * @return true if the atom is inside the tesselation structure, false otherwise
+ */
+bool IsInnerAtom(atom *Atom, class Tesselation *Tess, LinkedCell* LC) {
+  if (Tess->LinesOnBoundary.begin() == Tess->LinesOnBoundary.end()) {
+    cout << Verbose(0) << "Error: There is no tesselation structure to compare the atom with, "
+        << "please create one first.";
+    exit(1);
+  }
+
+  class atom *trianglePoints[3];
+  trianglePoints[0] = findClosestAtom(Atom, LC);
+  // check whether closest atom is "too close" :), then it's inside
+  if (trianglePoints[0]->x.DistanceSquared(&Atom->x) < MYEPSILON)
+    return true;
+  list<atom*> *connectedClosestAtoms = Tess->getClosestConnectedAtoms(trianglePoints[0], Atom);
+  trianglePoints[1] = connectedClosestAtoms->front();
+  trianglePoints[2] = connectedClosestAtoms->back();
+  for (int i=0;i<3;i++) {
+    if (trianglePoints[i] == NULL) {
+      cout << Verbose(1) << "IsInnerAtom encounters serious error, point " << i << " not found." << endl;
+    }
+
+    cout << Verbose(1) << "List of possible atoms:" << endl;
+    cout << *trianglePoints[i] << endl;
+
+//    for(list<atom*>::iterator runner = connectedClosestAtoms->begin(); runner != connectedClosestAtoms->end(); runner++)
+//      cout << Verbose(2) << *(*runner) << endl;
+  }
+  delete(connectedClosestAtoms);
+
+  list<BoundaryTriangleSet*> *triangles = Tess->FindTriangles(trianglePoints);
+
+  if (triangles->empty()) {
+    cout << Verbose(0) << "Error: There is no nearest triangle. Please check the tesselation structure.";
+    exit(1);
+  }
+
+  Vector helper;
+  helper.CopyVector(&Atom->x);
+
+  // Only in case of degeneration, there will be two different scalar products.
+  // If at least one scalar product is positive, the point is considered to be outside.
+  bool status = (helper.ScalarProduct(&triangles->front()->NormalVector) < 0)
+      && (helper.ScalarProduct(&triangles->back()->NormalVector) < 0);
+  delete(triangles);
+  return status;
+}
+
+/**
+ * Finds the atom which is closest to the provided one.
+ *
+ * @param atom to which to find the closest other atom
+ * @param linked cell structure
+ *
+ * @return atom which is closest to the provided one
+ */
+atom* findClosestAtom(const atom* Atom, LinkedCell* LC) {
+  LinkedAtoms *List = NULL;
+  atom* closestAtom = NULL;
+  double distance = 1e16;
+  Vector helper;
+  int N[NDIM], Nlower[NDIM], Nupper[NDIM];
+
+  LC->SetIndexToVector(&Atom->x); // ignore status as we calculate bounds below sensibly
+  for(int i=0;i<NDIM;i++) // store indices of this cell
+    N[i] = LC->n[i];
+  //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
+
+  LC->GetNeighbourBounds(Nlower, Nupper);
+  //cout << endl;
+  for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
+    for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
+      for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
+        List = LC->GetCurrentCell();
+        //cout << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
+        if (List != NULL) {
+          for (LinkedAtoms::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+            helper.CopyVector(&Atom->x);
+            helper.SubtractVector(&(*Runner)->x);
+            double currentNorm = helper. Norm();
+            if (currentNorm < distance) {
+              distance = currentNorm;
+              closestAtom = (*Runner);
+            }
+          }
+        } else {
+          cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << ","
+            << LC->n[2] << " is invalid!" << endl;
+        }
+      }
+
+  return closestAtom;
+}
+
+/**
+ * Gets all atoms connected to the provided atom by triangulation lines.
+ *
+ * @param atom of which get all connected atoms
+ * @param atom to be checked whether it is an inner atom
+ *
+ * @return list of the two atoms linked to the provided one and closest to the atom to be checked,
+ */
+list<atom*> * Tesselation::getClosestConnectedAtoms(atom* Atom, atom* AtomToCheck) {
+  list<atom*> connectedAtoms;
+  map<double, atom*> anglesOfAtoms;
+  map<double, atom*>::iterator runner;
+  LineMap::iterator findLines = LinesOnBoundary.begin();
+  list<atom*>::iterator listRunner;
+  Vector center, planeNorm, currentPoint, OrthogonalVector, helper;
+  atom* current;
+  bool takeAtom = false;
+
+  planeNorm.CopyVector(&Atom->x);
+  planeNorm.SubtractVector(&AtomToCheck->x);
+  planeNorm.Normalize();
+
+  while (findLines != LinesOnBoundary.end()) {
+    takeAtom = false;
+
+    if (findLines->second->endpoints[0]->Nr == Atom->nr) {
+      takeAtom = true;
+      current = findLines->second->endpoints[1]->node;
+    } else if (findLines->second->endpoints[1]->Nr == Atom->nr) {
+      takeAtom = true;
+      current = findLines->second->endpoints[0]->node;
+    }
+
+    if (takeAtom) {
+      connectedAtoms.push_back(current);
+      currentPoint.CopyVector(&current->x);
+      currentPoint.ProjectOntoPlane(&planeNorm);
+      center.AddVector(&currentPoint);
+    }
+
+    findLines++;
+  }
+
+  cout << "Summed vectors " << center << "; number of atoms " << connectedAtoms.size()
+    << "; scale factor " << 1.0/connectedAtoms.size();
+
+  center.Scale(1.0/connectedAtoms.size());
+  listRunner = connectedAtoms.begin();
+
+  cout << " calculated center " << center <<  endl;
+
+  // construct one orthogonal vector
+  helper.CopyVector(&AtomToCheck->x);
+  helper.ProjectOntoPlane(&planeNorm);
+  OrthogonalVector.MakeNormalVector(&center, &helper, &(*listRunner)->x);
+  while (listRunner != connectedAtoms.end()) {
+    double angle = getAngle((*listRunner)->x, AtomToCheck->x, center, OrthogonalVector);
+    cout << "Calculated angle " << angle << " for atom " << **listRunner << endl;
+    anglesOfAtoms.insert(pair<double, atom*>(angle, (*listRunner)));
+    listRunner++;
+  }
+
+  list<atom*> *result = new list<atom*>;
+  runner = anglesOfAtoms.begin();
+  cout << "First value is " << *runner->second << endl;
+  result->push_back(runner->second);
+  runner = anglesOfAtoms.end();
+  runner--;
+  cout << "Second value is " << *runner->second << endl;
+  result->push_back(runner->second);
+
+  cout << "List of closest atoms has " << result->size() << " elements, which are "
+    << *(result->front()) << " and " << *(result->back()) << endl;
+
+  return result;
+}
+
+/**
+ * Finds triangles belonging to the three provided atoms.
+ *
+ * @param atom list, is expected to contain three atoms
+ *
+ * @return triangles which belong to the provided atoms, will be empty if there are none,
+ *         will usually be one, in case of degeneration, there will be two
+ */
+list<BoundaryTriangleSet*> *Tesselation::FindTriangles(atom* Points[3]) {
+  list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
+  LineMap::iterator FindLine;
+  PointMap::iterator FindPoint;
+  TriangleMap::iterator FindTriangle;
+  class BoundaryPointSet *TrianglePoints[3];
+
+  for (int i = 0; i < 3; i++) {
+    FindPoint = PointsOnBoundary.find(Points[i]->nr);
+    if (FindPoint != PointsOnBoundary.end()) {
+      TrianglePoints[i] = FindPoint->second;
+    } else {
+      TrianglePoints[i] = NULL;
+    }
+  }
+
+  // checks lines between the points in the Points for their adjacent triangles
+  for (int i = 0; i < 3; i++) {
+    if (TrianglePoints[i] != NULL) {
+      for (int j = i; j < 3; j++) {
+        if (TrianglePoints[j] != NULL) {
+          FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr);
+          if (FindLine != TrianglePoints[i]->lines.end()) {
+            for (; FindLine->first == TrianglePoints[j]->node->nr; FindLine++) {
+              FindTriangle = FindLine->second->triangles.begin();
+              for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
+                if ((
+                  (FindTriangle->second->endpoints[0] == TrianglePoints[0])
+                    || (FindTriangle->second->endpoints[0] == TrianglePoints[1])
+                    || (FindTriangle->second->endpoints[0] == TrianglePoints[2])
+                  ) && (
+                    (FindTriangle->second->endpoints[1] == TrianglePoints[0])
+                    || (FindTriangle->second->endpoints[1] == TrianglePoints[1])
+                    || (FindTriangle->second->endpoints[1] == TrianglePoints[2])
+                  ) && (
+                    (FindTriangle->second->endpoints[2] == TrianglePoints[0])
+                    || (FindTriangle->second->endpoints[2] == TrianglePoints[1])
+                    || (FindTriangle->second->endpoints[2] == TrianglePoints[2])
+                  )
+                ) {
+                  result->push_back(FindTriangle->second);
+                }
+              }
+            }
+            // Is it sufficient to consider one of the triangle lines for this.
+            return result;
+
+          }
+        }
+      }
+    }
+  }
+
+  return result;
+}
+
+/**
+ * Gets the angle between a point and a reference relative to the provided center.
+ *
+ * @param point to calculate the angle for
+ * @param reference to which to calculate the angle
+ * @param center for which to calculate the angle between the vectors
+ * @param OrthogonalVector helps discern between [0,pi] and [pi,2pi] in acos()
+ *
+ * @return angle between point and reference
+ */
+double getAngle(Vector point, Vector reference, Vector center, Vector OrthogonalVector) {
+  Vector ReferenceVector, helper;
+  cout << Verbose(2) << reference << " is our reference " << endl;
+  cout << Verbose(2) << center << " is our center " << endl;
+  // create baseline vector
+  ReferenceVector.CopyVector(&reference);
+  ReferenceVector.SubtractVector(&center);
+  if (ReferenceVector.IsNull())
+    return M_PI;
+
+  // calculate both angles and correct with in-plane vector
+  helper.CopyVector(&point);
+  helper.SubtractVector(&center);
+  if (helper.IsNull())
+    return M_PI;
+  double phi = ReferenceVector.Angle(&helper);
+  if (OrthogonalVector.ScalarProduct(&helper) > 0) {
+    phi = 2.*M_PI - phi;
+  }
+
+  cout << Verbose(2) << point << " has angle " << phi << endl;
+
+  return phi;
+}
+
+/**
+ * Checks whether the provided point is within the tesselation structure.
+ *
+ * This is a wrapper function for IsInnerAtom, so it can be used with a simple
+ * vector, too.
+ *
+ * @param point of which to check the position
+ * @param tesselation structure
+ *
+ * @return true if the point is inside the tesselation structure, false otherwise
+ */
+bool IsInnerPoint(Vector Point, class Tesselation *Tess, LinkedCell* LC) {
+  atom *temp_atom = new atom;
+  bool status = false;
+  temp_atom->x.CopyVector(&Point);
+
+  status = IsInnerAtom(temp_atom, Tess, LC);
+  delete(temp_atom);
+
+  return status;
 }
 
@@ -2870,4 +3170,37 @@
     cout << Verbose(2) << "None." << endl;
 
+  // Tests the IsInnerAtom() function.
+  Vector x (0, 0, 0);
+  cout << Verbose(0) << "Point to check: " << x << endl;
+  cout << Verbose(0) << "Check: IsInnerPoint() returns " << IsInnerPoint(x, Tess, LCList)
+    << "for vector " << x << "." << endl;
+  atom* a = Tess->PointsOnBoundary.begin()->second->node;
+  cout << Verbose(0) << "Point to check: " << *a << " (on boundary)." << endl;
+  cout << Verbose(0) << "Check: IsInnerAtom() returns " << IsInnerAtom(a, Tess, LCList)
+    << "for atom " << a << " (on boundary)." << endl;
+  LinkedAtoms *List = NULL;
+  for (int i=0;i<NDIM;i++) { // each axis
+    LCList->n[i] = LCList->N[i]-1; // current axis is topmost cell
+    for (LCList->n[(i+1)%NDIM]=0;LCList->n[(i+1)%NDIM]<LCList->N[(i+1)%NDIM];LCList->n[(i+1)%NDIM]++)
+      for (LCList->n[(i+2)%NDIM]=0;LCList->n[(i+2)%NDIM]<LCList->N[(i+2)%NDIM];LCList->n[(i+2)%NDIM]++) {
+        List = LCList->GetCurrentCell();
+        //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
+        if (List != NULL) {
+          for (LinkedAtoms::iterator Runner = List->begin();Runner != List->end();Runner++) {
+            if (Tess->PointsOnBoundary.find((*Runner)->nr) == Tess->PointsOnBoundary.end()) {
+              a = *Runner;
+              i=3;
+              for (int j=0;j<NDIM;j++)
+                LCList->n[j] = LCList->N[j];
+              break;
+            }
+          }
+        }
+      }
+  }
+  cout << Verbose(0) << "Check: IsInnerAtom() returns " << IsInnerAtom(a, Tess, LCList)
+    << "for atom " << a << " (inside)." << endl;
+
+
   if (freeTess)
     delete(Tess);
Index: src/boundary.hpp
===================================================================
--- src/boundary.hpp	(revision ee1b1672b32e3729acbddd8118c30803b9bca638)
+++ src/boundary.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
@@ -104,4 +104,6 @@
     int CheckPresenceOfTriangle(ofstream *out, atom *Candidates[3]);
     void Find_next_suitable_point_via_Angle_of_Sphere(atom* a, atom* b, atom* c, atom* Candidate, atom* Parent, int RecursionLevel, Vector *Chord, Vector *direction1, Vector *OldNormal, Vector ReferencePoint, atom*& Opt_Candidate, double *Storage, const double RADIUS, molecule* mol);
+    list<atom*> *getClosestConnectedAtoms(atom* Atom, atom* AtomToCheck);
+    list<BoundaryTriangleSet*> *FindTriangles(atom* TrianglePoints[3]);
 
     PointMap PointsOnBoundary;
@@ -132,4 +134,8 @@
 bool existsIntersection(Vector point1, Vector point2, Vector point3, Vector point4);
 bool sortCandidates(CandidateForTesselation* candidate1, CandidateForTesselation* candidate2);
+bool IsInnerPoint(Vector Point, class Tesselation *Tess, LinkedCell* LC);
+bool IsInnerAtom(atom *Atom, class Tesselation *Tess, LinkedCell* LC);
+atom* findClosestAtom(const atom* Atom, LinkedCell* LC);
+double getAngle(Vector point, Vector reference, Vector center, Vector OrthogonalVector);
 
 #endif /*BOUNDARY_HPP_*/
