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

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

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

int 
VidWriter::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_arrays[0]->size ();
  int frames = m_arrays[0]->frames ();
  
  pixel *onepixel = NEW (pixel [m_channels]);
  for (int c = 0; c < m_channels; c++)
    {
      onepixel[c] = 0;
    }

  for (int i = 0; i < m_skip; i++)
    {
      if (fwrite (onepixel, sizeof (pixel), (size_t)1, fhandle) != (size_t)1)
        {
          (void)fclose (fhandle);
          return -1;
        }
    }
  
  /* import */
  for (int frame = 0; frame < frames; frame++)
    {
      for (int c = 0; c < m_channels; c++)
        {
          m_arrays[c]->current (frame);
        }
      for (int i = 0; i < xysize; i++)
        {
          for (int c = 0; c < m_channels; c++)
            {
              onepixel[c] = tools_coeff2pixel (m_arrays[c]->at (i));
              if (fwrite (onepixel, sizeof (pixel), (size_t)m_channels, 
                          fhandle) != (size_t)m_channels)
                {
                  (void)fclose (fhandle);
                  return -1;
                }
            }
        }
    }

  fclose (fhandle);

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