From 5a847b2629c49d72ea2fa5eb5d1697fdef8095c9 Mon Sep 17 00:00:00 2001
From: iceman1001 <iceman@iuse.se>
Date: Fri, 16 Apr 2021 21:35:14 +0200
Subject: [PATCH] lf pac demod - now also checks for inverted bitstream

---
 client/src/cmdlfpac.c | 36 +++++++++++++++++++++++++++++-------
 client/src/cmdlfpac.h |  2 +-
 2 files changed, 30 insertions(+), 8 deletions(-)

diff --git a/client/src/cmdlfpac.c b/client/src/cmdlfpac.c
index 5c2ccd98c..f9d6b098c 100644
--- a/client/src/cmdlfpac.c
+++ b/client/src/cmdlfpac.c
@@ -123,8 +123,9 @@ int demodPac(bool verbose) {
         PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: NRZ Demod failed");
         return PM3_ESOFT;
     }
+    bool invert = false;
     size_t size = DemodBufferLen;
-    int ans = detectPac(DemodBuffer, &size);
+    int ans = detectPac(DemodBuffer, &size, &invert);
     if (ans < 0) {
         if (ans == -1)
             PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: too few bits found");
@@ -137,6 +138,12 @@ int demodPac(bool verbose) {
 
         return PM3_ESOFT;
     }
+
+    if (invert) {
+        for (size_t i = ans; i < ans + 128; i++) {
+            DemodBuffer[i] ^= 1;
+        }
+    }
     setDemodBuff(DemodBuffer, 128, ans);
     setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
 
@@ -394,14 +401,29 @@ int CmdLFPac(const char *Cmd) {
 }
 
 // find PAC preamble in already demoded data
-int detectPac(uint8_t *dest, size_t *size) {
-    if (*size < 128) return -1; //make sure buffer has data
+int detectPac(uint8_t *dest, size_t *size, bool *invert) {
+    // make sure buffer has data
+    if (*size < 128) 
+        return -1;
+
     size_t startIdx = 0;
     uint8_t preamble[] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0};
-    if (!preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx))
-        return -2; //preamble not found
-    if (*size != 128) return -3; //wrong demoded size
-    //return start position
+    if (!preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx)) {
+
+        // preamble not found
+        uint8_t pre_inv[] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1};
+        if (!preambleSearch(dest, pre_inv, sizeof(pre_inv), size, &startIdx)) {
+            return -2;
+        } else {
+            *invert = true;
+        }
+    }
+
+    // wrong demoded size
+    if (*size != 128)
+        return -3;
+    
+    // return start position
     return (int)startIdx;
 }
 
diff --git a/client/src/cmdlfpac.h b/client/src/cmdlfpac.h
index a2145051b..107280cdf 100644
--- a/client/src/cmdlfpac.h
+++ b/client/src/cmdlfpac.h
@@ -14,6 +14,6 @@
 int CmdLFPac(const char *Cmd);
 
 int demodPac(bool verbose);
-int detectPac(uint8_t *dest, size_t *size);
+int detectPac(uint8_t *dest, size_t *size, bool *invert);
 #endif