+ previous_nt = nt;
+ nt = bytes_to_num(receivedAnswer, 4);
+
+ // Transmit reader nonce with fake par
+ ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);
+
+ if (first_try && previous_nt && !nt_attacked) { // we didn't calibrate our clock yet
+ int nt_distance = dist_nt(previous_nt, nt);
+ if (nt_distance == 0) {
+ nt_attacked = nt;
+ }
+ else {
+ if (nt_distance == -99999) { // invalid nonce received, try again
+ continue;
+ }
+ sync_cycles = (sync_cycles - nt_distance);
+ if (MF_DBGLEVEL >= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i, nt_distance, sync_cycles);
+ continue;
+ }
+ }
+
+ if ((nt != nt_attacked) && nt_attacked) { // we somehow lost sync. Try to catch up again...
+ catch_up_cycles = -dist_nt(nt_attacked, nt);
+ if (catch_up_cycles == 99999) { // invalid nonce received. Don't resync on that one.
+ catch_up_cycles = 0;
+ continue;
+ }
+ if (catch_up_cycles == last_catch_up) {
+ consecutive_resyncs++;
+ }
+ else {
+ last_catch_up = catch_up_cycles;
+ consecutive_resyncs = 0;
+ }
+ if (consecutive_resyncs < 3) {
+ if (MF_DBGLEVEL >= 3) Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, -catch_up_cycles, consecutive_resyncs);
+ }
+ else {
+ sync_cycles = sync_cycles + catch_up_cycles;
+ if (MF_DBGLEVEL >= 3) Dbprintf("Lost sync in cycle %d for the fourth time consecutively (nt_distance = %d). Adjusting sync_cycles to %d.\n", i, -catch_up_cycles, sync_cycles);
+ }
+ continue;
+ }
+
+ consecutive_resyncs = 0;
+
+ // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
+ if (ReaderReceive(receivedAnswer))
+ {
+ catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
+