/*
  bitwindow class
  Copyright (C) 2000  Martin Vogt

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU Library General Public License as published by
  the Free Software Foundation.

  For more information look at the file COPYRIGHT in this package

 */


#include "mpegAudioBitWindow.h"




int MpegAudioBitWindow::getbits(int bits) {
  union
  {
    char store[4];
    int current;
  }u;
  int bi;

  if(!bits)return 0;

  u.current=0;
  bi=(bitindex&7);
  u.store[_KEY]=buffer[(bitindex>>3)&(WINDOWSIZE-1)]<<bi;
  //u.store[_KEY]=buffer[bitindex>>3]<<bi;
  bi=8-bi;
  bitindex+=bi;

  while(bits) {
    if(!bi) {
      u.store[_KEY]=buffer[(bitindex>>3)&(WINDOWSIZE-1)];
      //u.store[_KEY]=buffer[bitindex>>3];
      bitindex+=8;
      bi=8;
    }

    if(bits>=bi) {
      u.current<<=bi;
      bits-=bi;
      bi=0;
    }
    else {
      u.current<<=bits;
      bi-=bits;
      bits=0;
    }
  }
  bitindex-=bi;

  return (u.current>>8);
}



void MpegAudioBitWindow::wrap(void) {
  int p=bitindex>>3;
  point&=(WINDOWSIZE-1);

  if(p>=point)
  {
    for(register int i=4;i<point;i++)
      buffer[WINDOWSIZE+i]=buffer[i];
  }
  *((int *)(buffer+WINDOWSIZE))=*((int *)buffer);
}
