#include <amscimglib4/amscimglib4.h>
#include <amscimglib4/amscimglib4_intl.h>

#ifdef __cplusplus
extern "C" {  
#endif

//returns the size of a file using ANSI C
unsigned int amscimglib4_filesize(FILE *fp)
{
  unsigned int ret = 0;
  fseek(fp,0L,SEEK_END);
  ret = ftell(fp); //find the size of the file
  fseek(fp,0L,SEEK_SET);
  return ret;
}

AMSCIMGLIB4_API int amscimglib4_magic_type(const char *fname)
{
  FILE *fp = NULL;
  int ret = amscimglib4_type_unknown; //unidentified type
  unsigned char magicbuff[8];

  fp = fopen(fname,"rb");
  if(fp==NULL)
  {
    printf("amscimglib4magic_type: %s could not be opened!\n",fname);
  }
  else
  {
    fseek(fp,0L,SEEK_SET);
    fread(magicbuff,8,1,fp);
    fseek(fp,0L,SEEK_SET);

    //is this file one of PNG, BMP, or JPEG?

    if(magicbuff[0] == 'B' && magicbuff[1] == 'M')
    {
      ret = amscimglib4_type_bmp; //BMP
    }

    if(magicbuff[0] == 0x89 &&
    magicbuff[1] == 0x50 &&
    magicbuff[2] == 0x4E &&
    magicbuff[3] == 0x47 &&
    magicbuff[4] == 0x0D &&
    magicbuff[5] == 0x0A &&
    magicbuff[6] == 0x1A &&
    magicbuff[7] == 0x0A
    )
    {
      ret = amscimglib4_type_png; //PNG
    }

    if(magicbuff[0] == 0xFF &&
    magicbuff[1] == 0xD8 &&
    magicbuff[2] == 0xFF &&
    (magicbuff[3]==0xDB || magicbuff[3]==0xE0 || magicbuff[3]==0xE1)
    )
    {
      ret = amscimglib4_type_jpg; //JPG
    }

    fclose(fp);
  }

  return ret;
}



#ifdef __cplusplus
}; //end extern "C"
#endif