int BN_nist_mod_521(BIGNUM *r, const BIGNUM *a, const BIGNUM *field,
	BN_CTX *ctx)
	{
	int	top = a->top, i;
	BN_ULONG *r_d, *a_d = a->d,
		 t_d[BN_NIST_521_TOP],
		 val,tmp,*res;
	size_t	mask;
	static const BIGNUM _bignum_nist_p_521_sqr = {
		(BN_ULONG *)_nist_p_521_sqr,
		sizeof(_nist_p_521_sqr)/sizeof(_nist_p_521_sqr[0]),
		sizeof(_nist_p_521_sqr)/sizeof(_nist_p_521_sqr[0]),
		0,BN_FLG_STATIC_DATA };

	field = &_bignum_nist_p_521; /* just to make sure */

 	if (BN_is_negative(a) || BN_ucmp(a,&_bignum_nist_p_521_sqr)>=0)
		return BN_nnmod(r, a, field, ctx);

	i = BN_ucmp(field, a);
	if (i == 0)
		{
		BN_zero(r);
		return 1;
		}
	else if (i > 0)
		return (r == a)? 1 : (BN_copy(r ,a) != NULL);

	if (r != a)
		{
		if (!bn_wexpand(r,BN_NIST_521_TOP))
			return 0;
		r_d = r->d;
		nist_cp_bn(r_d,a_d, BN_NIST_521_TOP);
		}
	else
		r_d = a_d;

	/* upper 521 bits, copy ... */
	nist_cp_bn_0(t_d,a_d + (BN_NIST_521_TOP-1), top - (BN_NIST_521_TOP-1),BN_NIST_521_TOP);
	/* ... and right shift */
	for (val=t_d[0],i=0; i<BN_NIST_521_TOP-1; i++)
		{
		tmp = val>>BN_NIST_521_RSHIFT;
		val = t_d[i+1];
		t_d[i] = (tmp | val<<BN_NIST_521_LSHIFT) & BN_MASK2;
		}
	t_d[i] = val>>BN_NIST_521_RSHIFT;
	/* lower 521 bits */
	r_d[i] &= BN_NIST_521_TOP_MASK;

	bn_add_words(r_d,r_d,t_d,BN_NIST_521_TOP);
	mask = 0-(size_t)bn_sub_words(t_d,r_d,_nist_p_521,BN_NIST_521_TOP);
	res  = (BN_ULONG *)(((size_t)t_d&~mask) | ((size_t)r_d&mask));
	nist_cp_bn(r_d,res,BN_NIST_521_TOP);
	r->top = BN_NIST_521_TOP;
	bn_correct_top(r);

	return 1;
	}