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

#include "WImage/ImageArray.hh"
#include "WImage/PpmReader.hh"
#include "WImage/debug.h"
#include "ppmlib.h"
#include <cstdio>

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

int
PpmReader::readfmt (void)
{
  FILE *fhandle = NULL;

  int cmax = 0;
  int xsize = 0;
  int ysize = 0;
  int xysize = 0;

  if (m_fname == NULL)
    {
      fhandle = stdin;
    }
  else
    {
      /*
       * Never fails since checked before.
       */
      fhandle = fopen (m_fname, "rb");
    }

  /* initialization */
  pixel * allpixels = ppm_fromStream (fhandle, &ysize, &xsize, &cmax);
  fclose (fhandle);
  if (allpixels == NULL)
    {
      return -2;
    }
  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)allpixels[m_channels * i + j]);
        }
    }

  /* cleanup */
  DELETEAR (allpixels);

  return 0;
}

