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

// compile with gcc readdat.c -o readdat
// run with ./readdat engineeringSettings.dat > jsonname.json

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

 int DEBUG = 0;

if( argc != 2 ) {
  printf("Usage: %s [engineeringSettings.dat filename]\n", argv[0]);
  return 0;
}

	FILE *file;
	char *buffer;
	unsigned long fileLen;

	//Open file
	file = fopen(argv[1], "rb");
        //file = fopen("engineeringSettings.dat", "rb");
	if (!file)
	{
		fprintf(stderr, "Unable to open file %s\n", argv[1]);
		return 0;
	}
	
	//Get file length
	fseek(file, 0, SEEK_END);
	fileLen=ftell(file);
	fseek(file, 0, SEEK_SET);

	//Allocate memory
	buffer=(char *)malloc(fileLen+1);
	if (!buffer)
	{
		fprintf(stderr, "Memory error!");
                                fclose(file);
		return 0;
	}

	//Read file contents into buffer
	fread(buffer, fileLen, 1, file);
	fclose(file);

	//Do what ever with buffer
if ( 1 == 0) {
int bufferSize = 402;
for (int y=0;y<fileLen;y++)
{

     //printf("%.2X ", (int)buffer[y]);
     printf("%#X ", (int)buffer[y]);

     // put an extra space between every 4 bytes
     if (y % 4 == 3)
     {
         printf(" ");
     }

     // Display 16 bytes per line
     if (y % 16 == 15)
     {
         printf("\n");
     }
}
// Add an extra line feed for good measure
printf("\n");
}
 if(fileLen != 402){ printf("Wrong file byte count. Should be 402.\n"); return 0; }


printf("[\n");

int i = 2; // 2 bytes of header
int ii = 34; // 8 * 4 bytes start of coolant

for (int preset=0; preset<10; preset++) {
  printf("\t{\n");
//  if(preset<9) 
//  printf("\n");
//  else
//printf("\n");

  printf("\t\t\"rigging\": \"Attack\",\n");
  printf("\t\t\"description\": \"Attack\",\n");
  printf("\t\t\"settings\": [");


if (DEBUG) printf("\n:%d %d\n",i,ii);
  for (int system = 0; system < 8; system ++) {

    float energy;
    memcpy(&energy, &buffer[i], 4);
    i+=4;
    energy = 300*energy;

    char coolant;
    memcpy(&coolant, &buffer[ii], 1);
    ii++;

    printf("[%d, %d]",(int)energy, coolant);
if (DEBUG) printf("%lu",sizeof(coolant));
    if(system<7) printf(",");

  }

  printf("]\n");

  printf("\t}");
  if(preset<9) printf(",\n");

  i += 8; // skip the coolant 
  ii = i+32; // skip the energy

}

printf("\n]\n");
if (DEBUG) printf("\n:%d %d\n",i,ii);

	free(buffer);
  return 1;
}
