// Output: RGB interleaved RAW 24-bit bitmap

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

//#define BLOCK_LEN 318
#define BLOCK_LEN 424
//#define SKIP (8*636+318)
#define SKIP 5830
//#define SKIP 0
#define OFFSET_1 (2*BLOCK_LEN)
int main(int argc, char *argv[]) {
  FILE *input = fopen(argv[1], "r");
  if (!input) {
    perror("fopen");
    return 1;
  }
  if (fseek(input, 0, SEEK_END) < 0) {
    perror("seek");
    return 1;
  }
  int filesize = ftell(input) - SKIP;  
  
  if (fseek(input, SKIP, SEEK_SET) < 0) {
    perror("seek");
    return 1;
  }

  FILE *output = fopen(argv[2], "w");
  if (!output) {
    perror("fopen");
    return 1;
  }
//  char buf[3*BLOCK_LEN];
  char *buf = malloc(filesize);
  fread(buf, 1, filesize, input);
  char pixel[3];
  int pos = 0;
//  while (!feof(input)) {
  while (pos<filesize) {
//    fread(buf, BLOCK_LEN, 3, input);
    printf(".");
    for (int i = 0; i < BLOCK_LEN; i++) {
      pixel[0] = buf[pos+i+2*BLOCK_LEN];	// R
      pixel[1] = buf[(pos+15*BLOCK_LEN)+i];		// G
      pixel[2] = buf[(pos+9*BLOCK_LEN)+i+BLOCK_LEN];	// B
      fwrite(pixel, sizeof(pixel), 1, output);
    }
    pos+=3*BLOCK_LEN;
  }
  free(buf);
  fclose(input);
  fclose(output);
  printf("\n");
  return 0;
}

