// file: $USFS/class/image_analysis/v3.0/imaga_rle_09.cc
//

// isip include files
//
#include "image_analysis.h"

#include "image_analysis_constants.h"
#include <integral_constants.h>

// method: rle_bitblu_cc
//
// arguments: none
//
// return: a logical_1 value indicating status
//
// this method computes the category and assigns the number of bits
//
logical_1 Image_analysis::rle_bitblu_cc() {

  // category and offset for coefficient
  //
  int_4 cat_l = 0;
  int_4 offset_l = 0;
  
  // get category for DC difference error
  //
  rle_category_cc(rle_r_blu_d[0] - rle_r_bpdc_d, cat_l, offset_l);
  rle_r_bpdc_d = rle_r_blu_d[0];

  // add the number of bits required
  //
  rle_r_blubits_d += rle_dc_codes_d[(int_4)fabs(cat_l)] + (int_4)fabs(cat_l);

  // now output the AC values one by one after counting the zero run lengths
  //
  int_4 zrl = 0;
  logical_1 end_blk_l = ISIP_FALSE;
  int_4 l = 1;
  while (l < IMAGA_RLE_BLK_SIZE * IMAGA_RLE_BLK_SIZE) {
    
    zrl = 0;
    end_blk_l = ISIP_FALSE;

    // count zero run lengths
    //
    while (rle_r_blu_d[l] == 0) {
      zrl++;
      l++;

      // if block size is reached
      //
      if ((l == IMAGA_RLE_BLK_SIZE * IMAGA_RLE_BLK_SIZE)) {
	end_blk_l = ISIP_TRUE;
	break;
      }
    }
    
    // check if end of block is reached
    //
    if (end_blk_l == ISIP_TRUE) {
      rle_r_blubits_d += 4;
      break;
    }

    // otherwise find the appropriate category and code length
    //
    else {

      // if zero runlength is larger than buffer break it up
      //
      while (zrl >= IMAGA_NUM_ZEROLENGTHS) {
	cat_l = 0;
	offset_l = 0;
	zrl -= IMAGA_NUM_ZEROLENGTHS;
	rle_r_blubits_d += 11;
      }
      
      // encode the next pixel value
      //
      rle_category_cc(rle_r_blu_d[l], cat_l, offset_l);
      rle_r_blubits_d += ((int_4)fabs(cat_l) + rle_ac_codes_d[zrl][(int_4)fabs(cat_l) - 1]);
      l++;
    }
  }

  // check if end of block is reached
  //
  if (end_blk_l == ISIP_FALSE) {
    rle_r_blubits_d += 4;
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
