#include <stdio.h>
#include <stdlib.h>

void *dynamalloc(int dim, int objsize, void *data, int nels, int lb1, ...)
{
      char *fred, *rslt, *datap;
      int fred_inels = 0;
      int fred_dim_1;
      int ub1=1006; /* get from ap */

      /* if objsize needs to be short/word/double aligned,
         do so here (or at point of call)? */

      fred = (char *)malloc (((ub1) - (lb1) + 1) * objsize);
      rslt = fred -= (lb1*objsize);

      datap = data;
      for (fred_dim_1 = lb1; fred_dim_1 <= ub1; fred_dim_1++) {
         if (fred_inels++ == nels) break;

	 memmove(fred, datap, objsize);
         
          fred += objsize;
         datap += objsize;
      }

      return((void *)rslt);
}

#define ARRAY1(t, name, lb1, ub1, nels) \
        (t *)dynamalloc(1, sizeof(t),name##_data,lb1,ub1,nels)

#define ARRAY2(t, name, lb1, ub1, lb2, ub2, nels) \
        (t **)dynamalloc(2, sizeof(t),name##_data,lb1,ub1,nels)

#define ARRAY3(t, name, lb1, ub1, lb2, ub2, lb3, ub3, nels) \
        (t ***)dynamalloc(3, sizeof(t),name##_data,lb1,ub1,nels)

#define ARRAY4(t, name, lb1, ub1, lb2, ub2, lb3, ub3, lb4, ub4, nels) \
        (t ****)dynamalloc(4, sizeof(t),name##_data,lb1,ub1,nels)

static unsigned char fred_data[] = {1, 2, 2, 2, 3, 4};
static unsigned char *fred;
/* This must be output to an init routine, called at the start of main():
   You cannot call it in main itself in case fred is shadowed by a local
   fred = ARRAY1(unsigned char, fred, i, j, 6);
 */

int main(int argc, char **argv)
{
int i = 1000;
int j = 1006;

unsigned char fred_data[] = {1, 2, 2, 2, 3, 4};
unsigned char *fred = ARRAY1(unsigned char, fred, i, j, 6);

unsigned char jim_data[] = {1, 2, 2, 2, 3, 4};
unsigned char *jim = ARRAY1(unsigned char, jim, i, j, 6);

unsigned char sheila_data[] = {1, 2, 2, 2, 3, 4};
unsigned char **sheila = ARRAY2(unsigned char, sheila, i, j, k, l, 6);

exit(0);
}
