#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "Gdefns.h"

// uncompressor (Golomb) for sparse file.

// usage: GolombDecode < file.GZ > file.decoded

// (c) David J.C. MacKay
// License: GPL                                  http://www.gnu.org/copyleft/gpl.html

// Originates from:  http://www.inference.phy.cam.ac.uk/mackay/itprnn/code/c/compress/

void      printzeroes( int , int *  ) ;

// prints a string of r zeroes, PRECEDED by "1" if the second flag is set. 
void      printzeroes( int r , int *needtoprint1 ) {
  if ( *needtoprint1 ) {
    printf("1\n");
    *needtoprint1 = 0 ;
  }
  for ( ; r>0 ; r-- ) {
    printf("0\n");
  }
}

int main( int argc , char *argv[] ){
  FILE *fp;
  int r , u , needtoprint1 = 0 ;
  //  unsigned char c ; 
  int c ; 
  fp=stdin;
  r = 0 ; 
  while( (c=getc(fp)) != EOF ) {
    if( c == '1' ) {
      printzeroes(MGolomb, &needtoprint1 );
      r = 0 ;
    }    else if (c=='0') {
      // read in the next m bits as an integer
      r=0;
      for ( u=1 ; ( (u<=mGolomb) && (c=getc(fp)) != EOF ) ; u++ ) {
	if( c == '1' ) {	  r++   ;	}
	if ( u < mGolomb ) { r = r * 2 ; }
      }
      printzeroes(r, &needtoprint1); // Ideally we should print a "1" immediately, but
      // instead we postpone this printing event and make a note that we need to do it later;
      // this is an ugly hack to cope with the "add a virtual trailing 1" behaviour of the encoder.
      // The final "1" does not get printed.
      needtoprint1 = 1;
    } else {
      // carriage returns
    }
  }
  return(0);
}

