/*
    Module : ImageSize

    Purpose: Routines to 'size' JPEGs.

    Version: 0.05

    Date   : 5th June 2008

    Started: 25th May 2006

    Author : Rick Murray
             http://www.heyrick.co.uk/eurovision/

*/

#include "euroscore.h"


struct imgsizedef size;


#define readhalfword(fp) ( (fgetc(fp) << 8) + fgetc(fp) )


struct imgsizedef *imagesize_getimagesize(char *path)
{
   /* Converts an HTML path into a DOS path, then tries to reference the image
      to determine its size. If this is not possible, returns a default size. */

   int  recurse = 0;
   FILE *fileptr = NULL;
   unsigned int data = 0;
   unsigned int segtype = 0;
   unsigned int seglen = 0;

   // Set defaults, as for 2008; all exits return this UNLESS values updated.
   size.width = 502;  // 2004: 360x254 (4:3)   2005: 360x214 (14:9)
   size.height = 282; // 2006: 360x212 (14:9)  2007: 384x212 (16:9)

   // dead simple conversion!
   for (recurse = 0; recurse < strlen(path); recurse++)
      if (path[recurse] == '/')
         path[recurse] = '\\';

   // try to open it
   fileptr = fopen(path, "rb");
   if (fileptr == NULL)
   {
      // revert to defaults
      return &size;
   }

   // Check it is a JPEG!
   data = readhalfword(fileptr);
   if (data != 0xFFD8)
   {
      // Doesn't have correct JPEG marker - revert to defaults!
      fclose(fileptr);
      return &size;
   }

   while ( !feof(fileptr) )
   {
      // read a segment
      segtype = readhalfword(fileptr);

      switch (segtype)
      {
         case 0xFFC0 : // BASELINE JPEG
                       // (intentional fall through)
         case 0xFFC2 : // PROGRESSIVE JPEG
                       data = readhalfword(fileptr);
                       data = fgetc(fileptr);
                       size.height = readhalfword(fileptr); // height is FIRST
                       size.width = readhalfword(fileptr);
                       fclose(fileptr);
                       //printf("JPEG \"%s\" sized at %d, %d.\n", path, size.width, size.height);
                       return &size;

         case 0xFFE1 : // EXIF marker
                       printf("Encountered EXIF style JPEG - these are not supported...\n");
                       printf("   [%s]\n", path);
                       fclose(fileptr);
                       return &size;

         case 0xFFD9 : // EOI!!!
                       fclose(fileptr);
                       return &size;
      }

      // Still here? Skip this block!
      seglen = readhalfword(fileptr);
      seglen -= 2;
      for (recurse = 0; recurse < seglen; recurse++)
         data = fgetc(fileptr);
   }

   // Shouldn't fall to here. If we do, exit with defaults.
   fclose(fileptr);
   return &size;
}