/* ibitstream.cpp
 *
 * CSI 2131
 * Lucia Moura
 */

#include "ibitstream.h"

IBitStream::IBitStream():
            pin (NULL), bits_processed(8)
{
}

IBitStream::IBitStream(istream &in) : 
            pin (&in), bits_processed(8)
{
}

// The destructor doesn't do anything.
IBitStream::~IBitStream() 
{
}

istream *IBitStream::getfile()
{
   return pin;
}

void IBitStream::setfile(istream & newin) 
{
   pin = &newin;
   bits_processed = 8;
}

short int IBitStream::get()
{
   // if nothing new in buffer, read another character into buffer
   if (bits_processed >= 8) {
      buf = pin->get();
      bits_processed = 0;
      if (pin->eof())
         return -1; // no file, no bit
   }
   
   // To find out what the most significant bit
   // of buf is, we shift buf right by 7, knocking
   // off all the bits and leaving only the most
   // significant bit in the first position.
   // For example, 10010100 >> 7 = 00000001, which == 1.
   // Thus, we know the MSB of 10010100 is 1.  


   short int bit = buf >> 7;

   // Shift all the bits left
   buf = buf << 1;

   // increment the number of bits processed in this buffer
   bits_processed++;

   return (bit); // return the bit found
}

bool IBitStream::eof()
{
   if (!pin)
      return true;
   return pin->eof();
}

