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

/*
      The mark/space timings were estimated from sampling, but it is possible that they
   should be the NEC times: 562.5 for 0 and 1687.5 for 1 ?
 */

void addpair(int mark, int space, int *codes, int *count) {
  codes[*count] = mark; codes[(*count)+1] = space;
  *count = (*count)+2;
}

void outbyte(int b, int *codes, int *count) {
  int i;
  for (i = 0; i < 8; i++) {
    if (b&1) {
      //fprintf(stdout, " 512, 1652, ");
      addpair(512, 1652, codes, count);
    } else {
      //fprintf(stdout, " 512, 574, ");
      addpair(512, 574, codes, count);
    }
    b = b>>1;
  }
}

void savecode(char *name, int code0, int code1, int code2, int code3, int code4, int *codes, int *count) {
  int code5 = ((0xff + code0 + code1 + code2 + code3 + code4) ^ 0xff)&255;
  //fprintf(stderr, "%s = %02x %02x %02x %02x %02x %02x\n", name, code0, code1, code2, code3, code4, code5);
  //fprintf(stdout, "\"%s\": [4378, 4699, ", name);
  addpair(4378, 4699, codes, count);
    outbyte(code0, codes, count);
    outbyte(code1, codes, count);
    outbyte(code2, codes, count);
    outbyte(code3, codes, count);
    outbyte(code4, codes, count);
    outbyte(code5, codes, count);
  //fprintf(stdout, "512, 4699, 4378, 4699, ");
  addpair(512, 4699, codes, count);
  addpair(4378, 4699, codes, count);
    outbyte(code0^0xff, codes, count);
    outbyte(code1^0xff, codes, count);
    outbyte(code2^0xff, codes, count);
    outbyte(code3^0xff, codes, count);
    outbyte(code4^0xff, codes, count);
    outbyte(code5^0xff, codes, count);
  //fprintf(stdout, "512, 4699]");
  addpair(512, 4699, codes, count);
}

int main(int argc, char **argv) {
  int count, result, codes[1024];
  unsigned int outPin = 23;       // The Broadcom pin number the signal will be sent on
  int frequency = 38000;          // The frequency of the IR signal in Hz
  double dutyCycle = 0.5;         // The duty cycle of the IR signal. 0.5 means for every cycle,
                                  // the LED will turn on for half the cycle time, and off the other half

  savecode("led",   0x45, 0x10, 0xff, 0xff, 0xff, codes, &count);
  result = irSlingRaw(outPin, frequency, dutyCycle, codes, count);

  //savecode("swing", 0x45, 0x40, 0xff, 0xff, 0xff, codes, &count);
  //result = irSlingRaw(outPin, frequency, dutyCycle, codes, count);

  exit(0);
  return 1;
}