#include "ArgPack.h"
#include "useful.h"
#include "memory.h"
#include "assert.h"

/*--------------*/
ArgPack ArgPack_create()  /* use this tyo get the ArgPack that you */
{                              /*  pass to the other functions */
  ArgPack w;
  w=(struct ArgPack_str *)Memory_allocate(sizeof(struct ArgPack_str));
  w->Count=0;
  w->args=NULL;
  return(w);
}
/*----------*/
void ArgPack_add_arg(AP,resource,value)
ArgPack AP;
char *resource;
XtArgVal value;    /* here is a problem for machines with ints < 32 bits */
{
  int Count;
  Count=AP->Count;
  if (AP->args==NULL)
    AP->args=(Arg *)Memory_allocate((Count+1)*sizeof(Arg));
  else
    AP->args=(Arg *)Memory_reallocate((char *)AP->args,(Count+1)*sizeof(Arg));
  XtSetArg(AP->args[Count],resource,value);
  AP->Count++;
};
/*----------------*/
int ArgPack_num_args(AP)
ArgPack AP;
{
  return(AP->Count);
}
/*-----------------*/
Arg *ArgPack_the_args(AP)
ArgPack AP;
{
  return(AP->args);
}
/*---------------*/
void ArgPack_delete(AP)
ArgPack AP;
{
  if (AP->args!=NULL)
    Memory_free((char *)AP->args);
  Memory_free((char *)AP);
}
    
/*-------------------------------------------*/
ArgPack ArgPack_duplicate_args(al)
Arg *al;
{
  ArgPack dal;
  int Size, i;

  dal=ArgPack_create();
  Size=0;
  while (al[Size].name!=NULL)  Size++;
  if (Size!=0)
    dal->args=(Arg *)Memory_allocate(Size*sizeof(Arg));
  else
    dal->args=NULL;
  dal->Count=Size;
  for (i=0;i<Size;i++)  {
    dal->args[i].name=al[i].name;
    dal->args[i].value=al[i].value;
  }
  return(dal);
} 

/*-------------------------------------------*/
ArgPack ArgPack_append_args(dal,al)
ArgPack dal;
Arg *al;
{
  int Size, i,Count;

  Size=0;
  while (al[Size].name!=NULL)  Size++;
  dal->args=(Arg *)Memory_allocate(Size*sizeof(Arg));
  Count=dal->Count;
  dal->Count=Count+Size;
  for (i=Count;i<(Size+Count);i++)  {
    dal->args[i].name=al[i].name;
    dal->args[i].value=al[i].value;
  }
  return(dal);
} 

/*-------------------------------------------*/
ArgPack ArgPack_copy_and_append(dest,source)
ArgPack dest,source;
{
  int S,D,i;

  assert(dest);
  if (source!=NULL) {
    S=source->Count;
    D=dest->Count;
    if (S!=0) {
      if (dest->args==NULL) {
	dest->args=(Arg *)Memory_allocate(S*sizeof(Arg));
	dest->Count=S;
      }
      else {
	dest->args=(Arg *)Memory_reallocate(dest->args,(S+D)*sizeof(Arg));
	dest->Count=S+D;
      }
      for (i=D;i<(S+D);i++)  {
	dest->args[i].name=source->args[i].name;
	dest->args[i].value=source->args[i].value;
      }
    }
  }
  return(dest);
} 
