/******************************************************************************

   This file is a part of the

             COMPLEX PSEUDO-RAW SAR IMAGE PROCESSING TOOLBOX

   Copyright (C) 2017 Rémy Abergel (Remy.Abergel AT parisdescartes.fr), Loïc
   Denis (Loic.Denis AT univ-st-etienne.fr), Saïd Ladjal (Said.Ladjal AT
   telecom-paristech.fr) and Florence Tupin (Florence.Tupin AT
   telecom-paristech.fr).

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

******************************************************************************/

/*
   Compilation (using gcc):
   ========================

   gcc -O3 tiffprintasc.c tiffread.c -ltiff -o tiffprintasc


   Ddescription:
   =============

   Print the graylevels of a TIFF image in the standard output

*/

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

#define FREE_ALL() {				\
    if(NULL != u) free(u);			\
  }
#define ASSERT_ALLOC(cmd) if(NULL == (cmd)) { printf("Not enough memory\n"); FREE_ALL(); exit(EXIT_FAILURE); }

static void display_usage()
{
  printf("\nPrint the graylevels of a TIFF image (row major order) in ascii format.\n\n");
  printf("Usage: tiffprintasc [-s s] in\n\n");
  printf("   -s s      : only print graylevels of slice with index s\n");
  printf("   in        : intput TIFF image\n\n");
}


int main(int argc, char **argv)
{
  char *filename_in = NULL,*svalue = NULL;
  int s,i,adr,nx,ny,npages=0,err;
  TIFF *tiffp;
  double *u;

  /******************************************/
  /*            arguments parser            */
  /******************************************/

  /* main parser */
  for(i=1;i<argc;i++) {
    if (strcmp(argv[i],"-s") == 0) {
      if(i==argc-1) { display_usage(); printf("Error: option -s requires an argument\n\n"); return EXIT_FAILURE; }
      else {
	svalue = argv[i+1]; err = sscanf(svalue,"%d",&s); i++;
	if(err != 1) { display_usage(); printf("Error: could not retrieve properly the argument of option -s\n\n"); return EXIT_FAILURE; }
      }
    }
    else if (NULL == filename_in) filename_in = argv[i];
    else { display_usage(); printf("Error: could not retrieve properly input arguments.\n\n"); return EXIT_FAILURE; }
  }

  /* check consistency */
  if (NULL == filename_in) {
    display_usage();
    printf("Error: input 'in' is missing\n\n");
    return EXIT_FAILURE;
  }


  /**********************************************************/
  /* count number of pages (directories) in the input image */
  /**********************************************************/
  TIFFSetWarningHandler(NULL);
  tiffp = TIFFOpen(filename_in,"r");
  if (!tiffp) {
    printf("Failed to open TIFF File '%s'\n",filename_in);
    return EXIT_FAILURE;
  }
  do ++npages; while (TIFFReadDirectory(tiffp));
  TIFFClose(tiffp);
  if(svalue && s >= npages) { printf("Incoherent slice index s=%d (only %d pages detected in '%s')\n",s,npages,filename_in); return EXIT_FAILURE; }


  /************************************************************/
  /* Open TIFF Image & get its graylevels in double precision */
  /************************************************************/
  if(svalue) npages = s+1;
  for(i=(svalue)?s:0;i<npages;i++) {
    if(EXIT_FAILURE == load_monopage_tiff_into_double(&u,&nx,&ny,filename_in,0,i)) {
      printf("An error occured during the image reading process.\n");
      printf("Free memory and exit the program.\n\n");
      FREE_ALL();
      return EXIT_FAILURE;
    }
    for(adr=0;adr<nx*ny;adr++) printf("%.17g\n",u[adr]);
  }

  /* free memory */
  FREE_ALL();

}
