From 2a64b060ea33b3b872e4fbcdf9bba0e18e948c0d Mon Sep 17 00:00:00 2001
From: Thomas Lambert <t.lambert@uliege.be>
Date: Mon, 23 Jan 2023 18:50:49 +0100
Subject: [PATCH] fix(loader): automate header lines counting

---
 utils/loadid.m | 35 +++++++++++++++++++++++++++++++----
 1 file changed, 31 insertions(+), 4 deletions(-)

diff --git a/utils/loadid.m b/utils/loadid.m
index 80513c5..9a24932 100644
--- a/utils/loadid.m
+++ b/utils/loadid.m
@@ -34,15 +34,42 @@ function idTable = loadid(idFile)
     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
     % Defaults and constants
-    COMMENT_LINES = 3; % Number of commented lines in the header
+    HEADER_STYLE = '#';
+
+    % Determine where the data starts
+    headerLines = calcheaderlines(idFile, HEADER_STYLE);
 
     % Tweak options before import
     opts = detectImportOptions(idFile);
-    opts.VariableNamesLine = COMMENT_LINES + 1;
-    opts.VariableUnitsLine = COMMENT_LINES + 2;
-    opts.DataLines = [COMMENT_LINES + 3 Inf];
+    opts.VariableNamesLine = headerLines + 1;
+    opts.VariableUnitsLine = headerLines + 2;
+    opts.DataLines = [headerLines + 3 Inf];
 
     % Import
     idTable = readtable(idFile, opts);
 
 end
+
+function headerLines = calcheaderlines(file, headerStyle)
+    % CALCHEADERLINES Calculate number of header lines in a file
+
+    fileID = fopen(file);
+
+    headerLines = 0;
+    inHeader = true;
+
+    while inHeader
+        line = textscan(fileID, '%s', 1, 'Delimiter', {'\n', '\r'});
+        line = char(line{:});
+
+        % The '' in the regex is not an empty space, it is the byte order mark that Matlab puts
+        % at the beginning of the stream...
+        if regexp(line, ['^\*\s*', headerStyle])
+            headerLines = headerLines + 1;
+        else
+            inHeader = false;
+        end
+
+    end
+
+end
-- 
GitLab