// File:		bits.h
// -----------------------------------------------------------------------
// Author:		Omri Traub, <otraub@eecs.harvard.edu>
// Modified by: Adriana Karagiozova, <karagioz@post.harvard.edu>
// Date:		08/06/01
// Assignment:	Unit 9 Main prigramming exercises>
// Version:		2
//
// Description:
//      Routines for reading and writing bits to a file.
//
// NOTE: 
//      You should not have to modify this file.
// 

#ifndef _BITS_H
#define _BITS_H

#include <iostream>
#include <iomanip>
#include <fstream>


// class node
// ----------
// An encoding of a character consists of the bits and the number of
// bits in the code.  Note that the maximum length of a character
// encoding is 32 bits.
// 
// Note:  You are encouraged to use this class wherever you ned to 
//        store a bit code.
// 
class code {
    public:
        unsigned int bits;
        int length;
        
        code() 
        { 
            bits   = 0;
            length = 0; 
        }
};


// class bit_reader
// ----------------
// A class interface to reading a file one bit at a time.
// 
class bit_reader {
    private:
        // a bit buffer containing up to 8 bits from the file
        unsigned char buffer;

        // number of bits currently in the buffer
        int buf_len;

        // the current file, assumed to be open
        ifstream *in;
    
    public:
        // initializes the reader with an input file handle
        bit_reader(ifstream &_in);

        // reads the next bit from the file into the argument int variable. 
        // returns a bool indicating whether end of file was reached.
        bool get_bit(int &the_bit);
};


// class bit_writer
// ----------------
// A class interface to writing a file one bit at a time
// 
class bit_writer {
    private:
        // a bit buffer containing up to 8 bits to be written to the file
        unsigned char buffer;

        // number of characters currently in the buffer
        int buf_len;

        // the current file, assumed to be open
        ofstream *out;

        // number of bytes written
        int num_bytes;
    
    public:
        // initializes the reader with an output file handle
        bit_writer(ofstream &_out);

        // writes the next code (sequence of bits) to the file
        void write_code(code the_code);

        // writes the next bit to the file
        void put_bit(int the_bit);

        // when the buffer gets full, writes the bits out to the file.
        // NOTE: call this file when you are done writing, or else some bits
        //       may not get written out!
        void flush_bits();

        // returns the number of bytes written to file
        int num_bytes_written() 
        { 
            return num_bytes; 
        }
};


#endif
