#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>

#include <unistd.h>

#include <stdarg.h>
#include <limits.h>

#define MCLK 6
#define DX 0

unsigned char reverse(unsigned char b) {
   b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
   b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
   b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
   return b;
}

int main(int argc, char **argv) {

  int i,j = 0;

  int gcnt = 0;
  int framecnt = 0;

  int prevclk = 0;
  int prevfs = 0;

  int sample = 0;
  int sptr = 0;

  int fss = 0;
  int sps = 0;

  char c;

  int pos = 0;

  while( (j=(read(0, &c, 1))) > 0 ) {

    char clk = (c >> MCLK) & 1;
    if(clk == 0 && prevclk == 1) {
      char dx = (c >> DX) & 1;
      if( pos <= 7) {
        sample = (sample << 1) | dx;
        sptr++;
        if(sptr == 8) {
          putchar(sample);
          sample = 0;
          sptr = 0;
          sps++;
        }
      }
      gcnt++;
      framecnt++;
      pos++;
      if(pos > 9) {
        pos = 0;
      }
    }

    prevclk = clk;
  }

  fprintf(stderr, "fss = %i, sps = %i\n", fss, sps);
}

