Index: trunk/BNC/src/ssrQc.cpp
===================================================================
--- trunk/BNC/src/ssrQc.cpp	(revision 11214)
+++ trunk/BNC/src/ssrQc.cpp	(revision 11218)
@@ -59,4 +59,8 @@
   const double EPH_IOD_REUSE  = 21600.0; // [s] an outdated data set this far from the epoch: IOD reused
   const unsigned EPH_KEPT     = 30;    // data sets kept per satellite
+  const double OUTAGE_FRACTION = 0.75; // common outage: streams with a gap at the same time
+  const unsigned OUTAGE_MIN_STA = 3;   //   (at least this many)
+  const double OUTAGE_LAT_AFTER = 120.0; // [s] latencies left out after a common outage
+  const double MAX_EPOCH_OFFSET = 900.0; // [s] corrections with epochs further from their reception not used
   const double CMP_SAMPL      = 30.0;  // [s] sampling of the stream comparison
   const double CMP_DELAY      = 60.0;  // [s] epochs compared when data this much newer arrived
@@ -370,8 +374,10 @@
     if (stat.last.valid()) {
       stat.intervals.push_back(time - stat.last);
+      stat.intervalEnds.push_back(tKey(time));
     }
     stat.last = time;
     stat.numEpo += 1;
     stat.latencies.push_back(currentTime() - time);
+    stat.latencyEpochs.push_back(tKey(time));
   }
   else if (time < stat.last) {
@@ -450,4 +456,64 @@
 }
 
+// Switch of the orbit corrections to another IOD
+////////////////////////////////////////////////////////////////////////////
+void t_ssrQc::checkIodSwitch(t_satStat& stat, const QString& staID, const QString& prnInt,
+                             unsigned iod, const bncTime& time) {
+  bool     first   = !stat.orbIodSet;
+  unsigned prevIod = stat.orbIod;
+  stat.orbIodSet = true;
+  stat.orbIod    = iod;
+  if (!first && iod == prevIod) {
+    return;
+  }
+  // data set of an IOD (not one with a reused IOD)
+  auto dataSet = [this, &prnInt, &time](unsigned ii) -> t_eph* {
+    t_eph* eph = _ephUser.ephWithIOD(prnInt, ii);
+    return (eph && fabs(time - eph->TOC()) <= EPH_IOD_REUSE) ? eph : 0;
+  };
+  t_eph* eph = dataSet(iod);
+  if (!eph) {
+    return;
+  }
+  if (first || !stat.newestToc.valid()) {
+    stat.newestToc = eph->TOC();
+    return;
+  }
+  t_eph* prev = dataSet(prevIod);
+  char sys = eph->prn().system();
+  QString staSys = QString("%1 %2").arg(staID).arg(sys);
+  if (prev && eph->TOC() < prev->TOC()) {
+    _iodSwitch[staSys].back[QString::fromStdString(eph->prn().toString())] += 1;
+    return;
+  }
+  // first switch to this data set (not again after switching back), not
+  // before all broadcast ephemerides may have been received
+  if (!(stat.newestToc < eph->TOC())) {
+    return;
+  }
+  stat.newestToc = eph->TOC();
+  if (!eph->receptDateTime().isValid() || time - _staStart[staID] < EPH_WARMUP) {
+    return;
+  }
+  bncTime recept(eph->receptDateTime().toString(Qt::ISODate).toStdString());
+  t_iodSwitchStat& sw = _iodSwitch[staSys];
+  sw.afterRecept.push_back(currentTime() - recept);
+  if (sys == 'C') {
+    sw.afterToc.push_back(time - eph->TOC());
+  }
+}
+
+// Epoch time far from the reception time, e.g. a GLONASS epoch erroneously
+// encoded 11758 s ahead (SHA1/GFZ1 22 Nov 2026): not used, as it would move
+// the report interval (no reports for hours) and distort all statistics
+////////////////////////////////////////////////////////////////////////////
+bool t_ssrQc::badEpoch(const string& staID, const bncTime& time) {
+  if (fabs(currentTime() - time) <= MAX_EPOCH_OFFSET) {
+    return false;
+  }
+  _badEpochs[QString::fromStdString(staID)] += 1;
+  return true;
+}
+
 // Orbit corrections
 ////////////////////////////////////////////////////////////////////////////
@@ -455,4 +521,5 @@
   QMutexLocker locker(&_mutex);
   for (const t_orbCorr& corr : orbCorrections) {
+    if (badEpoch(corr._staID, corr._time)) continue;
     if (!_excluded.contains(QString::fromStdString(corr._staID)) || corr._staID == _reference.toStdString()) {
       storeHist(&corr, 0);
@@ -467,4 +534,6 @@
     checkEph(stat, QString::fromStdString(corr._staID) + ' ' + prn,
              QString::fromStdString(corr._prn.toInternalString()), corr._iod, corr._time, corr._staID);
+    checkIodSwitch(stat, QString::fromStdString(corr._staID),
+                   QString::fromStdString(corr._prn.toInternalString()), corr._iod, corr._time);
     double radial = fabs(corr._xr[0]);
     double alongCross = max(fabs(corr._xr[1]), fabs(corr._xr[2]));
@@ -479,4 +548,5 @@
   QMutexLocker locker(&_mutex);
   for (const t_clkCorr& corr : clkCorrections) {
+    if (badEpoch(corr._staID, corr._time)) continue;
     if (!_excluded.contains(QString::fromStdString(corr._staID)) || corr._staID == _reference.toStdString()) {
       storeHist(0, &corr);
@@ -515,4 +585,5 @@
   QMutexLocker locker(&_mutex);
   for (const t_satCodeBias& bias : codeBiases) {
+    if (badEpoch(bias._staID, bias._time)) continue;
     bool sel = selected(bias._staID);
     if (_excluded.contains(QString::fromStdString(bias._staID)) && bias._staID != _reference.toStdString()) continue;
@@ -564,4 +635,5 @@
   QMutexLocker locker(&_mutex);
   for (const t_satPhaseBias& bias : phaseBiases) {
+    if (badEpoch(bias._staID, bias._time)) continue;
     QString staID = QString::fromStdString(bias._staID);
     QString prn   = QString::fromStdString(bias._prn.toString());
@@ -1516,5 +1588,5 @@
 void t_ssrQc::slotNewTec(t_vTec vTec) {
   QMutexLocker locker(&_mutex);
-  if (vTec._layers.empty()) {
+  if (vTec._layers.empty() || badEpoch(vTec._staID, vTec._time)) {
     return;
   }
@@ -1696,4 +1768,23 @@
   }
 
+  // common outages of the input, reported in each stream's report
+  QVector<t_outage> outages = commonOutages(streams);
+  auto inOutage = [&outages](double t0, double t1) {   // window [t0, t1] overlaps an outage
+    for (const t_outage& oo : outages) {
+      if (t0 < oo.end && t1 > oo.start) return true;
+    }
+    return false;
+  };
+  auto afterOutage = [&outages](double tt) {
+    for (const t_outage& oo : outages) {
+      if (tt > oo.start && tt <= oo.end + OUTAGE_LAT_AFTER) return true;
+    }
+    return false;
+  };
+  auto tStr = [](double tt) {
+    bncTime bt(int(tt / 604800.0), tt - 604800.0 * int(tt / 604800.0));
+    return QString::fromStdString(bt.datestr() + ' ' + bt.timestr(0));
+  };
+
   QMapIterator<QString, QSet<char> > itSta(streams);
   while (itSta.hasNext()) {
@@ -1727,11 +1818,19 @@
         double ref = max(double(stat.nominal), medInt);
         unsigned gaps = 0;
-        for (double dt : stat.intervals) {
-          if (ref > 0.0 && dt > 2.0 * ref) {
+        for (int ii = 0; ii < stat.intervals.size(); ii++) {
+          double dt = stat.intervals[ii];
+          if (ref > 0.0 && dt > 2.0 * ref &&
+              !inOutage(stat.intervalEnds[ii] - dt, stat.intervalEnds[ii])) {
             ++gaps;
           }
         }
-        double maxLat = stat.latencies.isEmpty() ? 0.0 :
-                        *std::max_element(stat.latencies.begin(), stat.latencies.end());
+        QVector<double> latencies;
+        for (int ii = 0; ii < stat.latencies.size(); ii++) {
+          if (!afterOutage(stat.latencyEpochs[ii])) {
+            latencies.push_back(stat.latencies[ii]);
+          }
+        }
+        double maxLat = latencies.isEmpty() ? 0.0 :
+                        *std::max_element(latencies.begin(), latencies.end());
         out << "  " << sys << "   " << left << setw(10) << TYPE_NAME[type] << right
               << setw(8) << stat.numEpo
@@ -1739,7 +1838,18 @@
               << " /" << setw(7) << maxInt
               << setw(6) << gaps << setw(14) << stat.numOutOfOrder
-              << setw(10) << median(stat.latencies) << " /" << setw(7) << maxLat
+              << setw(10) << median(latencies) << " /" << setw(7) << maxLat
               << setw(7) << stat.sats.size() << endl;
       }
+    }
+
+    for (const t_outage& oo : outages) {
+      out << "  common outage of the input " << tStr(oo.start).toStdString() << " - "
+          << tStr(oo.end).toStdString() << " (" << oo.numSta << " of " << oo.numAll
+          << " streams): not counted as gaps, latencies until " << int(OUTAGE_LAT_AFTER)
+          << " s after it left out" << endl;
+    }
+    if (_badEpochs.value(staID)) {
+      out << "  corrections with an epoch time more than " << int(MAX_EPOCH_OFFSET)
+          << " s from their reception, not used: " << _badEpochs.value(staID) << endl;
     }
 
@@ -1901,4 +2011,24 @@
       addSats("corrections for satellites without broadcast ephemeris", noEph);
       QString staSys = QString("%1 %2").arg(staID).arg(sys);
+      if (_iodSwitch.contains(staSys)) {
+        const t_iodSwitchStat& sw = _iodSwitch[staSys];
+        // quantiles "min / 10 % / median / max"
+        auto quant = [](QVector<double> vv) {
+          std::sort(vv.begin(), vv.end());
+          return QString("%1 / %2 / %3 / %4").arg(vv.first(), 0, 'f', 0)
+                 .arg(vv[int(0.1 * (vv.size() - 1))], 0, 'f', 0)
+                 .arg(median(vv), 0, 'f', 0).arg(vv.last(), 0, 'f', 0);
+        };
+        if (!sw.afterRecept.isEmpty()) {
+          QString line = QString("IOD switch to new data sets (%1), delay after their reception by BNC "
+                                 "(ephemeris streams) min / 10 % / median / max: %2 s")
+                         .arg(sw.afterRecept.size()).arg(quant(sw.afterRecept));
+          if (!sw.afterToc.isEmpty()) {
+            line += QString(", after TOC: %1 s").arg(quant(sw.afterToc));
+          }
+          lines << line;
+        }
+        addSats("orbit corrections switching back to an older data set", sw.back);
+      }
       if (_codeSignals.contains(staSys)) {
         QStringList sigs = _codeSignals[staSys].values();
@@ -2115,4 +2245,6 @@
   _cmpStat.clear();
   _cmpEpochs.clear();
+  _iodSwitch.clear();
+  _badEpochs.clear();
   _attEvents.clear();
   _pbIndStat.clear();
@@ -2142,5 +2274,89 @@
     fresh.refBiasOK     = stat.refBiasOK;
     fresh.biasIF        = stat.biasIF;
+    fresh.orbIodSet     = stat.orbIodSet;
+    fresh.orbIod        = stat.orbIod;
+    fresh.newestToc     = stat.newestToc;
     stat = fresh;
   }
 }
+
+// Common outages of the input in the report interval: windows in which at
+// least OUTAGE_FRACTION (and OUTAGE_MIN_STA) of the streams with data had a
+// gap (interval > 2 x max(declared, median) of any of its message types)
+////////////////////////////////////////////////////////////////////////////
+QVector<t_ssrQc::t_outage> t_ssrQc::commonOutages(const QMap<QString, QSet<char> >& streams) const {
+  QVector<t_outage> outages;
+  // gap windows per stream, merged over the message types
+  QMap<double, int> events;   // time: change of the number of streams in a gap
+  unsigned numAll = 0;
+  QMapIterator<QString, QSet<char> > itSta(streams);
+  while (itSta.hasNext()) {
+    itSta.next();
+    QVector<QPair<double, double> > wins;
+    bool hasData = false;
+    for (char sys : itSta.value()) {
+      for (int type = ORB; type <= VTEC; type++) {
+        QString kk = QString("%1 %2 %3").arg(itSta.key()).arg(sys).arg(type);
+        if (!_epoStat.contains(kk)) continue;
+        const t_epoStat& stat = _epoStat[kk];
+        hasData = hasData || stat.numEpo > 0;
+        double ref = max(double(stat.nominal), median(stat.intervals));
+        for (int ii = 0; ii < stat.intervals.size(); ii++) {
+          if (ref > 0.0 && stat.intervals[ii] > 2.0 * ref) {
+            wins.push_back(qMakePair(stat.intervalEnds[ii] - stat.intervals[ii], stat.intervalEnds[ii]));
+          }
+        }
+      }
+    }
+    if (!hasData) continue;
+    ++numAll;
+    // gap of the stream: all its message types interrupted (intersection
+    // would need equal epochs; the union of overlapping windows of the
+    // types is used, a gap of a single type rarely coincides with others)
+    std::sort(wins.begin(), wins.end());
+    QVector<QPair<double, double> > merged;
+    for (const QPair<double, double>& ww : wins) {
+      if (!merged.isEmpty() && ww.first <= merged.last().second) {
+        merged.last().second = max(merged.last().second, ww.second);
+      }
+      else {
+        merged.push_back(ww);
+      }
+    }
+    for (const QPair<double, double>& ww : merged) {
+      events[ww.first]  += 1;
+      events[ww.second] -= 1;
+    }
+  }
+  unsigned need = max(OUTAGE_MIN_STA, unsigned(ceil(OUTAGE_FRACTION * numAll)));
+  if (numAll < need) {
+    return outages;
+  }
+  int      level = 0;
+  unsigned maxLevel = 0;
+  double   start = 0.0;
+  bool     open = false;
+  QMapIterator<double, int> itE(events);
+  while (itE.hasNext()) {
+    itE.next();
+    level += itE.value();
+    if (!open && level >= int(need)) {
+      open = true;
+      start = itE.key();
+      maxLevel = level;
+    }
+    else if (open && level >= int(need)) {
+      maxLevel = max(maxLevel, unsigned(level));
+    }
+    else if (open && level < int(need)) {
+      open = false;
+      t_outage oo;
+      oo.start  = start;
+      oo.end    = itE.key();
+      oo.numSta = maxLevel;
+      oo.numAll = numAll;
+      outages.push_back(oo);
+    }
+  }
+  return outages;
+}
