/***
 *  PROJECT     :  Generation of Anatomical Models for Surgical Simulators (GAMSS)
 *  AUTHOR      :  Raimundo Sierra
 *  CONTACT     :  http://www.rsierra.com/?main=contact
 *  CREATED     :  21.03.2002
 *  CHANGED     :  
 *  DESCRIPTION :  Read arbitrary image files, docu see .h file 
 */
#include "readImages.h"

template<class T> T* readColorImage(const char * file, int &rows, int &columns, T *array,
                                    const float gamma=-1.0)
{
  try { 
    // Create an image object and read an image
    Image image( file );
    if(gamma>0) image.gamma(gamma); 
    cout << "Resolution of image:     "<< image.rows() << "x"<< image.columns() << endl;
    rows    = image.rows();
    columns = image.columns();
    array   = new T[rows*columns*3];           // allocate memory for image
    ColorRGB color;
    int position = 0;
    for(int j=0; j<rows; j++){
      for(int i=0; i<columns; i++){
        color = image.pixelColor(i,j);         // get pixel color at position i,j
        position = 3*(i+(rows-j-1)*columns);   // flip image horizontaly for OpenGL
        array[position    ] = T(color.red());
        array[position + 1] = T(color.green());
        array[position + 2] = T(color.blue());
      }
    }
    // imageMagick takes care of deleting the image
  }
  catch( Exception &error_ ){ 
    cout << "Caught exception: " << error_.what() << endl;
    rows    = 0;
    columns = 0;
    array   = NULL;
  }
  
  return array;
}

template<class T> T* readGreyImage(const char * file, int &rows, int &columns, T *array,
                                   const float gamma=-1.0)
{
  try { 
    Image image( file );
    if(gamma>0) image.gamma(gamma); 
    cout << "Resolution of image:     "<< image.rows() << "x"<< image.columns() << endl;
    rows    = image.rows();
    columns = image.columns();
    array   = new T[rows*columns];
    ColorGray gray;
    for(int j=0; j<rows; j++){
      for(int i=0; i<columns; i++){
        gray = image.pixelColor(i,j);
        array[i+(rows-j-1)*columns] = T(gray.shade());
      }
    }
  }
  catch( Exception &error_ ){ 
    cout << "Caught exception: " << error_.what() << endl;
    rows    = 0;
    columns = 0;
    array   = NULL;
  }
  
  return array;
}


void dummyReadImages()
{
  float  * fvector = new float[1];
  double * dvector = new double[1];
  //int    * ivector = new int[1];
  //short  * svector = new short[1];
  char   * file    = new char[1];
  int    i         = 0;
  
  readColorImage(file, i, i, fvector);
  readColorImage(file, i, i, dvector);

  readGreyImage(file, i, i, fvector);
  readGreyImage(file, i, i, dvector);
  
  delete[] file;
  delete[] fvector;
  delete[] dvector;
  //delete[] ivector;
  //delete[] svector;
}


