//using logic analyzer at 1 mhz for 1 sec

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

#define BUFSIZE 1050
#define GRANULARITY 100

int main(int argn, char *args[])
{
FILE *fd;
char buffer[BUFSIZE];
int i,j,k,l;
char c;
int low,high;
int *cycles;
int cycle_index = 0;
int threshold = 20;
int threshold_accumulator = 0;

if (argn < 2)
{
printf("Now your binary is accesible to stdout!\n\n");
printf("Usage: binout inputfile threshold\n");
}

/*
for (i=0; i<argn; i++)
{
printf("%s\n", args[i]);

}
*/

fd = fopen(args[1], "rb");

sscanf(args[2], "%d", &threshold);
//printf("%d\n",threshold);


if (fd == NULL)
{
printf("Invalid input file: File Not Found\n");
return 1;
}

/*
fgets(buffer, BUFSIZE, fd);

for (i=0; i<BUFSIZE; i++)
{
printf("%c",buffer[i]);
}
*/

i=0;
while(!feof(fd))
{
fread(&c,1,1,fd);
i++; //what if this overflows!!?
}
rewind(fd);

cycles = malloc(sizeof(int)*i);

if (cycles == NULL)
  {
    printf("malloc failed to allocate %d integers", i);
    return 1;
  }

i=0; j=0; k=0; l=0; high=0; low=0;

while(!feof(fd))
{
  fread(&c,1,1,fd); //read into c an object 1 byte big 1 time from fd

  //if (c == 'ÿ')
  if (c == (char) 0xFF)
    {
    low = 1;
    i++;
    }
  //if (c == 'þ')
  if (c == (char) 0xFE)
    {
    high = 1;
    j++;
    }

  if (low == 1 && high == 1) //indicates a switch from low->high or high->low
    {
      if (c == (char) 0xFF && l >= threshold)
      {
        if (threshold != 0)
        {
          printf("- %d\n",threshold_accumulator);
          cycles[cycle_index] = threshold_accumulator;
          cycle_index++;
          threshold_accumulator = 0;
        }
        high = 0;
        printf("+ %d\n",l);
        cycles[cycle_index] = l;
        cycle_index++;
        l=0;
      }
      else
      {
        high = 0;
        threshold_accumulator += l;
        l = 0;
      }
      if (c == (char) 0xFE && k >= threshold)
      {
        if (threshold != 0)
        {
          printf("+ %d\n",threshold_accumulator);
          cycles[cycle_index] = threshold_accumulator;
          cycle_index++;
          threshold_accumulator = 0;
        }
        low = 0; 
        printf("- %d\n",k); 
        cycles[cycle_index] = k; 
        cycle_index++; 
        k=0; 
      }
      else
      {
        low = 0; 
        threshold_accumulator += k; 
        k = 0;
      }
    }

  if (low == 1 && high == 0)
    {
	k++;
    }

  if (low == 0 && high == 1)
    {
	l++;
    }

}
rewind(fd);

printf("\n%d %d = %d\n",i,j,i+j);

high=1;  //high is false
fread(&c,1,1,fd);
if (c == (char) 0xFF)
  {
    high = 0;
  }

for (i=0; i<cycle_index; i++)
  {
    if (high == 0)
      {
	high=1;
	for (j=GRANULARITY; j<cycles[i]; j+=GRANULARITY)
	  {
	    printf("-");
	  }
      } else {
	high=0;
	for (j=GRANULARITY; j<cycles[i]; j+=GRANULARITY)
	  {
	    printf("_");
	  }
      }

  }

printf("\n");
fclose(fd);
return 0;
}

