/*
 * This file is part of libdyn.a, the C Dynamic Object library.  It
 * contains the source code for the function DynInsert().
 * 
 * There are no restrictions on this code; however, if you make any
 * changes, I request that you document them so that I do not get
 * credit or blame for your modifications.
 *
 * Written by Barr3y Jaspan, Student Information Processing Board (SIPB)
 * and MIT-Project Athena, 1989.
 */

#include <stdio.h>
#include "DynObject.H"

int DynObject::Insert(int index, DynPtr els, int num)
{
     int ret;
     
     if (index < 0 || index > num_el) {
	  if (debug)
	       fprintf(stderr, "dyn: insert: index %d is not in [0,%d]\n",
		       index, num_el);
	  return DYN_BADINDEX;
     }

     if (num < 1) {
	  if (debug)
	       fprintf(stderr, "dyn: insert: cannot insert %d elements\n",
		       num);
	  return DYN_BADVALUE;
     }

     if (debug)
	  fprintf(stderr,"dyn: insert: Moving %d bytes from %d + %d to + %d\n",
		  (num_el-index)*el_size, array,
		  el_size*index, el_size*(index+num));

     if ((ret = Resize(num_el + num)) != DYN_OK)
	  return ret;

     bcopy(array + index, array + (index + num), (num_el-index)*el_size);

     if (debug)
	  fprintf(stderr, "dyn: insert: Copying %d bytes from %d to %d + %d\n",
		  el_size*num, els, array, el_size*index);

     bcopy(els, array + el_size*index, el_size*num);

     num_el += num;

     if (debug)
	  fprintf(stderr, "dyn: insert: done.\n");

     return DYN_OK;
}
