From 209998fe340fdeda6935c36e59ee8fd038c8a62e Mon Sep 17 00:00:00 2001
From: Phil Olynyk <phil@pholynyk.ca>
Date: Fri, 15 May 2020 21:27:08 -0400
Subject: [PATCH] Re-arrange code to backup STR.edf before other files

---
 .../SleepLib/loader_plugins/resmed_loader.cpp | 150 ++++++++++--------
 1 file changed, 82 insertions(+), 68 deletions(-)

diff --git a/oscar/SleepLib/loader_plugins/resmed_loader.cpp b/oscar/SleepLib/loader_plugins/resmed_loader.cpp
index 2d06c4a5..03f58e30 100644
--- a/oscar/SleepLib/loader_plugins/resmed_loader.cpp
+++ b/oscar/SleepLib/loader_plugins/resmed_loader.cpp
@@ -246,7 +246,7 @@ MachineInfo ResmedLoader::PeekInfo(const QString & path)
 long event_cnt = 0;
 
 bool parseIdentTGT( QString path, MachineInfo * info, QHash<QString, QString> & idmap );    // forward
-void BackupSTRfiles( const QString strpath, const QString path, const QString backupPath,
+void BackupSTRfiles( const QString strpath, const QString importPath, const QString strBackupPath,
                         MachineInfo & info, QMap<QDate, STRFile> & STRmap );                    // forward
 
 int ResmedLoader::Open(const QString & dirpath, ResDaySaveCallback s)                       // alternate for unit testing
@@ -263,24 +263,24 @@ int ResmedLoader::Open(const QString & dirpath)
     QString datalogPath;
     QHash<QString, QString> idmap;  // Temporary machine ID properties hash
 
-    QString path(dirpath);
-    path = path.replace("\\", "/");
+    QString importPath(dirpath);
+    importPath = importPath.replace("\\", "/");
 
     // Strip off end "/" if any
-    if (path.endsWith("/")) {
-        path = path.section("/", 0, -2);
+    if (importPath.endsWith("/")) {
+        importPath = importPath.section("/", 0, -2);
     }
 
-    // Strip off DATALOG from path, and set newpath to the path containing DATALOG
-    if (path.endsWith(RMS9_STR_datalog)) {
-        datalogPath = path + "/";
-        path = path.section("/", 0, -2);
+    // Strip off DATALOG from importPath, and set newimportPath to the importPath containing DATALOG
+    if (importPath.endsWith(RMS9_STR_datalog)) {
+        datalogPath = importPath + "/";
+        importPath = importPath.section("/", 0, -2);
     } else {
-        datalogPath = path + "/" + RMS9_STR_datalog + "/";
+        datalogPath = importPath + "/" + RMS9_STR_datalog + "/";
     }
 
     // Add separator back
-    path += "/";
+    importPath += "/";
 
     // Check DATALOG folder exists and is readable
     if (!QDir().exists(datalogPath)) {
@@ -291,7 +291,7 @@ int ResmedLoader::Open(const QString & dirpath)
     m_abort = false;
     MachineInfo info = newInfo();
 
-    if ( ! parseIdentTGT(path, & info, idmap) ) {
+    if ( ! parseIdentTGT(importPath, & info, idmap) ) {
         qDebug() << "Failed to parse Identification.tgt";
         return -1;
     }
@@ -311,7 +311,7 @@ int ResmedLoader::Open(const QString & dirpath)
     }
 
     // Early check for STR.edf file, so we can early exit before creating faulty machine record.
-    QString strpath = path + RMS9_STR_strfile + STR_ext_EDF; // STR.edf file
+    QString strpath = importPath + "STR.edf"; // STR.edf file
     QFile f(strpath);
 
     if (!f.exists()) { // No STR.edf.. Do we have a STR.edf.gz?
@@ -354,19 +354,54 @@ int ResmedLoader::Open(const QString & dirpath)
 
     QString backup_path = mach->getBackupPath();
 
-    if (path == backup_path) {
+    if (importPath == backup_path) {
         // Don't create backups if importing from backup folder
         importing_backups = true;
         create_backups = false;
     }
 
     ///////////////////////////////////////////////////////////////////////////////////
-    // Parse the idmap into machine objects properties, (overwriting any old values)
+    // Copy the idmap into machine objects properties, (overwriting any old values)
     ///////////////////////////////////////////////////////////////////////////////////
     for (auto i=idmap.begin(), idend=idmap.end(); i != idend; i++) {
         mach->properties[i.key()] = i.value();
     }
 
+    ///////////////////////////////////////////////////////////////////////////////////
+    // Create the backup folder for storing a copy of everything in..
+    // (Unless we are importing from this backup folder)
+    ///////////////////////////////////////////////////////////////////////////////////
+    QDir dir;
+    if (create_backups) {
+        if ( ! dir.exists(backup_path)) {
+            if ( ! dir.mkpath(backup_path + RMS9_STR_datalog)) {
+                qDebug() << "Could not create ResMed backup directory :-/";
+            }
+        }
+
+        QString importFile(importPath+"STR.edf");
+        QString backupFile(backup_path + "STR.edf");
+        if ( compress_backups ) {
+            backupFile += ".gz";
+            if ( QFile::exists( backupFile ) )
+                QFile::remove( backupFile );
+            compressFile(importFile, backupFile);
+        }
+        else {
+            if ( QFile::exists( backupFile ) )
+                QFile::remove( backupFile );
+            if ( ! QFile::copy(importFile, backupFile) )
+                qWarning() << "Failed to copy" << importFile << "to" << backupFile;
+        }
+
+        // Copy Identification files to backup folder
+        QFile::copy(importPath + RMS9_STR_idfile + STR_ext_TGT, backup_path + RMS9_STR_idfile + STR_ext_TGT);
+        QFile::copy(importPath + RMS9_STR_idfile + STR_ext_CRC, backup_path + RMS9_STR_idfile + STR_ext_CRC);
+
+        // Meh.. these can be calculated if ever needed for ResScan SDcard export
+        QFile::copy(importPath + "STR.crc", backup_path + "STR.crc");
+    }
+
     ///////////////////////////////////////////////////////////////////////////////////
     // Open and Parse STR.edf files (including those listed in STR_Backup)
     ///////////////////////////////////////////////////////////////////////////////////
@@ -382,7 +417,6 @@ int ResmedLoader::Open(const QString & dirpath)
 
     // Create the STR_Backup folder if it doesn't exist
     QString strBackupPath = backup_path + "STR_Backup";
-    QDir dir;
     if ( ! dir.exists(strBackupPath))
         dir.mkpath(strBackupPath);
 
@@ -390,9 +424,9 @@ int ResmedLoader::Open(const QString & dirpath)
     if ( ! dir.exists(newpath) )
         dir.mkpath(newpath);
 
-    if ( ! importing_backups ) {
-        BackupSTRfiles( strpath, path, backup_path, info, STRmap );
-    } else {    // get the STR file that is in the BACKUP folder
+    if ( ( ! importing_backups) /* && create_backups */ ) {
+        BackupSTRfiles( strpath, importPath, strBackupPath, info, STRmap );
+    } else {    // get the STR file that is in the BACKUP folder that we are rebuilding from
         ResMedEDFInfo * stredf = new ResMedEDFInfo();
         if ( stredf->Open(strpath) ) {
             if ( stredf->Parse()) {
@@ -418,7 +452,7 @@ int ResmedLoader::Open(const QString & dirpath)
     qDebug() << "STRmap size is " << STRmap.size();
 #endif
 
-    // Now we open the REAL STR_Backup, and open the rest for later parsing
+    // Now we open the REAL destination STR_Backup, and open the rest for later parsing
 
     dir.setPath(backup_path + "STR_Backup");
     dir.setFilter(QDir::Files | QDir::Hidden | QDir::Readable);
@@ -496,7 +530,7 @@ int ResmedLoader::Open(const QString & dirpath)
     for (auto it=STRmap.begin(), end=STRmap.end(); it != end; ++it) {
         QString fullname = it.value().filename;
 #ifdef STR_DEBUG
-        qDebug() << "Deleting edf of" << fullname;
+        qDebug() << "Deleting edf object of" << fullname;
 #endif
         QString datepart = fullname.section("STR-",-1).section(".edf",0,0);
         if (datepart.size() == 6 ) {    // old style name, change to full date
@@ -515,31 +549,6 @@ int ResmedLoader::Open(const QString & dirpath)
     qDebug() << "Finished STRmap cleanup";
 #endif
 
-    ///////////////////////////////////////////////////////////////////////////////////
-    // Create the backup folder for storing a copy of everything in..
-    // (Unless we are importing from this backup folder)
-    ///////////////////////////////////////////////////////////////////////////////////
-    dir.setPath(datalogPath);
-    if (create_backups) {
-        if ( ! dir.exists(backup_path)) {
-            if ( ! dir.mkpath(backup_path + RMS9_STR_datalog)) {
-                qDebug() << "Could not create ResMed backup directory :-/";
-            }
-        }
-
-        if ( compress_backups )
-            compressFile(path + "STR.edf", backup_path + "STR.edf.gz");
-        else
-            QFile::copy(path + "STR.edf", backup_path + "STR.edf");
-
-        // Copy Identification files to backup folder
-        QFile::copy(path + RMS9_STR_idfile + STR_ext_TGT, backup_path + RMS9_STR_idfile + STR_ext_TGT);
-        QFile::copy(path + RMS9_STR_idfile + STR_ext_CRC, backup_path + RMS9_STR_idfile + STR_ext_CRC);
-
-        // Meh.. these can be calculated if ever needed for ResScan SDcard export
-        QFile::copy(path + "STR.crc", backup_path + "STR.crc");
-    }
-
     ///////////////////////////////////////////////////////////////////////////////////
     // Scan DATALOG files, sort, and import any new sessions
     ///////////////////////////////////////////////////////////////////////////////////
@@ -557,6 +566,7 @@ int ResmedLoader::Open(const QString & dirpath)
 
     qDebug() << "Starting scan of DATALOG";
 //  sleep(1);
+    dir.setPath(datalogPath);
     ScanFiles(mach, datalogPath, firstImportDay);
     if (isAborted())
         return 0;
@@ -1477,29 +1487,33 @@ bool parseIdentTGT( QString path, MachineInfo * info, QHash<QString, QString> &
     return true;
 }
 
-void BackupSTRfiles( const QString strpath, const QString importPath, const QString backupPath, 
+void BackupSTRfiles( const QString strpath, const QString importPath, const QString strBackupPath, 
                     MachineInfo & info, QMap<QDate, STRFile> & STRmap )
 {
-    // copy the STR.edf file into Backup folder, safely
-    QString strBackupFile(backupPath+"STR.edf");
-    if (QFile::exists(strBackupFile) ) {
-        qDebug() << "Renaming existing STR.edf file";
-        if ( ! QFile::rename(strBackupFile, strBackupFile+"~") )
-            qWarning() << "Failed to rename" << strBackupFile;
-    }
-    qDebug() << "Copy inported STR.edf into Backup";
-    if ( ! QFile::copy(strpath, strBackupFile) ) {
-        qWarning() << "Failed to copy STR.edf to Backup folder";
-        qDebug() << "Undoing rename of existing STR.edf file";
-        if ( ! QFile::rename(strBackupFile+"~", strBackupFile) ) {
-            qWarning() << "Failed to rename" << strBackupFile << "+~";
-        }
-    }
-    else {  // copy was successful, remove the old, renamed copy
-        qDebug() << "Remove the renamed STR.edf file";
-        if ( ! QFile::remove(strBackupFile+"~") ) 
-            qWarning() << "Failed to remove" << strBackupFile << "+~";
-    }
+    Q_UNUSED(importPath);
+//      The commented-out code has been done before this routine is called - this routine
+//      copies the files from importpath/STR_Backup into backupPath/STR_Backup
+//
+//    // copy the STR.edf file into Backup folder, safely
+//    QString strBackupFile(backupPath+"STR.edf");
+//    if (QFile::exists(strBackupFile) ) {
+//        qDebug() << "Renaming existing STR.edf file";
+//        if ( ! QFile::rename(strBackupFile, strBackupFile+"~") )
+//            qWarning() << "Failed to rename" << strBackupFile;
+//    }
+//    qDebug() << "Copy inported STR.edf into Backup";
+//    if ( ! QFile::copy(strpath, strBackupFile) ) {
+//        qWarning() << "Failed to copy STR.edf to Backup folder";
+//        qDebug() << "Undoing rename of existing STR.edf file";
+//        if ( ! QFile::rename(strBackupFile+"~", strBackupFile) ) {
+//            qWarning() << "Failed to rename" << strBackupFile << "+~";
+//        }
+//    }
+//    else {  // copy was successful, remove the old, renamed copy
+//        qDebug() << "Remove the renamed STR.edf file";
+//        if ( ! QFile::remove(strBackupFile+"~") ) 
+//            qWarning() << "Failed to remove" << strBackupFile << "+~";
+//    }
 
     QDir dir;
     QStringList strfiles;
@@ -1507,7 +1521,7 @@ void BackupSTRfiles( const QString strpath, const QString importPath, const QStr
     strfiles.push_back(strpath);
 
     // Just in case we are importing from a Backup folder, process OSCAR backup structures
-    QString strBackupPath(importPath + "STR_Backup");
+//  QString strBackupPath(importPath + "STR_Backup");
     dir.setPath(strBackupPath);
     dir.setFilter(QDir::Files | QDir::Hidden | QDir::Readable);
     QFileInfoList flist = dir.entryInfoList();