int X509_NAME_add_entry(X509_NAME *name, X509_NAME_ENTRY *ne, int loc,
	     int set)
	{
	X509_NAME_ENTRY *new_name=NULL;
	int n,i,inc;
	STACK_OF(X509_NAME_ENTRY) *sk;

	if (name == NULL) return(0);
	sk=name->entries;
	n=sk_X509_NAME_ENTRY_num(sk);
	if (loc > n) loc=n;
	else if (loc < 0) loc=n;

	name->modified=1;

	if (set == -1)
		{
		if (loc == 0)
			{
			set=0;
			inc=1;
			}
		else
			{
			set=sk_X509_NAME_ENTRY_value(sk,loc-1)->set;
			inc=0;
			}
		}
	else /* if (set >= 0) */
		{
		if (loc >= n)
			{
			if (loc != 0)
				set=sk_X509_NAME_ENTRY_value(sk,loc-1)->set+1;
			else
				set=0;
			}
		else
			set=sk_X509_NAME_ENTRY_value(sk,loc)->set;
		inc=(set == 0)?1:0;
		}

	if ((new_name=X509_NAME_ENTRY_dup(ne)) == NULL)
		goto err;
	new_name->set=set;
	if (!sk_X509_NAME_ENTRY_insert(sk,new_name,loc))
		{
		X509err(X509_F_X509_NAME_ADD_ENTRY,ERR_R_MALLOC_FAILURE);
		goto err;
		}
	if (inc)
		{
		n=sk_X509_NAME_ENTRY_num(sk);
		for (i=loc+1; i<n; i++)
			sk_X509_NAME_ENTRY_value(sk,i-1)->set+=1;
		}	
	return(1);
err:
	if (new_name != NULL)
		X509_NAME_ENTRY_free(new_name);
	return(0);
	}