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

#include "WImage/RawWriter.hh"
#include "WImage/debug.h"
#include <cstdio>

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

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

  /*
   * Write the header...
   */
  if (m_offset > 0)
    {
      pixel dummy = (pixel)0;
      for (int i = 0; i < m_offset; i++)
        {
          if (fwrite (&dummy, sizeof (pixel), (size_t)1, fhandle) != (size_t)1)
            {
              (void)fclose (fhandle);
              return -1;
            }
        }
    }
  
  /*
   * And the rest...
   */
  for (int line = 0; line < m_pixels->rows (); line++)
    {
      if (fwrite (&m_pixels->array () [line*m_pixels->cols ()], sizeof (pixel),
          (size_t)m_pixels->cols (), fhandle) != (size_t)m_pixels->cols ())
        {
          (void)fclose (fhandle);
          return -1;
        }
    }
  
  return (fclose (fhandle) == EOF)? -1: 0;

} 
