/*
        Frank Lyonnet 1993
*/

#include "Erreur.h"
#include "Bool.h"
#include <stdio.h>
#include "Modes.h"

static int pbm_getc (FILE * file) {
/* Read next char, skipping over any comments */
/* A comment/newline sequence is returned as a newline */
  register int ch;
  
  ch = getc(file);
  if (ch == '#') {
    do {
      ch = getc(file);
    } while (ch != '\n' && ch != EOF);
  }
  return ch;
}


static unsigned int read_pbm_integer (FILE * File) {
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
  register int ch;
  register unsigned int val;
  
  /* Skip any leading whitespace */
  do {
    ch = pbm_getc(File);
    if (ch == EOF)
      erreur_fatal("Premature EOF in PPM file");
  } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
  
  if (ch < '0' || ch > '9')
    erreur_fatal("Bogus data in PPM file");
  
  val = ch - '0';
  while ((ch = pbm_getc(File)) >= '0' && ch <= '9') {
    val *= 10;
    val += ch - '0';
  }
  return val;
}


BOOL is_ppm(char *Filename) {
 FILE *File;
 BOOL Res = FALSE;
 int c;
 unsigned int w, h, maxval;

   File = fopen(Filename, "r");

   if (getc(File) == 'P') {
      c = getc(File); /* save format discriminator for a sec */
      w = read_pbm_integer(File);  /* while we fetch the header info */
      h = read_pbm_integer(File);
      maxval = read_pbm_integer(File);

      if (w > 0 && h > 0 && maxval > 0) /* error check */
         Res=TRUE;
   }

   fclose(File);
   return (Res);
}

void get_ppm_size(char *Filename, int *Width, int *Height) {
 FILE *File;

 int c;
 unsigned int w, h;

   File = fopen(Filename, "r");

   if (getc(File) == 'P') {
      c = getc(File); /* save format discriminator for a sec */
      w = read_pbm_integer(File);  /* while we fetch the header info */
      h = read_pbm_integer(File);
   }

   *Width = w;
   *Height = h;   

   fclose(File);
}

void get_ppm_bpp_and_colorspace(char *Filename, int *Bpp,int * Colorspace) {
 FILE *File;

 int c;

   File = fopen(Filename, "r");

   if (getc(File) == 'P') {
      c = getc(File); /* save format discriminator for a sec */
   }

   switch(c) {
      case '2':
      case '5':
         *Bpp = 8;
         *Colorspace = FYEO_GRAY;
         break;
      case '3':
      case '6':
         *Bpp = 24;
         *Colorspace = FYEO_RGB;
         break;
      default:
         break;
   }

   fclose(File);
}
