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

#include "WImage/PpmWriter.hh"
#include "WImage/debug.h"
#include "WImage/tools.h"
#include "ppmlib.h"
#include <cstdio>

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

int 
PpmWriter::writefmt (void)
{
  int rc = 0;
  FILE *fhandle = NULL;
  
  if (m_fname == NULL)
    {
      fhandle = stdout;
    }
  else 
    {
      /*
       * Never fails since checked before.
       */
      fhandle = fopen (m_fname, "wb");
    }

  int xysize = m_images[0]->size ();
  
  pixel *allpixels = NEW (pixel [m_channels * xysize]);

  /* import */
  for (int i = 0; i < xysize; i++)
    {
      for (int j = 0; j < m_channels; j++)
        {
          allpixels[m_channels * i + j] 
            = tools_coeff2pixel (m_images[j]->at (i));
        }
    }

  /* write */
  rc = ppm_toStream (fhandle, allpixels, m_images[0]->rows (), 
                     m_images[0]->cols (), 255);
  fclose (fhandle);

  /* cleanup */
  DELETEAR (allpixels);
  return rc;
}
