
/** @file  psArray.c
 *
 *  @brief Contains support for basic vector types
 *
 *  This file defines the basic type for a vector struct and functions useful
 *  in manupulating vectors.
 *
 *  @author Ross Harman, MHPCC
 *
 *  @version $Revision: 1.52 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2006-09-15 14:38:25 $
 *
 *  Copyright 2004-2005 Maui High Performance Computing Center, University of Hawaii
 */

/******************************************************************************/

/*  INCLUDE FILES                                                             */

/******************************************************************************/
#include<stdlib.h>                         // for qsort, etc.
#include<string.h>

#include "psMemory.h"
#include "psError.h"
#include "psArray.h"
#include "psLogMsg.h"
#include "psAssert.h"



/*****************************************************************************
  FUNCTION IMPLEMENTATION - LOCAL
 *****************************************************************************/
static void arrayFree(psArray* psArr);

static void arrayFree(psArray* psArr)
{
    psArrayElementsFree(psArr);

    psFree(psArr->data);
}

bool psMemCheckArray(psPtr ptr)
{
    if (!is_psType(ptr)) {
        return false;
    }
    return ( psMemGetDeallocator(ptr) == (psFreeFunc)arrayFree );
}


/*****************************************************************************
  FUNCTION IMPLEMENTATION - PUBLIC
 *****************************************************************************/
psArray* psArrayAlloc(long nalloc)
{
    if (nalloc < 0) {
        psError(PS_ERR_BAD_PARAMETER_VALUE, true,
                "Can't allocate a psArray of negative size.");
        return NULL;
    }
    psArray* psArr = NULL;

    // Create vector struct
    psArr = (psArray* ) psAlloc(sizeof(psArray));
    psMemSetDeallocator(psArr, (psFreeFunc) arrayFree);

    P_PSARRAY_SET_NALLOC(psArr,nalloc);
    psArr->n = 0;  //set the initial number of elements in use to 0
    // Create vector data array
    psArr->data = psAlloc(nalloc * sizeof(psPtr));
    memset(psArr->data, 0, sizeof(void*) * nalloc);  //set the initial values of data to NULL

    return psArr;
}

psArray* psArrayRealloc(psArray* in,
                        long nalloc)
{
    if (nalloc < 0) {
        psError(PS_ERR_BAD_PARAMETER_VALUE, true,
                "Can't reallocate a psArray to negative size.");
        return in;
    }
    if (in == NULL) {
        psError(PS_ERR_BAD_PARAMETER_NULL,true,
                _("psArrayRealloc must be given a non-NULL psArray to resize."));
        return NULL;
    } else if (in->nalloc != nalloc) {     // No need to realloc to same size
        if (nalloc < in->n) {
            for (psS32 i = nalloc; i < in->n; i++) {      // For reduction in vector size
                psFree(in->data[i]);
            }
            in->n = nalloc;
        }
        // Realloc after decrementation to avoid accessing freed array elements
        long n = in->n;
        in->data = psRealloc(in->data, nalloc * sizeof(psPtr));
        P_PSARRAY_SET_NALLOC(in,nalloc);
        for (long m = n; m < nalloc; m++) { //if array is grown, set grown data to NULL
            in->data[m] = NULL;
        }
    }

    return in;
}

psArray* psArrayAdd(psArray* array,
                    long delta,
                    psPtr data)
{
    if (array == NULL) {
        int d = (delta > 0) ? delta : 10; // as spec'ed in SDRS.
        array = psArrayAlloc(d);
        array->n = 0;
    }

    int n = array->n;

    if (n >= array->nalloc) {
        // array needs to be expanded to make room for more elements
        int d = (delta > 0) ? delta : 10; // as spec'ed in SDRS.
        array = psArrayRealloc(array, n+d);
    }

    // add the element to the end of the array.
    array->data[n] = psMemIncrRefCounter(data);
    array->n = n+1;

    return array;
}

bool psArrayRemove(psArray* array,
                   const psPtr data)
{
    bool success = false;

    if (array == NULL) {
        psError(PS_ERR_BAD_PARAMETER_NULL, true,
                _("Specified psArray can not be NULL."));
        return false;
    }

    psS32 n = array->n;
    psPtr* psArrData = array->data;
    for (psS32 i = n-1; i >= 0; i--) {
        if (psArrData[i] == data) {
            memmove(&array->data[i],&array->data[i+1],(n-i-1)*sizeof(psPtr));
            psFree(data); // free the removed item (see Bug #449)
            n--;
            success = true;
        }
    }
    array->n = n; // reset the array size to indicate the removed item(s)

    return success;
}

bool psArrayRemoveByPos(psArray* array,
                        long position)
{
    PS_ASSERT_PTR_NON_NULL(array, false);

    if (position < 0 || position >= array->n) {
        psError(PS_ERR_BAD_PARAMETER_NULL, true,
                _("position > then the number of elements in the array."));
        return false;
    }

    long i = position;
    long n = array->n;
    psFree(array->data[i]);
    memmove(&array->data[i], &array->data[i + 1], (n - i - 1) * sizeof(psPtr));
    array->n--;    // reset the array size to indicate the removed item

    return true;
}

void psArrayElementsFree(psArray* array)
{
    if (array == NULL) {
        return;
    }

    for (long i = 0; i < array->n; i++) {
        psFree(array->data[i]);
        array->data[i] = NULL;
    }

    array->n = 0;
}

psArray* psArraySort(psArray* array,
                     psComparePtrFunc func)
{
    if (array == NULL) {
        return NULL;
    }

    qsort(array->data, array->n, sizeof(psPtr), (int (*)(const void* , const void*))func);

    return array;
}

// Set an element in the array.
bool psArraySet(psArray* array,                      ///< input array to set element in
                long position,                      ///< the element position to set
                psPtr data)                        ///< the value to set it to
{
    if (array == NULL)
    {
        psError(PS_ERR_BAD_PARAMETER_NULL, true,
                _("Specified psArray can not be NULL."));
        return false;
    }

    if (position > array->n)
    {
        psError(PS_ERR_BAD_PARAMETER_NULL, true,
                "Specified position, %ld, is greater than n+1 of the array, %ld.",
                position, array->n);
        return false;
    }

    if (position < 0)
        position += array->n;
    if (position < 0)
    {
        psError(PS_ERR_BAD_PARAMETER_SIZE, true, "Invalid position.  Negative number too large\n");
        return false;
    }

    if (position == array->n)
    {
        if (position >= array->nalloc) {
            psError(PS_ERR_BAD_PARAMETER_NULL, true,
                    _("Specified position, %ld, is greater than the allocated size of the array, %ld."),
                    position, array->nalloc);
            return false;
        }
        array->n++;
    }
    psFree(array->data[position]);
    array->data[position] = psMemIncrRefCounter(data);

    return true;
}

// Get an element in the array.
psPtr psArrayGet(const psArray* array,
                 long position )
{
    if (array == NULL) {
        psError(PS_ERR_BAD_PARAMETER_NULL, true,
                _("Specified psArray can not be NULL."));
        return NULL;
    }

    if (position >= array->n) {
        psError(PS_ERR_BAD_PARAMETER_NULL, true,
                "Specified position, %ld, is greater than n+1 of the array, %ld.",
                position, array->n);
        return NULL;
    }
    if (position < 0)
        position += array->n;
    if (position < 0) {
        psError(PS_ERR_BAD_PARAMETER_SIZE, true, "Invalid position.  Negative number too large\n");
        return NULL;
    }
    return (array->data[position]);
}

long psArrayLength(const psArray *array)
{
    if ( !psMemCheckArray((psArray*)array) ) {
        psError(PS_ERR_BAD_PARAMETER_TYPE, true,
                "Error:  Specified array is not a valid psArray \n");
        return -1;
    }
    return (array->n);
}

