//  ARYAL6.C
//  6-dimensional array functions
//  Last mod.: 2001-07-13

#include "arraysi.h"
#include "arrays.h"

/*  This returns a pointer <a> which is used as a 6-dimensional array.
 *  The elements of the array can be accessed as a[i][j][k][l][m][n].
 *  The return value should be typecast using the A6 macro.
 *  If init_val != NULL then the array is initialized using
 *  the <size> bytes at location <init_val>, otherwise it is
 *  initialized with null bytes.
 */
/*----------------------------------------*/
void ******lib_array6_alloc(unsigned int n1,       
                            unsigned int n2,       
                            unsigned int n3,       
                            unsigned int n4,
                            unsigned int n5,
                            unsigned int n6,
                            unsigned int size,     //  size of element
                            void *init_val,        //  initialization value
                            int *err_flag)
{
unsigned int i, j, k, l, m;
unsigned int row_size = n6*size;
unsigned int num_bytes = n1*n2*n3*n4*n5*row_size;
void ******a;
char *data_space;

*err_flag = ARRAYS_NO_ERROR;

//  Argument error checking done in ARYAL.C.

//  First allocate (and possibly initialize) the data space.
if ( init_val == NULL )  
    data_space = mem_alloc_ch(num_bytes,0,err_flag);
else        /*  allocate memory for data space  */
    {
    data_space = mem_alloc(num_bytes,err_flag);
    if ( !*err_flag )           /*  if no error  */
        lib_initialize_array(data_space,n1*n2*n3*n4*n5,size,init_val);
    }

if ( !*err_flag )
    {
    //  Set up a 6-dimensional array of pointers to the rows.
    a = (void ******)lib_array5_alloc(n1,n2,n3,n4,n5,sizeof(void *),NULL,err_flag);
    if ( *err_flag )        /*  if error  */
        free(data_space);
    else                    /*  if no error  */
        {
        //  Set up pointers into the data space.
        for ( i=0; i<n1; i++ )
            {
            for ( j=0; j<n2; j++ )
                {
                for ( k=0; k<n3; k++ )
                    {
                    for ( l=0; l<n4; l++ )
                        {
                        for ( m=0; m<n5; m++ )
                            {
                            a[i][j][k][l][m] = data_space;
                            data_space += row_size;
                            }
                        }
                    }
                }
            }
        }
    }

if ( *err_flag )
    a = NULL;

return ( a );
}

//  Free a 6-dimensional array previously allocated.
/*-----------------------------*/
int lib_array6_free(void ******a)
{
void *data_space;
int result = false;

if ( a != NULL )
    {
    data_space = a[0][0][0][0][0];
    lib_array5_free((void *****)a);
    if ( data_space != NULL )
        {
        free(data_space);
        result = true;
        }
    }

return ( result );
}