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

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

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

int
RawReader::readfmt (void)
{
  FILE * fhandle = NULL;
  enum { s_size, s_header, s_read, s_done, s_error };
  int state = s_size;

  if (m_fname == NULL)
    {
      fhandle = stdin;
    }
  else 
    {
      /*
       * Never fails since checked before.
       */
      fhandle = fopen (m_fname, "rb");
    }

  while (state < s_done)
    {
      switch (state)
        {
        case s_size:
          m_pixels->resize (m_ysize, m_xsize);
          state = s_header;
          break;

        case s_header:
          /*
           * Read two leading bytes and forget them...
           */
          if (m_offset > 0)
            {
              size_t justread;
              pixel *tmp = NEW (pixel[m_offset]);
              justread = fread (tmp, sizeof (pixel), 
                                (size_t)m_offset, fhandle);
              DELETEAR (tmp);
              if (justread != (size_t)m_offset)
                {
                  state = s_error;
                  break;
                }
            }
          state = s_read;
          break;
          
        case s_read:
          /*
           * Now read row-wise...
           */
          /*
           * may be overwritten in loop!
           */
          state = s_done;
          for (int i = 0; i < m_ysize; i++)
            {
              if (fread (&m_pixels->array () [i*m_xsize], sizeof (pixel),
                         m_xsize, fhandle) != (size_t)m_xsize)
                {
                  state = s_error;
                  break;
                }
            }
          break;

        default: 
          break;
        }
    }
  
  if (fclose (fhandle) == EOF)
    {
      return -1;
    }

  return state == s_error? -2: 0;
}

