//
// Copyright (c) 1997,1998 Colosseum Builders, Inc.
// All rights reserved.
//
// Colosseum Builders, Inc. makes no warranty, expressed or implied
// with regards to this software. It is provided as is.
//
// See the README.TXT file that came with this software for restrictions
// on the use and redistribution of this file or send E-mail to
// info@colosseumbuilders.com
//

//
//  Title:  Image Type Functions
//
//  Author:  John M. Miano miano@colosseumbuilders.com
//
#include <fstream>
#include <cstdlib>

#include "imagetype.h"

#include "jpgdecoder.h"
#include "pngdecoder.h"
#include "bmpdecoder.h"

using namespace std ;

namespace Colosseum
{

//
//  Description:
//
//    This function determines the type of image stored in a stream.
//
//  Parameters:
//    strm:  The image stream
//
//  Return Value:
//    An enumeration that identifies the stream type
//
ImageType GetStreamImageType (const std::string &filename)
{
  ImageType result = UnknownImage ;
  ifstream strm (filename.c_str (), ios::binary) ;
  if (! strm)
    return result ;

  char buffer [10] ;
  strm.read (buffer, sizeof (buffer)) ;
  if (strm.gcount () == sizeof (buffer))
  {
    if (memcmp (buffer, "\211PNG\r\n\032\n", 8) == 0)
    {
      result = PngImage ;
    }
    else if (memcmp (buffer, "\xFF\xD8\xFF\xE0", 4) == 0
             && memcmp (&buffer [6], "JFIF", 4) == 0)
    {
      result = JpegImage ;
    }
    else if (memcmp (buffer, "BM", 2) == 0)
    {
      result = BmpImage ;
    }
  }
  return result ;
}

ImageType ReadImage (const std::string &filename,
                BitmapImage &image,
                PROGRESSFUNCTION function,
                void *data)
{
  ImageType type = GetStreamImageType (filename) ;
  if (type == UnknownImage)
    return type ;

  BmpDecoder bmpdecoder ;
  JpegDecoder jpegdecoder ;
  PngDecoder pngdecoder ;
  BitmapImageDecoder *decoder ;
  switch (type)
  {
  case BmpImage:
    decoder = &bmpdecoder ;
    break ;
  case PngImage:
    decoder = &pngdecoder ;
    break ;
  case JpegImage:
    decoder = &jpegdecoder ;
    break ;
  }

  decoder->setProgressFunction (function, data) ;
  decoder->readImageFile (filename, image) ;
  return type ;
}


} // End Namespace Colosseum
