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

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

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


extern "C" {
#include "avilib.h"
}

int 
AviWriter::writefmt (void)
{
#if 0
  // Currently not supported due to restrictions in avilib 
  FILE *fhandle = NULL;
  
  if (m_fname == NULL)
    {
      fhandle = stdout;
    }
  else 
    {
      /*
       * Never fails since checked before.
       */
      fhandle = fopen (m_fname, "wb");
    }
#endif
  int rc = 0;
  pixel *oneFrame = NULL;
  avi_t *avi = AVI_open_output_file ((char*)m_fname);
  if (avi == NULL)
    {
      return -2;
    }
  int ysize = m_arrays[0]->rows ();
  int xsize = m_arrays[0]->cols ();
  int xysize = m_arrays[0]->size ();
  int frames = m_arrays[0]->frames ();
  AVI_set_video(avi, xsize, ysize, m_frameRate, (char*)"");
  oneFrame = NEW (pixel [m_channels * xysize]);
  /* 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++)
            {
              oneFrame[m_channels * i + c] = 
                tools_coeff2pixel (m_arrays[c]->at (i));
            }
        }
      if (AVI_write_frame (avi, (char*)oneFrame, 
                           xysize * m_channels * sizeof (*oneFrame), 0) < 0)
        {
          rc = -2;
          goto finish;
        }
    }

 finish:
  if (oneFrame != NULL)
    {
      DELETEAR (oneFrame);
    }
  AVI_close (avi);
  return rc;
}
