Index: trunk/BNC/src/rinex/rnxobsfile.cpp
===================================================================
--- trunk/BNC/src/rinex/rnxobsfile.cpp	(revision 11057)
+++ trunk/BNC/src/rinex/rnxobsfile.cpp	(revision 11192)
@@ -59,4 +59,11 @@
   _version  = 0.0;
   _interval = 0.0;
+  _timeSystem     = "GPS";
+  _rcvClkOffsAppl = -1;
+  _satSystem      = 'M';
+  _otherRecordsVersion = 0.0;
+  _hasLastObs     = false;
+  _hasObsCounts   = false;
+  _hasPrnObs      = false;
   for (unsigned iPrn = 1; iPrn <= t_prn::MAXPRN_GPS; iPrn++) {
     _wlFactorsL1[iPrn] = 1;
@@ -93,4 +100,15 @@
   int numLines = 0;
 
+  // full header (not the header records of an event)
+  // ------------------------------------------------
+  bool fullHeader = (maxLines == 0);
+  if (fullHeader) {
+    _otherRecords.clear();
+    _scaleFactors.clear();
+    _hasLastObs   = false;
+    _hasObsCounts = false;
+    _hasPrnObs    = false;
+  }
+
   while ( stream->status() == QTextStream::Ok && !stream->atEnd() ) {
     QString line = stream->readLine(); ++ numLines;
@@ -109,4 +127,7 @@
       QTextStream in(value.toLatin1(), QIODevice::ReadOnly);
       in >> _version;
+      _otherRecordsVersion = _version;
+      QChar satSystem = line.length() > 40 ? line[40] : QChar(' ');
+      _satSystem = (satSystem == ' ') ? 'G' : satSystem.toLatin1(); // blank: GPS (RINEX 2)
     }
     else if (key == "PGM / RUN BY / DATE") {
@@ -177,17 +198,32 @@
       QTextStream in(value.toLatin1(), QIODevice::ReadOnly);
       in >> _antXYZ[0] >> _antXYZ[1] >> _antXYZ[2];
+      if (fullHeader) {
+        _otherRecords << line;
+      }
     }
     else if (key == "ANTENNA: B.SIGHT XYZ") {
       QTextStream in(value.toLatin1(), QIODevice::ReadOnly);
       in >> _antBSG[0] >> _antBSG[1] >> _antBSG[2];
+      if (fullHeader) {
+        _otherRecords << line;
+      }
     }
     else if (key == "DOI") {
       _digitalObjectId = line.mid(0,60).trimmed();
+      if (fullHeader) {
+        _otherRecords << line;
+      }
     }
     else if (key == "LICENSE OF USE") {
       _licenseOfUse.append(line.mid(0,60).trimmed());
+      if (fullHeader) {
+        _otherRecords << line;
+      }
     }
     else if (key == "STATION INFORMATION") {
      _stationInformation.append(line.mid(0,60).trimmed());
+      if (fullHeader) {
+        _otherRecords << line;
+      }
     }
     else if (key == "# / TYPES OF OBSERV") {
@@ -245,4 +281,43 @@
       in >> year >> month >> day >> hour >> min >> sec;
       _startTime.set(year, month, day, hour, min, sec);
+      QString timeSystem = line.mid(48, 3).trimmed();
+      if (!timeSystem.isEmpty()) {
+        _timeSystem = timeSystem;
+      }
+    }
+    else if (key == "RCV CLOCK OFFS APPL") {
+      readInt(line, 0, 6, _rcvClkOffsAppl);
+    }
+    else if (key == "TIME OF LAST OBS") {
+      _hasLastObs = true;
+    }
+    else if (key == "# OF SATELLITES") {
+      _hasObsCounts = true;
+    }
+    else if (key == "PRN / # OF OBS") {
+      _hasPrnObs = true; // recomputed for the written file
+    }
+    else if (key == "SYS / SCALE FACTOR") {
+      // A1,1X,I4,2X,I2,12(1X,A3), continuation lines 10X,12(1X,A3)
+      char sys    = line.length() ? line[0].toLatin1() : ' ';
+      int  factor = 1;
+      int  nTypes = 0;
+      readInt(line, 2, 4, factor);
+      readInt(line, 8, 2, nTypes);
+      if (factor <= 0) {
+        factor = 1;
+      }
+      if (nTypes == 0) {
+        _scaleFactors[sys][""] = factor;
+      }
+      for (int ii = 0; ii < nTypes; ii++) {
+        if (ii > 0 && ii % 12 == 0) {
+          line = stream->readLine(); ++numLines;
+        }
+        QString type = line.mid(10 + 4*(ii % 12) + 1, 3).trimmed();
+        if (!type.isEmpty()) {
+          _scaleFactors[sys][type] = factor;
+        }
+      }
     }
     else if (key == "SYS / PHASE SHIFT"){
@@ -298,4 +373,9 @@
       }
       delete in;
+    }
+    else if (fullHeader && !key.isEmpty()) {
+      // kept verbatim, e.g. SIGNAL STRENGTH UNIT, LEAP SECONDS,
+      // SYS / DCBS APPLIED, SYS / PCVS APPLIED, ANTENNA: PHASECENTER
+      _otherRecords << line;
     }
     if (maxLines > 0 && numLines == maxLines) {
@@ -412,4 +492,13 @@
   _receiverVersion = header._receiverVersion;
   _startTime       = header._startTime;
+  _timeSystem      = header._timeSystem;
+  _rcvClkOffsAppl  = header._rcvClkOffsAppl;
+  _satSystem       = header._satSystem;
+  _scaleFactors    = header._scaleFactors;
+  _otherRecords    = header._otherRecords;
+  _otherRecordsVersion = header._version;
+  _hasLastObs      = header._hasLastObs;
+  _hasObsCounts    = header._hasObsCounts;
+  _hasPrnObs       = header._hasPrnObs;
   _usedSystems     = header._usedSystems;
   _comments        = header._comments;
@@ -638,6 +727,18 @@
   }
 
-  *stream << QString("%1           OBSERVATION DATA    M")
+  // Satellite system: the single system of the observation types, the one
+  // of the input file (RINEX 2: one list of types for all systems) or M
+  // -----------------------------------------------------------------------
+  char satSystem = 'M';
+  if (_obsTypes.size() == 1) {
+    satSystem = _obsTypes.firstKey();
+  }
+  else if (_version < 3.0 && _satSystem != 'M' && _satSystem != ' ' &&
+           _obsTypes.contains(_satSystem)) {
+    satSystem = _satSystem;
+  }
+  *stream << QString("%1           OBSERVATION DATA    %2")
     .arg(_version, 9, 'f', 2)
+    .arg(QChar(satSystem))
     .leftJustified(60)
            << "RINEX VERSION / TYPE\n";
@@ -720,4 +821,11 @@
            << "ANTENNA: DELTA H/E/N\n";
 
+  if (_rcvClkOffsAppl >= 0) {
+    *stream << QString("%1")
+      .arg(_rcvClkOffsAppl, 6)
+      .leftJustified(60)
+             << "RCV CLOCK OFFS APPL\n";
+  }
+
   if (_version < 3.0) {
     int defaultWlFact1 = _wlFactorsL1[1];
@@ -731,4 +839,40 @@
 
   *stream << obsTypesStrings().join("");
+
+  // SYS / SCALE FACTOR (RINEX >= 3), for the observation types written
+  // -------------------------------------------------------------------
+  if (_version >= 3.0) {
+    for (int iSys = 0; iSys < numSys(); iSys++) {
+      char sys = system(iSys);
+      if (!_scaleFactors.contains(sys)) {
+        continue;
+      }
+      QMap<int, QStringList> typesOfFactor;
+      for (int iType = 0; iType < nTypes(sys); iType++) {
+        QString type   = obsType(sys, iType);
+        int     factor = scaleFactor(sys, type);
+        if (factor > 1) {
+          typesOfFactor[factor] << type;
+        }
+      }
+      QMapIterator<int, QStringList> it(typesOfFactor);
+      while (it.hasNext()) {
+        it.next();
+        QStringList types = it.value();
+        if (types.size() == nTypes(sys)) {
+          types.clear(); // all observation types
+        }
+        QString hlp = QString("%1 %2  %3").arg(sys).arg(it.key(), 4).arg(types.size(), 2);
+        for (int ii = 0; ii < types.size(); ii++) {
+          if (ii > 0 && ii % 12 == 0) {
+            *stream << hlp.leftJustified(60) << "SYS / SCALE FACTOR\n";
+            hlp = QString().leftJustified(10);
+          }
+          hlp += QString(" %1").arg(types[ii], -3);
+        }
+        *stream << hlp.leftJustified(60) << "SYS / SCALE FACTOR\n";
+      }
+    }
+  }
 
   if (_interval > 0) {
@@ -750,9 +894,27 @@
     .arg(min, 6)
     .arg(sec, 13, 'f', 7)
-    .arg("GPS", 8)
+    .arg(_timeSystem, 8)
     .leftJustified(60)
            << "TIME OF FIRST OBS\n";
 
-  if (_version >= 3.0) {
+  if (_hasLastObs && _lastTime.valid()) {
+    _lastTime.civil_date(year, month, day);
+    _lastTime.civil_time(hour, min, sec);
+    *stream << QString("%1%2%3%4%5%6%7")
+      .arg(year, 6)
+      .arg(month, 6)
+      .arg(day, 6)
+      .arg(hour, 6)
+      .arg(min, 6)
+      .arg(sec, 13, 'f', 7)
+      .arg(_timeSystem, 8)
+      .leftJustified(60)
+             << "TIME OF LAST OBS\n";
+  }
+
+  // SYS / PHASE SHIFT: RINEX 3 only; strongly deprecated in RINEX 4
+  // and to be ignored by encoders (RINEX 4.02, 5.2.12, Table A2)
+  // ---------------------------------------------------------------
+  if (_version >= 3.0 && _version < 4.0) {
     if (_phaseShifts.empty()) {
       QMap<char, QStringList>::const_iterator it;
@@ -875,7 +1037,112 @@
   }
 
+  // Header records kept from the input file
+  // ---------------------------------------
+  for (int ii = 0; ii < _otherRecords.size(); ii++) {
+    QString record = convertRecord(_otherRecords[ii], _version, _otherRecordsVersion);
+    if (!record.isEmpty()) {
+      *stream << record << "\n";
+    }
+  }
+
+  // # OF SATELLITES and PRN / # OF OBS of the written file
+  // ------------------------------------------------------
+  if ((_hasObsCounts || _hasPrnObs) && !_obsCounts.isEmpty()) {
+    *stream << QString("%1").arg(_obsCounts.size(), 6).leftJustified(60)
+            << "# OF SATELLITES\n";
+    QMapIterator<QString, QVector<int> > it(_obsCounts);
+    while (_hasPrnObs && it.hasNext()) {
+      it.next();
+      QString hlp = QString("   %1").arg(it.key(), 3);
+      const QVector<int>& counts = it.value();
+      for (int ii = 0; ii < counts.size(); ii++) {
+        if (ii > 0 && ii % 9 == 0) {
+          *stream << hlp.leftJustified(60) << "PRN / # OF OBS\n";
+          hlp = QString().leftJustified(6);
+        }
+        hlp += QString("%1").arg(qMin(counts[ii], 99999), 6);
+      }
+      *stream << hlp.leftJustified(60) << "PRN / # OF OBS\n";
+    }
+  }
+
   *stream << QString()
     .leftJustified(60)
            << "END OF HEADER\n";
+}
+
+// Scale factor of an observation type (SYS / SCALE FACTOR, RINEX >= 3)
+////////////////////////////////////////////////////////////////////////////
+int t_rnxObsHeader::scaleFactor(char sys, const QString& type) const {
+  if (_version < 3.0 || !_scaleFactors.contains(sys)) {
+    return 1;
+  }
+  const QMap<QString, int>& factors = _scaleFactors[sys];
+  if (factors.contains(type)) {
+    return factors[type];
+  }
+  return factors.value("", 1);
+}
+
+// Header record (also from an event) converted to the output version;
+// empty if the record does not exist in the output version or defines
+// the layout of the observation records (given by the output header)
+////////////////////////////////////////////////////////////////////////////
+QString t_rnxObsHeader::convertRecord(const QString& line, double outVersion,
+                                      double inVersion) {
+  QString value = line.left(60);
+  QString key   = line.mid(60).trimmed();
+
+  static const QStringList layoutKeys = QStringList()
+    << "RINEX VERSION / TYPE" << "END OF HEADER" << "SYS / # / OBS TYPES"
+    << "# / TYPES OF OBSERV" << "SYS / SCALE FACTOR" << "TIME OF LAST OBS"
+    << "# OF SATELLITES" << "PRN / # OF OBS";
+  static const QStringList v4Keys = QStringList()
+    << "DOI" << "LICENSE OF USE" << "STATION INFORMATION";
+  static const QStringList v3Keys = QStringList()
+    << "MARKER TYPE" << "SIGNAL STRENGTH UNIT" << "SYS / DCBS APPLIED"
+    << "SYS / PCVS APPLIED" << "ANTENNA: PHASECENTER" << "ANTENNA: ZERODIR AZI"
+    << "ANTENNA: ZERODIR XYZ" << "CENTER OF MASS: XYZ" << "ANTENNA: DELTA X/Y/Z"
+    << "ANTENNA: B.SIGHT XYZ" << "GLONASS SLOT / FRQ #" << "GLONASS COD/PHS/BIS";
+  static const QStringList allKeys = QStringList()
+    << "COMMENT" << "MARKER NAME" << "MARKER NUMBER" << "OBSERVER / AGENCY"
+    << "REC # / TYPE / VERS" << "ANT # / TYPE" << "APPROX POSITION XYZ"
+    << "ANTENNA: DELTA H/E/N" << "INTERVAL" << "TIME OF FIRST OBS"
+    << "RCV CLOCK OFFS APPL" << "PGM / RUN BY / DATE";
+
+  if (key.isEmpty() || layoutKeys.contains(key)) {
+    return QString();
+  }
+  else if (key == "SYS / PHASE SHIFT") {   // RINEX 3 only
+    if (outVersion < 3.0 || outVersion >= 4.0) {
+      return QString();
+    }
+  }
+  else if (key == "WAVELENGTH FACT L1/2") { // RINEX 2 only
+    if (outVersion >= 3.0) {
+      return QString();
+    }
+  }
+  else if (key == "LEAP SECONDS") {         // RINEX 2: I6 only
+    if (outVersion < 3.0) {
+      value = value.left(6);
+    }
+  }
+  else if (v4Keys.contains(key)) {
+    if (outVersion < 4.0) {
+      return QString();
+    }
+  }
+  else if (v3Keys.contains(key)) {
+    if (outVersion < 3.0) {
+      return QString();
+    }
+  }
+  else if (!allKeys.contains(key)) {        // not known to BNC
+    if (inVersion > 0.0 && int(inVersion) != int(outVersion)) {
+      return QString();
+    }
+  }
+  return value.leftJustified(60) + key;
 }
 
@@ -1041,5 +1308,8 @@
   _inpOut       = inpOut;
   _stream       = 0;
+  _file         = 0;
   _flgPowerFail = false;
+  _epoFile      = 0;
+  _epoStream    = 0;
   if (_inpOut == input) {
     openRead(fileName);
@@ -1081,4 +1351,6 @@
     _stream->seek(0);
     _header.read(_stream);
+    _pendingEvents.clear();
+    _flgPowerFail = false;
   }
 
@@ -1093,4 +1365,6 @@
     _stream->seek(0);
     _header.read(_stream);
+    _pendingEvents.clear();
+    _flgPowerFail = false;
   }
 }
@@ -1116,52 +1390,215 @@
 ////////////////////////////////////////////////////////////////////////////
 void t_rnxObsFile::close() {
+  if (_epoStream) {
+    writeDeferredHeader();
+  }
   delete _stream; _stream = 0;
   delete _file;   _file = 0;
 }
 
-// Handle Special Epoch Flag
-////////////////////////////////////////////////////////////////////////////
-void t_rnxObsFile::handleEpochFlag(int flag, const QString& line,
-                                   bool& headerReRead) {
-
-  headerReRead = false;
-
-  // Power Failure
-  // -------------
-  if      (flag == 1) {
-    _flgPowerFail = true;
-  }
-
-  // Start moving antenna
-  // --------------------
-  else if (flag == 2) {
-    // no action
-  }
-
-  // Re-Read Header
-  // --------------
-  else if (flag == 3 || flag == 4 || flag == 5) {
-    int numLines = 0;
-    if (version() < 3.0) {
-      readInt(line, 29, 3, numLines);
+// Header written on close: the epochs are written to a temporary file
+// first, so that the header can hold TIME OF FIRST/LAST OBS and
+// # OF SATELLITES / PRN / # OF OBS of the written epochs
+////////////////////////////////////////////////////////////////////////////
+void t_rnxObsFile::writeHeaderOnClose(const QMap<QString, QString>& txtMap) {
+  if (_inpOut != output || _epoStream) {
+    return;
+  }
+  _txtMap  = txtMap;
+  _epoFile = new QTemporaryFile(_fileName + ".XXXXXX");
+  if (!_epoFile->open()) {
+    delete _epoFile; _epoFile = 0;
+    _header.write(_stream, &_txtMap); // no temporary file: header now
+    return;
+  }
+  _epoStream = new QTextStream(_epoFile);
+}
+
+// Write header and copy the epochs from the temporary file
+////////////////////////////////////////////////////////////////////////////
+void t_rnxObsFile::writeDeferredHeader() {
+  _epoStream->flush();
+  if (_firstEpoTime.valid()) {
+    _header._startTime = _firstEpoTime;
+    _header._lastTime  = _lastEpoTime;
+  }
+  _header._obsCounts = _obsCounts;
+  _header.write(_stream, &_txtMap);
+  _stream->flush();
+
+  _epoFile->seek(0);
+  while (!_epoFile->atEnd()) {
+    QByteArray buffer = _epoFile->read(1 << 20);
+    if (buffer.isEmpty()) {
+      break;
+    }
+    _file->write(buffer);
+  }
+  _file->flush();
+
+  delete _epoStream; _epoStream = 0;
+  delete _epoFile;   _epoFile   = 0; // removes the temporary file
+}
+
+// Read Event Record (epoch flag 2-6); the event is kept until the next
+// observation epoch (or pendingEvents() at the end of the file)
+////////////////////////////////////////////////////////////////////////////
+void t_rnxObsFile::readEvent(int flag, QString& line) {
+
+  t_rnxEvent event;
+  event.flag    = flag;
+  event.version = version();
+
+  bool v3 = (version() >= 3.0);
+
+  // Epoch (may be blank for events without significant epoch)
+  // ---------------------------------------------------------
+  QString epoStr = v3 ? line.mid(1, 28) : line.mid(0, 26);
+  if (!epoStr.trimmed().isEmpty()) {
+    QTextStream in(epoStr.toLatin1(), QIODevice::ReadOnly);
+    int    year = 0, month = 0, day = 0, hour = 0, min = 0;
+    double sec = 0.0;
+    in >> year >> month >> day >> hour >> min >> sec;
+    if (!v3) {
+      if      (year <  80) {year += 2000;}
+      else if (year < 100) {year += 1900;}
+    }
+    event.tt.set(year, month, day, hour, min, sec);
+    event.epochValid = true;
+    int psec;
+    if (v3 && !line.mid(57, 5).trimmed().isEmpty() &&
+        readInt(line, 57, 5, psec) == 0 && psec >= 0 && psec <= 99999) {
+      event.psec = psec;
+      event.tt   = event.tt + psec * 1.e-12;
+    }
+  }
+
+  int numRecords = 0;
+  readInt(line, v3 ? 32 : 29, 3, numRecords);
+
+  // Cycle slip records (same format as observation records)
+  // -------------------------------------------------------
+  if (flag == 6) {
+    if (v3) {
+      readSatRecordsV3(numRecords, event.slips);
     }
     else {
-      readInt(line, 32, 3, numLines);
+      readSatRecordsV2(line, numRecords, event.slips);
+    }
+  }
+
+  // Special records (header records)
+  // --------------------------------
+  else {
+    for (int ii = 0; ii < numRecords; ii++) {
+      event.records << _stream->readLine();
     }
     if (flag == 3 || flag == 4) {
-      _header.read(_stream, numLines);
-      headerReRead = true;
-    }
-    else {
-      for (int ii = 0; ii < numLines; ii++) {
-        _stream->readLine();
-      }
-    }
-  }
-
-  // Unhandled Flag
-  // --------------
-  else {
-    throw QString("t_rnxObsFile: unhandled flag\n" + line);
+      QString hlp = event.records.join("\n");
+      QTextStream in(&hlp, QIODevice::ReadOnly);
+      _header.read(&in, numRecords);
+    }
+  }
+
+  _pendingEvents.append(event);
+}
+
+// Events read after the last observation epoch
+////////////////////////////////////////////////////////////////////////////
+QList<t_rnxObsFile::t_rnxEvent> t_rnxObsFile::pendingEvents() {
+  QList<t_rnxEvent> events = _pendingEvents;
+  _pendingEvents.clear();
+  return events;
+}
+
+// Read Satellite Records (RINEX Version 3)
+////////////////////////////////////////////////////////////////////////////
+void t_rnxObsFile::readSatRecordsV3(int numSat, std::vector<t_rnxSat>& rnxSats) {
+  rnxSats.resize(numSat);
+  for (int iSat = 0; iSat < numSat; iSat++) {
+    QString line = _stream->readLine();
+    t_prn prn; prn.set(line.left(3).toLatin1().data());
+    char sys = prn.system();
+    int num  = prn.number();
+    int flag = t_corrSSR::getSsrNavTypeFlag(sys, num);
+    prn.setFlag(flag);
+    rnxSats[iSat].prn = prn;
+    for (int iType = 0; iType < _header.nTypes(sys); iType++) {
+      int pos = 3 + 16*iType;
+      double obsValue = 0.0;
+      int    lli      = 0;
+      int    snr      = 0;
+      readDbl(line, pos,     14, obsValue);
+      readInt(line, pos + 14, 1, lli);
+      readInt(line, pos + 15, 1, snr);
+      if (_flgPowerFail) {
+        lli |= 1;
+      }
+      QString type = obsType(sys, iType);
+      rnxSats[iSat].obs[type].value = obsValue / _header.scaleFactor(sys, type);
+      rnxSats[iSat].obs[type].lli   = lli;
+      rnxSats[iSat].obs[type].snr   = snr;
+    }
+  }
+}
+
+// Read Satellite List (epoch line and continuation lines) and Satellite
+// Records (RINEX Version 2)
+////////////////////////////////////////////////////////////////////////////
+void t_rnxObsFile::readSatRecordsV2(QString& line, int numSat,
+                                    std::vector<t_rnxSat>& rnxSats) {
+  rnxSats.resize(numSat);
+
+  // Read Satellite Numbers
+  // ----------------------
+  int pos = 32;
+  for (int iSat = 0; iSat < numSat; iSat++) {
+    if (iSat > 0 && iSat % 12 == 0) {
+      line = _stream->readLine();
+      pos = 32;
+    }
+
+    char sys = line.toLatin1()[pos];
+    if (sys == ' ') {
+      sys = 'G';
+    }
+    int num; readInt(line, pos + 1, 2, num);
+    int flag = t_corrSSR::getSsrNavTypeFlag(sys, num);
+    t_prn prn;
+    prn.set(sys, num, flag);
+    rnxSats[iSat].prn = prn;
+
+    pos += 3;
+  }
+
+  // Read Observation Records
+  // ------------------------
+  for (int iSat = 0; iSat < numSat; iSat++) {
+    char sys = rnxSats[iSat].prn.system();
+    line = _stream->readLine();
+    pos  = 0;
+    for (int iType = 0; iType < _header.nTypes(sys); iType++) {
+      if (iType > 0 && iType % 5 == 0) {
+        line = _stream->readLine();
+        pos  = 0;
+      }
+      double obsValue = 0.0;
+      int    lli      = 0;
+      int    snr      = 0;
+      readDbl(line, pos,     14, obsValue);
+      readInt(line, pos + 14, 1, lli);
+      readInt(line, pos + 15, 1, snr);
+
+      if (_flgPowerFail) {
+        lli |= 1;
+      }
+
+      QString type = obsType(sys, iType);
+      rnxSats[iSat].obs[type].value = obsValue;
+      rnxSats[iSat].obs[type].lli   = lli;
+      rnxSats[iSat].obs[type].snr   = snr;
+
+      pos += 16;
+    }
   }
 }
@@ -1193,11 +1630,12 @@
     int flag = 0;
     readInt(line, 31, 1, flag);
-    if (flag > 0) {
-      bool headerReRead = false;
-      handleEpochFlag(flag, line, headerReRead);
-      if (headerReRead) {
-        continue;
-      }
-    }
+    if (flag > 1) {
+      readEvent(flag, line);
+      continue;
+    }
+    if (flag == 1) { // power failure between previous and current epoch
+      _flgPowerFail = true;
+    }
+    _currEpo.flag = flag;
 
     QTextStream in(line.mid(1).toLatin1(), QIODevice::ReadOnly);
@@ -1215,35 +1653,28 @@
     readInt(line, 32, 3, numSat);
 
-    _currEpo.rnxSat.resize(numSat);
+    // Receiver Clock Offset (optional, 6X,F15.12)
+    // and additional pico-sec digits (optional, RINEX >= 4.02, 1X,I5.5)
+    // -----------------------------------------------------------------
+    double clkOffset;
+    if (!line.mid(41, 15).trimmed().isEmpty() &&
+        readDbl(line, 41, 15, clkOffset) == 0) {
+      _currEpo.clkOffset      = clkOffset;
+      _currEpo.clkOffsetValid = true;
+    }
+    int psec;
+    if (!line.mid(57, 5).trimmed().isEmpty() &&
+        readInt(line, 57, 5, psec) == 0 && psec >= 0 && psec <= 99999) {
+      _currEpo.psec = psec;
+      _currEpo.tt   = _currEpo.tt + psec * 1.e-12;
+    }
 
     // Observations
     // ------------
-    for (int iSat = 0; iSat < numSat; iSat++) {
-      line = _stream->readLine();
-      t_prn prn; prn.set(line.left(3).toLatin1().data());
-      char sys = prn.system();
-      int num  = prn.number();
-      int flag = t_corrSSR::getSsrNavTypeFlag(sys, num);
-      prn.setFlag(flag);
-      _currEpo.rnxSat[iSat].prn = prn;
-      for (int iType = 0; iType < _header.nTypes(sys); iType++) {
-        int pos = 3 + 16*iType;
-        double obsValue = 0.0;
-        int    lli      = 0;
-        int    snr      = 0;
-        readDbl(line, pos,     14, obsValue);
-        readInt(line, pos + 14, 1, lli);
-        readInt(line, pos + 15, 1, snr);
-        if (_flgPowerFail) {
-          lli |= 1;
-        }
-        QString type = obsType(sys, iType);
-        _currEpo.rnxSat[iSat].obs[type].value = obsValue;
-        _currEpo.rnxSat[iSat].obs[type].lli   = lli;
-        _currEpo.rnxSat[iSat].obs[type].snr   = snr;
-      }
-    }
+    readSatRecordsV3(numSat, _currEpo.rnxSat);
 
     _flgPowerFail = false;
+
+    _currEpo.events = _pendingEvents;
+    _pendingEvents.clear();
 
     return &_currEpo;
@@ -1267,11 +1698,12 @@
     int flag = 0;
     readInt(line, 28, 1, flag);
-    if (flag > 0) {
-      bool headerReRead = false;
-      handleEpochFlag(flag, line, headerReRead);
-      if (headerReRead) {
-        continue;
-      }
-    }
+    if (flag > 1) {
+      readEvent(flag, line);
+      continue;
+    }
+    if (flag == 1) { // power failure between previous and current epoch
+      _flgPowerFail = true;
+    }
+    _currEpo.flag = flag;
 
     QTextStream in(line.toLatin1(), QIODevice::ReadOnly);
@@ -1295,60 +1727,21 @@
     readInt(line, 29, 3, numSat);
 
-    _currEpo.rnxSat.resize(numSat);
-
-    // Read Satellite Numbers
-    // ----------------------
-    int pos = 32;
-    for (int iSat = 0; iSat < numSat; iSat++) {
-      if (iSat > 0 && iSat % 12 == 0) {
-        line = _stream->readLine();
-        pos = 32;
-      }
-
-      char sys = line.toLatin1()[pos];
-      if (sys == ' ') {
-        sys = 'G';
-      }
-      int num; readInt(line, pos + 1, 2, num);
-      int flag = t_corrSSR::getSsrNavTypeFlag(sys, num);
-      t_prn prn;
-      prn.set(sys, num, flag);
-      _currEpo.rnxSat[iSat].prn = prn;
-
-      pos += 3;
-    }
-
-    // Read Observation Records
-    // ------------------------
-    for (int iSat = 0; iSat < numSat; iSat++) {
-      char sys = _currEpo.rnxSat[iSat].prn.system();
-      line = _stream->readLine();
-      pos  = 0;
-      for (int iType = 0; iType < _header.nTypes(sys); iType++) {
-        if (iType > 0 && iType % 5 == 0) {
-          line = _stream->readLine();
-          pos  = 0;
-        }
-        double obsValue = 0.0;
-        int    lli      = 0;
-        int    snr      = 0;
-        readDbl(line, pos,     14, obsValue);
-        readInt(line, pos + 14, 1, lli);
-        readInt(line, pos + 15, 1, snr);
-
-        if (_flgPowerFail) {
-          lli |= 1;
-        }
-
-        QString type = obsType(sys, iType);
-        _currEpo.rnxSat[iSat].obs[type].value = obsValue;
-        _currEpo.rnxSat[iSat].obs[type].lli   = lli;
-        _currEpo.rnxSat[iSat].obs[type].snr   = snr;
-
-        pos += 16;
-      }
-    }
+    // Receiver Clock Offset (optional, F12.9)
+    // ---------------------------------------
+    double clkOffset;
+    if (!line.mid(68, 12).trimmed().isEmpty() &&
+        readDbl(line, 68, 12, clkOffset) == 0) {
+      _currEpo.clkOffset      = clkOffset;
+      _currEpo.clkOffsetValid = true;
+    }
+
+    // Satellite list and observations
+    // -------------------------------
+    readSatRecordsV2(line, numSat, _currEpo.rnxSat);
 
     _flgPowerFail = false;
+
+    _currEpo.events = _pendingEvents;
+    _pendingEvents.clear();
 
     return &_currEpo;
@@ -1365,9 +1758,37 @@
   }
   t_rnxEpo epoLocal;
-  epoLocal.tt = epo->tt;
-  for (unsigned ii = 0; ii < epo->rnxSat.size(); ii++) {
-    const t_rnxSat& rnxSat = epo->rnxSat[ii];
-    if (_header._obsTypes[rnxSat.prn.system()].size() > 0) {
-      if (_header.version() < 3.0) { // exclude new GNSS such as BDS, QZSS, NavIC, etc.
+  epoLocal.tt             = epo->tt;
+  epoLocal.clkOffset      = epo->clkOffset;
+  epoLocal.clkOffsetValid = epo->clkOffsetValid;
+  epoLocal.psec           = epo->psec;
+  epoLocal.flag           = epo->flag;
+  epoLocal.rnxSat         = selectSats(_header, epo->rnxSat);
+
+  QTextStream* stream = _epoStream ? _epoStream : _stream;
+
+  writeEvents(stream, _header, epo->events);
+
+  if (!_firstEpoTime.valid()) {
+    _firstEpoTime = epo->tt;
+  }
+  _lastEpoTime = epo->tt;
+
+  if (version() < 3.0) {
+    return writeEpochV2(stream, _header, &epoLocal, &_obsCounts);
+  }
+  else {
+    return writeEpochV3(stream, _header, &epoLocal, &_obsCounts);
+  }
+}
+
+// Satellites with observation types in the header, sorted
+////////////////////////////////////////////////////////////////////////////
+std::vector<t_rnxObsFile::t_rnxSat> t_rnxObsFile::selectSats(const t_rnxObsHeader& header,
+                                                             const std::vector<t_rnxSat>& rnxSats) {
+  std::vector<t_rnxSat> selected;
+  for (unsigned ii = 0; ii < rnxSats.size(); ii++) {
+    const t_rnxSat& rnxSat = rnxSats[ii];
+    if (header._obsTypes.value(rnxSat.prn.system()).size() > 0) {
+      if (header.version() < 3.0) { // exclude new GNSS such as BDS, QZSS, NavIC, etc.
           if (rnxSat.prn.system() != 'G' && rnxSat.prn.system() != 'R' &&
               rnxSat.prn.system() != 'E' && rnxSat.prn.system() != 'S' &&
@@ -1376,14 +1797,104 @@
           }
       }
-      epoLocal.rnxSat.push_back(rnxSat);
-    }
-  }
-  std::stable_sort(epoLocal.rnxSat.begin(), epoLocal.rnxSat.end(), t_rnxSat::prnSort);
-
-  if (version() < 3.0) {
-    return writeEpochV2(_stream, _header, &epoLocal);
-  }
-  else {
-    return writeEpochV3(_stream, _header, &epoLocal);
+      selected.push_back(rnxSat);
+    }
+  }
+  std::stable_sort(selected.begin(), selected.end(), t_rnxSat::prnSort);
+  return selected;
+}
+
+// Civil date and time of an epoch record (F11.7 seconds); seconds that
+// would be rounded to 60.0000000 are carried over into the next minute
+////////////////////////////////////////////////////////////////////////////
+static void epochFields(const bncTime& tt, unsigned& year, unsigned& month,
+                        unsigned& day, unsigned& hour, unsigned& min, double& sec) {
+  tt.civil_date(year, month, day);
+  tt.civil_time(hour, min, sec);
+  if (nint(sec * 1.e7) >= 600000000) {
+    bncTime ttMin;
+    ttMin.set(int(year), int(month), int(day), int(hour), int(min), 0.0);
+    ttMin = ttMin + 60.0;
+    ttMin.civil_date(year, month, day);
+    ttMin.civil_time(hour, min, sec);
+    sec = 0.0;
+  }
+}
+
+// Epoch fields of an epoch record: "> yyyy mm dd hh mm ss.sssssss" (V3) or
+// " yy mm dd hh mm ss.sssssss" (V2); with pico-sec digits (RINEX >= 4.02)
+// the seconds hold the epoch floored to 0.1 microsec
+////////////////////////////////////////////////////////////////////////////
+static QString epochString(const bncTime& epoTime, int psec, bool writePsec, bool v3) {
+  bncTime  tt = writePsec ? epoTime - psec * 1.e-12 : epoTime;
+  unsigned year, month, day, hour, min;
+  double   sec;
+  epochFields(tt, year, month, day, hour, min, sec);
+  return QString(v3 ? "> %1 %2 %3 %4 %5%6" : " %1 %2 %3 %4 %5%6")
+    .arg(v3 ? int(year) : int(fmod(double(year), 100.0)), v3 ? 4 : 2, 10, QChar(v3 ? ' ' : '0'))
+    .arg(month, 2, 10, QChar('0'))
+    .arg(day,   2, 10, QChar('0'))
+    .arg(hour,  2, 10, QChar('0'))
+    .arg(min,   2, 10, QChar('0'))
+    .arg(sec,  11, 'f', 7);
+}
+
+// Write Events (epoch flags 2-6)
+////////////////////////////////////////////////////////////////////////////
+void t_rnxObsFile::writeEvents(QTextStream* stream, const t_rnxObsHeader& header,
+                               const QList<t_rnxEvent>& events) {
+  bool v3 = (header.version() >= 3.0);
+  for (int iEv = 0; iEv < events.size(); iEv++) {
+    const t_rnxEvent& event = events[iEv];
+
+    // Cycle slip records: written like an observation epoch
+    // -----------------------------------------------------
+    if (event.flag == 6) {
+      t_rnxEpo epo;
+      epo.tt     = event.tt;
+      epo.psec   = event.psec;
+      epo.flag   = 6;
+      epo.rnxSat = selectSats(header, event.slips);
+      if (event.epochValid && !epo.rnxSat.empty()) {
+        if (v3) {
+          writeEpochV3(stream, header, &epo);
+        }
+        else {
+          writeEpochV2(stream, header, &epo);
+        }
+      }
+      continue;
+    }
+
+    // Special records: header records valid in the output version, without
+    // the ones defining the observation record layout (fixed by the output
+    // header)
+    // -------------------------------------------------------------------
+    QStringList records;
+    for (int ii = 0; ii < event.records.size(); ii++) {
+      QString record = t_rnxObsHeader::convertRecord(event.records[ii], header.version(), event.version);
+      if (!record.isEmpty()) {
+        records << record;
+      }
+    }
+    if ((event.flag == 3 || event.flag == 4) && records.isEmpty()) {
+      continue;
+    }
+
+    bool writePsec = (event.epochValid && event.psec >= 0 && header.version() >= 4.02);
+    QString epoLine;
+    if (event.epochValid) {
+      epoLine = epochString(event.tt, event.psec, writePsec, v3);
+    }
+    else {
+      epoLine = v3 ? QString(">").leftJustified(29) : QString().leftJustified(26);
+    }
+    epoLine += QString("%1%2").arg(event.flag, 3).arg(records.size(), 3);
+    if (writePsec) {
+      epoLine += QString().leftJustified(21) + QString(" %1").arg(event.psec, 5, 10, QChar('0'));
+    }
+    *stream << epoLine << "\n";
+    for (int ii = 0; ii < records.size(); ii++) {
+      *stream << records[ii] << "\n";
+    }
   }
 }
@@ -1392,34 +1903,36 @@
 ////////////////////////////////////////////////////////////////////////////
 void t_rnxObsFile::writeEpochV2(QTextStream* stream, const t_rnxObsHeader& header,
-                                const t_rnxEpo* epo) {
-
-  unsigned year, month, day, hour, min;
-  double sec;
-  epo->tt.civil_date(year, month, day);
-  epo->tt.civil_time(hour, min, sec);
-
-  QString dateStr;
-  QTextStream(&dateStr) << QString(" %1 %2 %3 %4 %5%6")
-    .arg(int(fmod(double(year), 100.0)), 2, 10, QChar('0'))
-    .arg(month,                          2, 10, QChar('0'))
-    .arg(day,                            2, 10, QChar('0'))
-    .arg(hour,                           2, 10, QChar('0'))
-    .arg(min,                            2, 10, QChar('0'))
-    .arg(sec,                           11, 'f', 7);
-
-  int flag = 0;
-  *stream << dateStr << QString("%1%2").arg(flag, 3).arg(epo->rnxSat.size(), 3);
+                                const t_rnxEpo* epo, t_obsCounts* obsCounts) {
+
+  QString dateStr = epochString(epo->tt, epo->psec, false, false);
+
+  int flag = epo->flag;
+  QString epoLine = dateStr + QString("%1%2").arg(flag, 3).arg(epo->rnxSat.size(), 3);
   for (unsigned iSat = 0; iSat < epo->rnxSat.size(); iSat++) {
     const t_rnxSat& rnxSat = epo->rnxSat[iSat];
     if (iSat > 0 && iSat % 12 == 0) {
-      *stream << Qt::endl << QString().leftJustified(32);
-    }
-    *stream << rnxSat.prn.toString().c_str();
-  }
-  *stream << Qt::endl;
+      if (iSat == 12 && epo->clkOffsetValid) {
+        epoLine += QString("%1").arg(epo->clkOffset, 12, 'f', 9);
+      }
+      *stream << epoLine << Qt::endl;
+      epoLine = QString().leftJustified(32);
+    }
+    epoLine += rnxSat.prn.toString().c_str();
+  }
+  // Receiver clock offset (F12.9, columns 69-80 of the first line)
+  // -------------------------------------------------------------
+  if (epo->rnxSat.size() <= 12 && epo->clkOffsetValid) {
+    epoLine = epoLine.leftJustified(68) + QString("%1").arg(epo->clkOffset, 12, 'f', 9);
+  }
+  *stream << epoLine << Qt::endl;
 
   for (unsigned iSat = 0; iSat < epo->rnxSat.size(); iSat++) {
     const t_rnxSat& rnxSat = epo->rnxSat[iSat];
     char            sys    = rnxSat.prn.system();
+    QVector<int>*   counts = 0;
+    if (obsCounts) {
+      counts = &(*obsCounts)[QString(rnxSat.prn.toString().c_str())];
+      counts->resize(header.nTypes(sys));
+    }
     for (int iTypeV2 = 0; iTypeV2 < header.nTypes(sys); iTypeV2++) {
       if (iTypeV2 > 0 && iTypeV2 % 5 == 0) {
@@ -1458,4 +1971,7 @@
               else {
                 *stream << QString("%1").arg(rnxObs.value, 14, 'f', 3);
+                if (counts) {
+                  (*counts)[iTypeV2]++;
+                }
                 if (rnxObs.lli != 0.0) {
                   *stream << QString("%1").arg(rnxObs.lli,1);
@@ -1487,22 +2003,28 @@
 ////////////////////////////////////////////////////////////////////////////
 void t_rnxObsFile::writeEpochV3(QTextStream* stream, const t_rnxObsHeader& header,
-                                const t_rnxEpo* epo) {
-
-  unsigned year, month, day, hour, min;
-  double sec;
-  epo->tt.civil_date(year, month, day);
-  epo->tt.civil_time(hour, min, sec);
-
-  QString dateStr;
-  QTextStream(&dateStr) << QString("> %1 %2 %3 %4 %5%6")
-      .arg(year, 4)
-      .arg(month, 2, 10, QChar('0'))
-      .arg(day, 2, 10, QChar('0'))
-      .arg(hour, 2, 10, QChar('0'))
-      .arg(min, 2, 10, QChar('0'))
-      .arg(sec, 11, 'f', 7);
-
-  int flag = 0;
-  *stream << dateStr << QString("%1%2\n").arg(flag, 3).arg(epo->rnxSat.size(), 3);
+                                const t_rnxEpo* epo, t_obsCounts* obsCounts) {
+
+  // Additional pico-sec digits (RINEX >= 4.02): the seconds field holds the
+  // epoch floored to 0.1 microsec, the digits beyond are appended
+  // (RINEX < 4.02: epoch rounded to 0.1 microsec)
+  // ------------------------------------------------------------------------
+  bool    writePsec = (epo->psec >= 0 && header.version() >= 4.02);
+  QString dateStr   = epochString(epo->tt, epo->psec, writePsec, true);
+
+  int flag = epo->flag;
+  QString epoLine = dateStr + QString("%1%2").arg(flag, 3).arg(epo->rnxSat.size(), 3);
+  if (epo->clkOffsetValid || writePsec) {
+    epoLine += QString().leftJustified(6);
+    if (epo->clkOffsetValid) {
+      epoLine += QString("%1").arg(epo->clkOffset, 15, 'f', 12);
+    }
+    else {
+      epoLine += QString().leftJustified(15);
+    }
+    if (writePsec) {
+      epoLine += QString(" %1").arg(epo->psec, 5, 10, QChar('0'));
+    }
+  }
+  *stream << epoLine << "\n";
 
   for (unsigned iSat = 0; iSat < epo->rnxSat.size(); iSat++) {
@@ -1561,4 +2083,9 @@
     if (header.nTypes(sys)) {
       QString record = rnxSat.prn.toString().c_str();
+      QVector<int>* counts = 0;
+      if (obsCounts) {
+        counts = &(*obsCounts)[record];
+        counts->resize(header.nTypes(sys));
+      }
       for (int iTypeV3 = 0; iTypeV3 < header.nTypes(sys); iTypeV3++) {
         const t_rnxObs* rnxObs = hlp[iTypeV3];
@@ -1567,5 +2094,10 @@
         }
         else {
-          record += QString("%1").arg(rnxObs->value, 14, 'f', 3);
+          // SYS / SCALE FACTOR of the output header
+          int scale = header.scaleFactor(sys, header.obsType(sys, iTypeV3));
+          record += QString("%1").arg(rnxObs->value * scale, 14, 'f', 3);
+          if (counts) {
+            (*counts)[iTypeV3]++;
+          }
           if (rnxObs->lli != 0.0) {
             record += QString("%1").arg(rnxObs->lli, 1);
