- //if 0 errors allowed then only try first 2 clock cycles as we want a low tolerance
- if (!maxErr && initLoopMax > *clk*3) initLoopMax = *clk * 3;
- //if best start not already found by detectclock
- if (start <= 0 || start > initLoopMax){
- bestErrCnt = maxErr+1;
- //PrintAndLog("DEBUG - lastbit - %d",lastBit);
- //loop to find first wave that works
- for (iii=0; iii < initLoopMax - *clk; ++iii){
- if ((BinStream[iii] >= high) || (BinStream[iii] <= low)){
- lastBit = iii - *clk;
- //loop through to see if this start location works
- for (i = iii; i < *size; ++i) {
- if (i-lastBit > *clk && (BinStream[i] >= high || BinStream[i] <= low)){
- lastBit += *clk;
- midBit = 0;
- } else if (i-lastBit > (*clk/2) && midBit == 0) {
- midBit = 1;
- } else if ((i-lastBit) > *clk) {
- //should have hit a high or low based on clock!!
- //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit);
- errCnt++;
- lastBit += *clk;//skip over until hit too many errors
- if (errCnt > maxErr)
- break;
- }
- if ((i-iii)>(MaxBits * *clk)) break; //got enough bits
- }
- //we got more than 32 good bits and not all errors
- if ((((i-iii)/ *clk) > 32) && (errCnt<=maxErr)) {
- //possible good read
- if (errCnt==0){
- bestStart=iii;
- bestErrCnt=errCnt;
- break; //great read - finish
- }
- if (errCnt<bestErrCnt){ //set this as new best run
- bestErrCnt=errCnt;
- bestStart = iii;
- }
- }
- errCnt=0;
- }
- }
- }
- if (bestErrCnt > maxErr){
- *invert = bestStart;
- *clk = iii;
- return -1;
- }
- //best run is good enough - set to best run and overwrite BinStream
- lastBit = bestStart - *clk - 1;
- errCnt = 0;
-
- for (i = bestStart; i < *size; ++i) {