/* X3F_EXTRACT.C - Extracting images from X3F files
 * 
 * Copyright 2008 (c) - Roland Karlsson (roland@proxel.se)
 * BSD-style - see readme.txt
 * 
 */

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

typedef enum {NONE, RAW, TIFF} raw_file_type_t;

static void usage(char *progname)
{
  fprintf(stderr,
          "usage: %s [-jpg] [{-rawraw | -raw [-noscale]}]"
          " <file1> ...\n"
          "   -jpg:     Dump JPG as JPG\n"
          "   -rawraw:  Dump RAW as RAW\n"
          "   -raw:     Dump RAW as TIFF (scaled and gamma 2.2)\n"
          "   -noscale: Dont scale RAW data\n",
          progname);
  exit(1);
}

int main(int argc, char *argv[])
{
  int extract_jpg = 0;
  int extract_raw = 0;
  double gamma = 2.2;
  raw_file_type_t file_type = NONE;
  int files = 0;

  int i;

  for (i=1; i<argc; i++)
    if (!strcmp(argv[i], "-jpg"))
      extract_jpg = 1;
    else if (!strcmp(argv[i], "-rawraw"))
      extract_raw = 1, file_type = RAW;
    else if (!strcmp(argv[i], "-raw"))
      extract_raw = 1, file_type = TIFF;
    else if (!strcmp(argv[i], "-noscale"))
      gamma = -1.0;
    else if (!strncmp(argv[i], "-", 1))
      usage(argv[0]);

  for (i=1; i<argc; i++)
    if (strncmp(argv[i], "-", 1)) {
      char *infilename = argv[i];
      FILE *f_in = fopen(infilename, "rb");
      x3f_t *x3f = NULL;

      files++;

      if (f_in == NULL) {
        fprintf(stderr, "Could not open infile %s\n", infilename);
        return 1;
      }

      printf("READ THE X3F FILE %s\n", infilename);
      x3f = x3f_new_from_file(f_in);

      if (extract_jpg) {
        char outfilename[1024];

        x3f_load_data(x3f, x3f_get_thumb_jpeg(x3f));

        strcpy(outfilename, infilename);
        strcat(outfilename, ".jpg");

        printf("Dump JPEG to %s\n", outfilename);
        x3f_dump_jpeg(x3f, outfilename);
      }

      if (extract_raw) {
        char outfilename[1024];

        strcpy(outfilename, infilename);

        switch (file_type) {
        case NONE:
          break;
        case RAW:
          printf("Load RAW block from %s\n", infilename);
          x3f_load_image_block(x3f, x3f_get_raw(x3f));
          strcat(outfilename, ".raw");
          printf("Dump RAW block to %s\n", outfilename);
          x3f_dump_raw_data(x3f, outfilename);
          break;
        case TIFF:
          printf("Load RAW from %s\n", infilename);
          x3f_load_data(x3f, x3f_get_raw(x3f));
          strcat(outfilename, ".tif");
          printf("Dump RAW as TIFF to %s\n", outfilename);
          x3f_dump_tiff_data_from_SDX(x3f, outfilename, gamma);
          break;
        }
      }

      x3f_delete(x3f);

      fclose(f_in);
    }

  if (files == 0)
    usage(argv[0]);

  return 0;
}
