int i2d_ASN1_SET(STACK *a, unsigned char **pp, i2d_of_void *i2d, int ex_tag,
		 int ex_class, int is_set)
	{
	int ret=0,r;
	int i;
	unsigned char *p;
        unsigned char *pStart, *pTempMem;
        MYBLOB *rgSetBlob;
        int totSize;

	if (a == NULL) return(0);
	for (i=sk_num(a)-1; i>=0; i--)
		ret+=i2d(sk_value(a,i),NULL);
	r=ASN1_object_size(1,ret,ex_tag);
	if (pp == NULL) return(r);

	p= *pp;
	ASN1_put_object(&p,1,ret,ex_tag,ex_class);

/* Modified by gp@nsj.co.jp */
	/* And then again by Ben */
	/* And again by Steve */

	if(!is_set || (sk_num(a) < 2))
		{
		for (i=0; i<sk_num(a); i++)
                	i2d(sk_value(a,i),&p);

		*pp=p;
		return(r);
		}

        pStart  = p; /* Catch the beg of Setblobs*/
		/* In this array we will store the SET blobs */
		rgSetBlob = (MYBLOB *)OPENSSL_malloc(sk_num(a) * sizeof(MYBLOB));
		if (rgSetBlob == NULL)
			{
			ASN1err(ASN1_F_I2D_ASN1_SET,ERR_R_MALLOC_FAILURE);
			return(0);
			}

        for (i=0; i<sk_num(a); i++)
	        {
                rgSetBlob[i].pbData = p;  /* catch each set encode blob */
                i2d(sk_value(a,i),&p);
                rgSetBlob[i].cbData = p - rgSetBlob[i].pbData; /* Length of this
SetBlob
*/
		}
        *pp=p;
        totSize = p - pStart; /* This is the total size of all set blobs */

 /* Now we have to sort the blobs. I am using a simple algo.
    *Sort ptrs *Copy to temp-mem *Copy from temp-mem to user-mem*/
        qsort( rgSetBlob, sk_num(a), sizeof(MYBLOB), SetBlobCmp);
		if (!(pTempMem = OPENSSL_malloc(totSize)))
			{
			ASN1err(ASN1_F_I2D_ASN1_SET,ERR_R_MALLOC_FAILURE);
			return(0);
			}

/* Copy to temp mem */
        p = pTempMem;
        for(i=0; i<sk_num(a); ++i)
		{
                memcpy(p, rgSetBlob[i].pbData, rgSetBlob[i].cbData);
                p += rgSetBlob[i].cbData;
		}

/* Copy back to user mem*/
        memcpy(pStart, pTempMem, totSize);
        OPENSSL_free(pTempMem);
        OPENSSL_free(rgSetBlob);

        return(r);
        }