#include <boost/format.hpp>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include "FreeImage.h"

int main(int argc, char** argv)
{
  if (argc != 2)
    {
      std::cerr << "Usage: " << argv[0] << " FILE" << std::endl;
      return EXIT_FAILURE;
    }
  else
    {
      FreeImage_Initialise();

      FIBITMAP* img = FreeImage_Load(FIF_PNG, argv[1]);
      if (img)
        {
          { // Convert to 24bit
            FIBITMAP* img24 = FreeImage_ConvertTo32Bits(img);
            FreeImage_Unload(img);
            img = img24;
          }

          assert(FreeImage_GetImageType(img) == FIT_BITMAP);
          assert(FreeImage_GetBPP(img) == 32);

          int width  = FreeImage_GetWidth(img);
          int height = FreeImage_GetHeight(img);
          int pitch  = FreeImage_GetPitch(img);
           
          std::cout << "Dimension: " << width << "x" << height << "  (" << pitch << " pitch)" << std::endl;
          std::cout << "BPP:       " << FreeImage_GetBPP(img) << std::endl;

          std::ofstream out("out.ppm");
          out << "P6" << std::endl;
          out << "# Test PPM from " << argv[1] << std::endl;
          out << width << " " << height << std::endl;
          out << "255" << std::endl;

          uint8_t* bytes = FreeImage_GetBits(img);
          for(int y = height-1; y >= 0; --y)
            {
              for(int x = 0; x < width; ++x)
                {
                  out.put(bytes[y*pitch + 4*x + FI_RGBA_RED]);
                  out.put(bytes[y*pitch + 4*x + FI_RGBA_GREEN]);
                  out.put(bytes[y*pitch + 4*x + FI_RGBA_BLUE]);
                }
            }
      
          FreeImage_Unload(img);
        }

      FreeImage_DeInitialise();  
      std::cout << "done" << std::endl;
      return 0;
    }
}

/* EOF */

