// Generate the "this_machine.h" file and write it in ../clib directory

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

int main(int ac, char **av) {

  // Native pointer size should usually be equal to the native
  // register size. If this isn't how your architecture works, skip
  // this program and create your own "this_machine.h" file manually.
  int ptr_size   = sizeof(void *);

  // Only very unusual architectures will fail to have ptr_size that
  // isn't one of the options below:
  int short_size = sizeof(unsigned short);
  int int_size   = sizeof(unsigned int);
  int long_size  = sizeof(unsigned long);
  int llong_size = sizeof(unsigned long long);

  char *names[4] = {
    "unsigned short",
    "unsigned int",
    "unsigned long int",
    "unsigned long long int",
  };
  
  FILE *fp;

  int index = -1;

  if (ptr_size == short_size) index = 0;
  if (ptr_size == int_size)   index = 1;
  if (ptr_size == long_size)  index = 2;
  if (ptr_size == llong_size) index = 3;

  if (index < 0) {
    fprintf(stderr, "Pointer size %d does not correspond to any elementary int type\n",
	    ptr_size);
    exit(1);
  }

  if (!(fp = fopen("../clib/this_machine.h", "w"))) {
    fprintf(stderr, "Failed to open output file for writing\n");
    exit(2);
  }

  printf("Selected '%s' as having %d bytes in size\n", names[index], ptr_size);

  fprintf(fp, "// This file is automatically generated! Any edits may be lost!\n");
  fprintf(fp, "\n");
  fprintf(fp, "typedef %s native_register_t;\n", names[index]);

  fclose(fp);
  exit(0);


}
