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

#ifdef __cplusplus
extern "C" {  
#endif

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

int amscimglib4_readbinfile(const char *fname, unsigned char *bytes, long bufflen, long *bytesread)
{

  FILE *fp = NULL;
  int ret = amscimglib4_success;
  long filesize;
  long I;
  static const long chunklen = 4096;
  long clen;
  long lres;
  long res;

  if(fname==NULL)
  {
    ret = amscimglib4_failure;
    return ret;
  }
  fp = fopen(fname,"rb");


  if(fp==NULL)
  {
    printf("amscimglib4_readbinfile:: could not open %s for reading.\n",fname);
    ret = amscimglib4_failure;
    return ret;
  }

  if(bytes==NULL || bufflen<=0)
  {
    ret = amscimglib4_failure;
    return ret;
  }

  filesize = (long) amscimglib4_filesize(fp);

  I = 0;
  while(I<bufflen && I<filesize)
  {
    //load binary file in chunklen sized reads
    clen = filesize - I; 
    clen = (clen>(bufflen-I)) ? bufflen-I : clen;
    clen = (clen>chunklen) ? chunklen : clen;
    res = fread(&(bytes[I]),sizeof(unsigned char),clen,fp);
    I = I + clen;
  }

  if(bytesread!=NULL) *bytesread = I;

  fclose(fp);

  return ret;
}

int amscimglib4_writebinfile(const char *fname, unsigned char *bytes, long bufflen)
{
  int ret = amscimglib4_success;
  FILE *fp = NULL;

  if(fname==NULL)
  {
    ret = amscimglib4_failure;
    return ret;
  }
  fp = fopen(fname,"w+b");

  if(fp==NULL)
  {
    printf("amscimglib4_writebinfile:: could not open %s for writing.\n",fname);
    ret = amscimglib4_failure;
    return ret;
  }

  fwrite(bytes,sizeof(unsigned char),bufflen,fp);

  fclose(fp);

  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];
  size_t res;

  fp = fopen(fname,"rb");
  if(fp==NULL)
  {
    printf("amscimglib4magic_type: %s could not be opened!\n",fname);
  }
  else
  {
    fseek(fp,0L,SEEK_SET);
    res = 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