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

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

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

VidReader::VidReader (char const *name, VideoArray < coeff > *arrays[], 
                      int rawy, int rawx, int colors, int from, int to, 
                      int skip)
  : VideoReader (name, arrays, colors, from, to) 
{ 
    m_ysize = rawy;
    m_xsize = rawx;
    m_skip = skip;
    
    if (m_to - m_from <= 0)
      { 
        m_frames = framesInFile (name, rawy, rawx, colors, skip);
        m_to = m_frames;
        m_frames -= m_from;
      }
}

int 
VidReader::framesInFile (const char *fname, int rows, int cols, 
                         int colors, int skip)
{
  return (tools_fileSize (fname) - skip) / (rows * cols * colors);
}


int 
VidReader::readfmt (void)
{
  FILE *fhandle = NULL;
  
  int xysize = m_ysize * m_xsize;
  int rc = 0;

  if (m_fname == NULL)
    {
      fhandle = stdin;
    }
  else 
    {
      /*
       * Never fails since checked before.
       */
      fhandle = fopen (m_fname, "rb");
    }
  
  /* import */
  pixel *onepixel = NEW (pixel [m_channels]);
  int offset = m_skip + (m_from * m_channels * m_ysize * m_xsize);
  
  if (fseek (fhandle, offset, SEEK_SET) < 0)
    {
      rc = -2;
      goto finish;
    }

  for (int frame = 0; frame < m_frames; frame++)
    {
      for (int c = 0; c < m_channels; c++)
        {
          m_arrays[c]->current (frame);
        }
      for (int i = 0; i < xysize; i++)
        {
          if (fread (onepixel, sizeof (pixel), m_channels, fhandle) 
              != (size_t)m_channels)
            {
              rc = -2;
              goto finish;
            }
          for (int c = 0; c < m_channels; c++)
            {
              m_arrays[c]->to (i, (coeff)onepixel[c]);
            }
        }
    }

 finish:
  DELETE (onepixel);

  if (fclose (fhandle) == EOF)
    {
      return -1;
    }
  return rc;
}
  
