/* Dynamic array: support stack, queue, etc. */

#define array_init(ptrs,type) \
    ptrs = (type*) malloc((sizeof(type) << 2));\
    ptrs[0] = (type)2;\
    ptrs[1] = (type)4

#define array_begin() 2
#define array_count(ptrs) (int) *ptrs
#define array_max(ptrs) (int) ptrs[1]
#define array_set_count(ptrs,type,c) ptrs[0]=(type)c

#define array_push(ptrs,type,i) { int xx= (int) ptrs[0]; ptrs[xx] =  i; ptrs[0] = (type) (xx+1); }

#define array_insert(ptrs1,type,x)\
  if (array_count(ptrs1) == array_max(ptrs1)) {\
    int i1=array_max(ptrs1);\
    type *ptrs2;\
    ptrs2 = (type*) malloc((i1<<1) * (sizeof(type)));\
    if (ptrs2 == NULL) { fprintf(stderr, "array_insert failed.\n"); exit(1); }\
    ptrs2[0] = (type) (i1);\
    ptrs2[1] = (type) (i1<<1);\
    while (i1-- > 2) ptrs2[i1] = ptrs1[i1];\
    free(ptrs1);\
    ptrs1 = ptrs2;\
  }\
  array_push(ptrs1, type, x)

#define array_insert_unique(ptrs1,type,x)\
  { int x1,x2=0; \
    for (x1=array_count(ptrs1)-1; x1>=array_begin(); x1--) \
       if (ptrs1[x1] == x) { x2=1; break; } \
    if (!x2) { array_insert(ptrs1,type,x); }}
  
