/*
 * Implementation of class PfcReader
 *
 * $Date$
 * $Revision$
 *
 */

#include "WImage/ImageArray.hh"
#include "WImage/PfcReader.hh"
#include "WImage/debug.h"
#include <pfi.h>
#include <cstdio>

#if !(defined __WATCOMC__ && __WATCOMC__ < 1230)
using namespace std;
#endif

int 
PfcReader::readfmt (void)
{
  int xsize = 0;
  int ysize = 0;
  int xysize = 0;
  double *values = NULL;
  int colors;
  int rgbmodel;
  
  if (pfi_properties_name ((char*)m_fname, &ysize, &xsize, 
                           &colors, &rgbmodel) < 0)
    {
      return -2;
    }

  values = NEW (double [ysize * xsize * colors * (int)sizeof (*values)]);

  if (pfi_read_name ((char*)m_fname, ysize, xsize, colors, values) < 0)
    {
      DELETE (values);
      return -2;
    }
  
  if (colors != m_channels)
    {
      return -2;
    }

  switch (rgbmodel)
    {
    case pfi_rgb: 
      m_cmodel = cm_rgb;
      break;
      
    case pfi_yuv:
      m_cmodel = cm_yuv;
      break;

    default:
      return -3;
    }
  
  xysize = xsize * ysize;
  
  for (int i = 0; i < m_channels; i++)
    {
      if (m_images[i]->rows () != ysize || m_images[i]->cols () != xsize)
        {
          m_images[i]->resize (ysize, xsize);
        }
    }
  
  /* import */
  for (int i = 0; i < xysize; i++)
    {
      for (int j = 0; j < m_channels; j++)
        {
          m_images[j]->to (i, (coeff)values[m_channels * i + j]);
        }
    }

  /* cleanup */
  DELETEAR (values);
  
  return 0;
}
