/*
        Frank Lyonnet 1993
*/

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

#define JFREAD(file,buf,sizeofbuf)  \
  ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))

#define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len)))


BOOL is_targa(char *Filename)
{
   // rewritten by Rick 2004/03/06; the original function is below...
   // (note that char Scrap[18] gives you Scrap[0] ... Scrap[17], so writing to Scrap[18] as
   //  is done by the original is a bit hairy...)

   FILE *File = NULL;
   BOOL Res = FALSE;
   char Scrap[18];

   File = fopen(Filename, "r");
   if (File == NULL)
      return FALSE;

   if ( !ReadOK(File, Scrap, 18) )
      return FALSE;

   fclose(File);

   Res = (get_filetype(Filename) == FILE_TARGA);

   return (Res);
}



// BOOL is_targa(char *Filename) {
// FILE *File;
// BOOL Res = FALSE;
// char Scrap[18];
//
// File=fopen(Filename,"r");
// if (ReadOK(File, Scrap, 18))
//    Scrap[18]=(Scrap[17])>>6; /* We use Scrap[18] as a temp variable */
//    Res=(get_filetype(Filename)==FILE_TARGA);
// fclose(File);
// return (Res);
//}

void get_targa_size(char *Filename, int *Width, int *Height) {
 FILE *File;
 char targaheader[18];
 short int width, height, maplen;

   File = fopen(Filename, "r");

   #define GET_2B(offset)  ((unsigned int)(targaheader[offset]) + \
                         (((unsigned int)(targaheader[offset+1])) << 8))

   if (!ReadOK(File, targaheader, 18))
      erreur_fatal("Unexpected end of file");

   maplen = GET_2B(5);
   width = GET_2B(12);
   height = GET_2B(14);

   *Width = (int)width;
   *Height = (int)height;

   fclose(File);
}

void get_targa_bpp_and_colorspace(char *Filename, int *Bpp,int *Colorspace)
{
FILE *File;
char targaheader[18];
short int pixel_size , subtype;

   File = fopen(Filename, "r");

   #define GET_2B(offset)  ((unsigned int)(targaheader[offset]) + \
                         (((unsigned int)(targaheader[offset+1])) << 8))
   #define UCH(x)	((int) (x))


   if (!ReadOK(File, targaheader, 18))
      erreur_fatal("Unexpected end of file");

   pixel_size = UCH(targaheader[16]) >> 3;
   subtype = UCH(targaheader[2]);

   if (subtype > 8)
       subtype -= 8;

   switch (subtype)
   {
   case 1:
       *Colorspace = FYEO_COLORMAPED;
       break;
   case 2:
       *Colorspace = FYEO_RGB;
       break;
   case 3:
       *Colorspace = FYEO_GRAY;
       break;
   default:
       break;
   }

   *Bpp = pixel_size*8;

   fclose(File);
}



