Index: trunk/BNC/src/bncephuser.cpp
===================================================================
--- trunk/BNC/src/bncephuser.cpp	(revision 11185)
+++ trunk/BNC/src/bncephuser.cpp	(revision 11215)
@@ -44,4 +44,5 @@
 #include "bnccore.h"
 #include "bncsettings.h"
+#include "RTCM3/ephEncoder.h"
 
 using namespace std;
@@ -49,5 +50,5 @@
 // Constructor
 ////////////////////////////////////////////////////////////////////////////
-bncEphUser::bncEphUser(bool connectSlots, unsigned maxQueueSize) : _maxQueueSize(maxQueueSize) {
+bncEphUser::bncEphUser(bool connectSlots, unsigned maxQueueSize) : _maxQueueSize(maxQueueSize), _voting(false) {
   if (connectSlots) {
     connect(BNC_CORE, SIGNAL(newGPSEph(t_ephGPS)),
@@ -90,4 +91,5 @@
     }
   }
+  qDeleteAll(_votes);
 }
 
@@ -142,28 +144,11 @@
   }
 
-  const t_ephGPS*     ephGPS     = dynamic_cast<const t_ephGPS*>(eph);
-  const t_ephGlo*     ephGlo     = dynamic_cast<const t_ephGlo*>(eph);
-  const t_ephGal*     ephGal     = dynamic_cast<const t_ephGal*>(eph);
-  const t_ephSBAS*    ephSBAS    = dynamic_cast<const t_ephSBAS*>(eph);
-  const t_ephBDS*     ephBDS     = dynamic_cast<const t_ephBDS*>(eph);
-
-  t_eph* newEph = 0;
-
-  if      (ephGPS) {
-    newEph = new t_ephGPS(*ephGPS);
-  }
-  else if (ephGlo) {
-    newEph = new t_ephGlo(*ephGlo);
-  }
-  else if (ephGal) {
-    newEph = new t_ephGal(*ephGal);
-  }
-  else if (ephSBAS) {
-    newEph = new t_ephSBAS(*ephSBAS);
-  }
-  else if (ephBDS) {
-    newEph = new t_ephBDS(*ephBDS);
-  }
-  else {
+  // satellite outside the range supported by BNC (e.g. G39)
+  if (eph->prn().toInt() == 0) {
+    return failure;
+  }
+
+  t_eph* newEph = clone(eph);
+  if (newEph == 0) {
     return failure;
   }
@@ -177,4 +162,7 @@
       if (qq[ii]->sameDataSet(eph)) {
         delete newEph;
+        if (_voting && realTime) {
+          vote(prn, ii, eph);
+        }
         return failure;
       }
@@ -203,5 +191,13 @@
     newEph->setCheckState(eph->checkState());
     qq.push_back(newEph);
+    if (_voting && realTime) {
+      t_votes* votes = new t_votes;
+      votes->_content.append(votingContent(newEph));
+      votes->_eph.append(clone(newEph));
+      votes->_station[newEph->receptStaID()] = 0;
+      _votes[newEph] = votes;
+    }
     if (qq.size() > _maxQueueSize) {
+      delete _votes.take(qq.front());
       delete qq.front();
       qq.pop_front();
@@ -214,4 +210,191 @@
     return failure;
   }
+}
+
+// Copy of an ephemeris of any system
+////////////////////////////////////////////////////////////////////////////
+t_eph* bncEphUser::clone(const t_eph* eph) {
+  if (const t_ephGPS*  e = dynamic_cast<const t_ephGPS*>(eph))  return new t_ephGPS(*e);
+  if (const t_ephGlo*  e = dynamic_cast<const t_ephGlo*>(eph))  return new t_ephGlo(*e);
+  if (const t_ephGal*  e = dynamic_cast<const t_ephGal*>(eph))  return new t_ephGal(*e);
+  if (const t_ephSBAS* e = dynamic_cast<const t_ephSBAS*>(eph)) return new t_ephSBAS(*e);
+  if (const t_ephBDS*  e = dynamic_cast<const t_ephBDS*>(eph))  return new t_ephBDS(*e);
+  return 0;
+}
+
+// Content compared in the vote: the uploaded RTCM3 message without CRC and,
+// for GLONASS, without the fields differing legitimately between receivers
+////////////////////////////////////////////////////////////////////////////
+QByteArray bncEphUser::votingContent(const t_eph* eph) {
+  unsigned char buffer[80];
+  int size = 0;
+  if      (const t_ephGPS*  e = dynamic_cast<const t_ephGPS*>(eph))  size = t_ephEncoder::RTCM3(*e, buffer);
+  else if (const t_ephGlo*  e = dynamic_cast<const t_ephGlo*>(eph))  size = t_ephEncoder::RTCM3(*e, buffer);
+  else if (const t_ephGal*  e = dynamic_cast<const t_ephGal*>(eph))  size = t_ephEncoder::RTCM3(*e, buffer);
+  else if (const t_ephSBAS* e = dynamic_cast<const t_ephSBAS*>(eph)) size = t_ephEncoder::RTCM3(*e, buffer);
+  else if (const t_ephBDS*  e = dynamic_cast<const t_ephBDS*>(eph))  size = t_ephEncoder::RTCM3(*e, buffer);
+  if (size <= 6) {
+    return QByteArray();
+  }
+  if (eph->system() == t_eph::GLONASS) {
+    // message bits (after the 3 header bytes) of tk and of the system time
+    // offsets tau_c and tau_GPS: receivers take the latter from the string 5
+    // of any satellite, they differ within the same data set
+    const int field[3][2] = {{27, 12}, {293, 32}, {330, 22}};
+    for (int ii = 0; ii < 3; ii++) {
+      for (int bit = 24 + field[ii][0]; bit < 24 + field[ii][0] + field[ii][1]; bit++) {
+        buffer[bit / 8] &= ~(0x80 >> (bit % 8));
+      }
+    }
+  }
+  return QByteArray((const char*) buffer, size - 3);
+}
+
+// Names of the fields in which two vote contents (RTCM3 messages) differ
+////////////////////////////////////////////////////////////////////////////
+namespace {
+struct t_field {const char* name; int nbits;};
+const t_field fields1019[] = {{"type",12},{"sv",6},{"week",10},{"URA",4},{"L2code",2},{"IDOT",14},{"IODE",8},
+  {"toc",16},{"af2",8},{"af1",16},{"af0",22},{"IODC",10},{"Crs",16},{"dn",16},{"M0",32},{"Cuc",16},{"e",32},
+  {"Cus",16},{"sqrtA",32},{"toe",16},{"Cic",16},{"Omega0",32},{"Cis",16},{"i0",32},{"Crc",16},{"omega",32},
+  {"OmegaDot",24},{"TGD",8},{"health",6},{"L2P",1},{"fit",1},{0,0}};
+const t_field fields1020[] = {{"type",12},{"sv",6},{"fc",5},{"Cn",1},{"A",1},{"P1",2},{"tk",12},{"Bn",1},{"P2",1},
+  {"tb",7},{"xv",24},{"x",27},{"xa",5},{"yv",24},{"y",27},{"ya",5},{"zv",24},{"z",27},{"za",5},{"P3",1},
+  {"gamma",11},{"P",2},{"ln3",1},{"tau",22},{"dtau",5},{"En",5},{"P4",1},{"FT",4},{"NT",11},{"M",2},{"add",1},
+  {"NA",11},{"tauc",32},{"N4",5},{"tauGPS",22},{"ln5",1},{0,0}};
+const t_field fields1042[] = {{"type",12},{"sv",6},{"week",13},{"URAI",4},{"IDOT",14},{"AODE",5},{"toc",17},
+  {"a2",11},{"a1",22},{"a0",24},{"AODC",5},{"Crs",18},{"dn",16},{"M0",32},{"Cuc",18},{"e",32},{"Cus",18},
+  {"sqrtA",32},{"toe",17},{"Cic",18},{"Omega0",32},{"Cis",18},{"i0",32},{"Crc",18},{"omega",32},{"OmegaDot",24},
+  {"TGD1",10},{"TGD2",10},{"SatH1",1},{0,0}};
+const t_field fields1044[] = {{"type",12},{"sv",4},{"toc",16},{"af2",8},{"af1",16},{"af0",22},{"IODE",8},
+  {"Crs",16},{"dn",16},{"M0",32},{"Cuc",16},{"e",32},{"Cus",16},{"sqrtA",32},{"toe",16},{"Cic",16},{"Omega0",32},
+  {"Cis",16},{"i0",32},{"Crc",16},{"omega",32},{"OmegaDot",24},{"IDOT",14},{"L2code",2},{"week",10},{"URA",4},
+  {"health",6},{"TGD",8},{"IODC",10},{"fit",1},{0,0}};
+#define GAL_COMMON {"type",12},{"sv",6},{"week",12},{"IODnav",10},{"SISA",8},{"IDOT",14},{"toc",14},{"af2",6}, \
+  {"af1",21},{"af0",31},{"Crs",16},{"dn",16},{"M0",32},{"Cuc",16},{"e",32},{"Cus",16},{"sqrtA",32},{"toe",14}, \
+  {"Cic",16},{"Omega0",32},{"Cis",16},{"i0",32},{"Crc",16},{"omega",32},{"OmegaDot",24},{"BGDa",10}
+const t_field fields1045[] = {GAL_COMMON,{"E5aHS",2},{"E5aDVS",1},{0,0}};
+const t_field fields1046[] = {GAL_COMMON,{"BGDb",10},{"E5bHS",2},{"E5bDVS",1},{"E1BHS",2},{"E1BDVS",1},{0,0}};
+
+unsigned long long getBits(const QByteArray& buf, int pos, int nbits) {
+  unsigned long long val = 0;
+  for (int bit = pos; bit < pos + nbits; bit++) {
+    val = (val << 1) | ((static_cast<unsigned char>(buf[bit / 8]) >> (7 - bit % 8)) & 1);
+  }
+  return val;
+}
+}
+
+QString bncEphUser::differingFields(const QByteArray& c1, const QByteArray& c2) {
+  if (c1.size() != c2.size() || c1.size() < 5) {
+    return "content";
+  }
+  const t_field* fields = 0;
+  switch (getBits(c1, 24, 12)) {
+    case 1019: fields = fields1019; break;
+    case 1020: fields = fields1020; break;
+    case 1042: fields = fields1042; break;
+    case 1044: fields = fields1044; break;
+    case 1045: fields = fields1045; break;
+    case 1046: fields = fields1046; break;
+  }
+  if (!fields) {
+    return "content";
+  }
+  QStringList names;
+  int pos = 24;
+  for (int ii = 0; fields[ii].name; ii++) {
+    if (pos + fields[ii].nbits > 8 * c1.size()) {
+      break;
+    }
+    if (getBits(c1, pos, fields[ii].nbits) != getBits(c2, pos, fields[ii].nbits)) {
+      names << fields[ii].name;
+    }
+    pos += fields[ii].nbits;
+  }
+  return names.isEmpty() ? QString("content") : names.join(" ");
+}
+
+// Further copy of the buffered data set qq[index] received from a stream
+////////////////////////////////////////////////////////////////////////////
+void bncEphUser::vote(const QString& prn, unsigned index, const t_eph* eph) {
+  deque<t_eph*>& qq = _eph[prn];
+  t_votes* votes = _votes.value(qq[index], 0);
+  if (!votes) {
+    return;
+  }
+  QByteArray content = votingContent(eph);
+  int iVar = votes->_content.indexOf(content);
+  if (iVar < 0) {
+    iVar = votes->_content.size();
+    votes->_content.append(content);
+    votes->_eph.append(clone(eph));
+  }
+  votes->_station[eph->receptStaID()] = iVar;
+
+  QVector<int> count(votes->_content.size(), 0);
+  QMapIterator<QString, int> it(votes->_station);
+  while (it.hasNext()) {
+    it.next();
+    count[it.value()]++;
+  }
+  int iBest = votes->_current;
+  for (int ii = 0; ii < count.size(); ii++) {
+    if (count[ii] > count[iBest]) {
+      iBest = ii;
+    }
+  }
+  if (iBest == votes->_current) {
+    return;
+  }
+
+  t_eph* oldEph = qq[index];
+  t_eph* newEph = clone(votes->_eph[iBest]);
+  if (!radialDistanceOk(newEph)) {
+    delete newEph;
+    return;
+  }
+  if      (newEph->isUnhealthy()) {
+    newEph->setCheckState(t_eph::unhealthy);
+  }
+  else if (oldEph->checkState() == t_eph::unhealthy) {
+    newEph->setCheckState(t_eph::ok);
+  }
+  else {
+    newEph->setCheckState(oldEph->checkState());
+  }
+
+  QStringList stations;
+  for (int ii = 0; ii < count.size(); ii++) {
+    QStringList hlp;
+    QMapIterator<QString, int> is(votes->_station);
+    while (is.hasNext()) {
+      is.next();
+      if (is.value() == ii) {
+        hlp << is.key();
+      }
+    }
+    if (!hlp.isEmpty()) {
+      stations << (ii == iBest ? "+ " : "- ") + hlp.join(" ");
+    }
+  }
+  BNC_CORE->message(QString("ephemeris vote %1 %2 %3: copy of %4 replaced by that of %5 (%6 of %7 streams; %8; differing: %9)")
+                    .arg(prn.left(3))
+                    .arg(oldEph->TOC().datestr().c_str())
+                    .arg(oldEph->TOC().timestr(0).c_str())
+                    .arg(oldEph->receptStaID())
+                    .arg(newEph->receptStaID())
+                    .arg(count[iBest])
+                    .arg(votes->_station.size())
+                    .arg(stations.join(", "))
+                    .arg(differingFields(votes->_content[votes->_current], votes->_content[iBest])).toLatin1(),
+                    false, "bce", t_logRecord::info);
+
+  _votes.remove(oldEph);
+  delete oldEph;
+  qq[index] = newEph;
+  votes->_current = iBest;
+  _votes[newEph] = votes;
+  ephBufferChanged();
 }
 
