/**************************************************************************
 *
 * bitio_gen.c -- General supoport routines for bitio
 * Copyright (C) 1994  Neil Sharman and Alistair Moffat
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 **************************************************************************/

#include "sysfuncs.h"
#include "bitio_m_abstract.h"

int fprintf (FILE *, const char *,...);

mg_u_long 
BIO_Unary_Length (mg_u_long val)
{
  register mg_u_long num;
  num = bitio_buffer::unary_length(val);
  //  UNARY_LENGTH (val, num);
  return (num);
}


mg_u_long 
BIO_Binary_Length (mg_u_long val, mg_u_long b)
{
  register mg_u_long num;
  num = bitio_buffer::binary_length (val, b);
  return (num);
}


mg_u_long BIO_Gamma_Length (mg_u_long val) {
  register mg_u_long num;
  num = bitio_buffer::gamma_length(val);
  return (num);
}


mg_u_long 
BIO_Delta_Length (mg_u_long val)
{
  register mg_u_long num;
  num = bitio_buffer::delta_length(val);
  return (num);
}


mg_u_long 
BIO_Elias_Length (mg_u_long val, mg_u_long b, double s)
{
  register mg_u_long num;
  num = bitio_buffer::elias_length(val, b, s);
  return (num);
}

mg_u_long 
BIO_Bblock_Length (mg_u_long val, mg_u_long b)
{
  register mg_u_long num;
  num = bitio_buffer::bblock_length (val, b);
  return (num);
}


int 
BIO_Bblock_Init (int N, int p)
{
  int b;
  b = (int) (0.5 + 0.6931471 * N / p);
  return (b ? b : 1);
}


int 
BIO_Bblock_Init_W (int N, int p)
{
  int logb;
  logb = bitio_buffer::floor_log2 ((N - p) / p);
  return (logb < 0 ? 1 : (1 << logb));
}

int 
BIO_Bblock_Bound_b (int N, int p, int b)
{
  int clogb;
  clogb = bitio_buffer::ceil_log2 (b);
  return (p * (1 + clogb) + (N - p * ((1 << clogb) - b + 1)) / b);
}

int 
BIO_Bblock_Bound (int N, int p)
{
  int b;
  b = BIO_Bblock_Init_W (N, p);
  return (BIO_Bblock_Bound_b (N, p, b));
}

/* adjustment is a hack to overcome inaccuracies in floating point,
   where (int)(ln4/ln2) can equal 1, not 2. */
int 
BIO_Gamma_Bound (int N, int p)
{
  return ((int) (p * (2 * log2 (((double) N * 1.0001) / p) + 1)));
}

int 
floorlog_2 (int b)
{
  int logb;
  logb = bitio_buffer::floor_log2 (b);
  return logb;
}

int 
ceillog_2 (int b)
{
  int logb;
  logb = bitio_buffer::ceil_log2 (b);
  return logb;
}
