// file: $USFS/class/image_eval/v1.0/imgev_qsort_1.cc
//

// system include files
//

// isip include files
//
#include "image_eval.h"
#include <integral_constants.h>

// method: qsort_cc
//
// arguments:
//  int_4* index_a: (output) buffer containing index array
//  char_1** values_a: (input) buffer containing the data to be sorted
//  int_4 num_items_a: (input) number of items in data buffer
//
// return:
//  logical_1 to indicate status
//
// This methods sorts the given buffer by returning an index array
// that will be used to index into the original array to get the
// sorted data.
//
//
logical_1 Image_eval::qsort_cc(int_4* index_a, char_1** values_a,
			       int_4 num_items_a) {

  // copy the data into a temporary space
  // can't do a memcpy here because space is not contiguous
  //
  char_1 *temp[num_items_a];
  for (int_4 i = 0; i < num_items_a; i ++) {
    temp[i] = new char_1[strlen((char*)values_a[i]) + 1];
    strcpy((char*)temp[i], (char*)values_a[i]);
  }
  
  // sort the temp array
  //
  qsort((char**)temp, (int)num_items_a, sizeof(char_1*),
	Image_eval::compare_str_cc);

  // compute an index array using a replacement algorithm
  //
  for (int_4 i = 0; i < num_items_a; i++) {
    for (int_4 j = 0; j < num_items_a; j++) {
      if (strcmp((char*)temp[i], (char*)values_a[j]) == 0) {
	index_a[i] = j;
	delete [] temp[i];
	temp[i] = (char_1*)NULL;
	break;
      }
    }
  }

  // print debug data
  //
  if (debug_level_d > ISIP_DEBUG_DETAILED) {
    fprintf(stdout, "\nSorted data\n"); 
    for (int_4 i=0; i<num_items_a; i++) {
      fprintf(stdout, "pos: %ld value: %s\n", index_a[i],
	      values_a[index_a[i]]);
    }
  }
  
  // cleanup temp variables
  //
  for (int_4 i = 0; i < num_items_a; i++) {
    delete [] temp[i];
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;

}
