#include <stdio.h>

int main(int argc, char *argv[]) {
  const char *usage = "Usage: index_number color [index_number color ...] " \
    "filename\n\n- index_number is an entry into the color table and ranges " \
    "from 0-255.\n- Color is an HTML formated color code, i.e.: 00CCFF\n" \
    "- filename is the name of the GIF file that is to have the color " \
    "replacement\n  performed on it.\n";
  FILE *f;
  int i;
  int var;
  char *val_ptr;
  int val;

  if (argc < 4) {
    fprintf(stderr, "Not enough arguments.\n\n%s", usage);
    return 1;
  }

  if (argc % 2 != 0) {
    fprintf(stderr, "Invalid number of arguments.\n\n%s", usage);
    return 1;
  }

  f = fopen(argv[argc - 1], "r+b");
  if (!f) {
    fprintf(stderr, "File %s cannot be opened for writing.\n", argv[argc -1]);
    return 1;
  }

  for (i = 1; i < argc - 1; i += 2) {
    var = atoi(argv[i]);
    val_ptr = argv[i + 1];
    if (*val_ptr == '#') val_ptr++;
    val = strtol(val_ptr, NULL, 16);
    val = (0x00FF00 & val) | ((0xFF0000 & val) >> 16) | ((0x0000FF & val) << 16);
    fseek(f, 13 + 3 * var, SEEK_SET);
    fwrite(&val, 3, 1, f);
  }

  fclose(f);
  return 0;
}
