// file: $USFS/class/image_analysis/v1.0/imaga_rle_08.cc
//

// system include files
//
#include <string.h>

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

// method: rle_zigzag_cc
//
// arguments: none
//
// return: a logical_1 value indicating status
//
// this method scans the DCT coefficients in a zigzag order
//
logical_1 Image_analysis::rle_zigzag_cc() {
  
  // step size in each direction
  //
  int_4 step1 = -1;
  int_4 step2 = 1;

  // temporary array to store reordered values
  //
  float_4* temp_r = new float_4[IMAGA_RLE_BLK_SIZE*IMAGA_RLE_BLK_SIZE];
  float_4* temp_b = new float_4[IMAGA_RLE_BLK_SIZE*IMAGA_RLE_BLK_SIZE];
  float_4* temp_g = new float_4[IMAGA_RLE_BLK_SIZE*IMAGA_RLE_BLK_SIZE];

  memset(temp_r, 0, IMAGA_RLE_BLK_SIZE*IMAGA_RLE_BLK_SIZE*sizeof(float_4));
  memset(temp_b, 0, IMAGA_RLE_BLK_SIZE*IMAGA_RLE_BLK_SIZE*sizeof(float_4));
  memset(temp_g, 0, IMAGA_RLE_BLK_SIZE*IMAGA_RLE_BLK_SIZE*sizeof(float_4));
  
  // index variables
  //
  int_4 i = 0;
  int_4 j = 0;
  int_4 l = 0;
  
  // reorder the pel array in a zigzag fashion and store in temp array
  // need to do this only for the first coef_a positions
  //
  while (l < (IMAGA_RLE_BLK_SIZE*IMAGA_RLE_BLK_SIZE)) {
    
    // if the lower limit is exceeded reset in new direction
    //
    if ((i < 0) && (j < (int_4)IMAGA_RLE_BLK_SIZE)) {
      i = 0;
      step1 *= -1;
      step2 *= -1;
    }
    
    else if ((i < (int_4)IMAGA_RLE_BLK_SIZE) && (j < 0)) {
      j = 0;
      step1 *= -1;
      step2 *= -1;
    }
    
    // if the higher limit is exceeded reset in new direction
    //
    else if (i > (int_4)IMAGA_RLE_BLK_SIZE - 1) {
      i = IMAGA_RLE_BLK_SIZE - 1;
      j += 2;
      step1 *= -1;
      step2 *= -1;
    }
    
    else if (j > (int_4)IMAGA_RLE_BLK_SIZE - 1) {
      j = IMAGA_RLE_BLK_SIZE - 1;
      i += 2;
      step1 *= -1;
      step2 *= -1;
    }
    
    // otherwise rearrange data
    //
    else {
      temp_r[l] = rle_r_red_d[i*IMAGA_RLE_BLK_SIZE + j];
      temp_g[l] = rle_r_grn_d[i*IMAGA_RLE_BLK_SIZE + j];
      temp_b[l] = rle_r_blu_d[i*IMAGA_RLE_BLK_SIZE + j];
      l++;
      i += step1;
      j += step2;
    }
  }

  // copy into the array and delete the memory
  //
  for (int_4 m=0; m < (IMAGA_RLE_BLK_SIZE * IMAGA_RLE_BLK_SIZE); m++) {
    rle_r_red_d[m] = temp_r[m];
    rle_r_grn_d[m] = temp_g[m];
    rle_r_blu_d[m] = temp_b[m];
  }

  delete [] temp_r;
  delete [] temp_g;
  delete [] temp_b;
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
