int BN_nist_mod_224(BIGNUM *r, const BIGNUM *a, const BIGNUM *field,
	BN_CTX *ctx)
	{
	int	top = a->top, i;
	int	carry;
	BN_ULONG *r_d, *a_d = a->d;
	BN_ULONG t_d[BN_NIST_224_TOP],
	         buf[BN_NIST_224_TOP],
		 c_d[BN_NIST_224_TOP],
		*res;
	size_t   mask;
	union { bn_addsub_f f; size_t p; } u;
	static const BIGNUM _bignum_nist_p_224_sqr = {
		(BN_ULONG *)_nist_p_224_sqr,
		sizeof(_nist_p_224_sqr)/sizeof(_nist_p_224_sqr[0]),
		sizeof(_nist_p_224_sqr)/sizeof(_nist_p_224_sqr[0]),
		0,BN_FLG_STATIC_DATA };


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

 	if (BN_is_negative(a) || BN_ucmp(a,&_bignum_nist_p_224_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_224_TOP))
			return 0;
		r_d = r->d;
		nist_cp_bn(r_d, a_d, BN_NIST_224_TOP);
		}
	else
		r_d = a_d;

#if BN_BITS2==64
	/* copy upper 256 bits of 448 bit number ... */
	nist_cp_bn_0(t_d, a_d + (BN_NIST_224_TOP-1), top - (BN_NIST_224_TOP-1), BN_NIST_224_TOP);
	/* ... and right shift by 32 to obtain upper 224 bits */
	nist_set_224(buf, t_d, 14, 13, 12, 11, 10, 9, 8);
	/* truncate lower part to 224 bits too */
	r_d[BN_NIST_224_TOP-1] &= BN_MASK2l;
#else
	nist_cp_bn_0(buf, a_d + BN_NIST_224_TOP, top - BN_NIST_224_TOP, BN_NIST_224_TOP);
#endif
	nist_set_224(t_d, buf, 10, 9, 8, 7, 0, 0, 0);
	carry = bn_add_words(r_d, r_d, t_d, BN_NIST_224_TOP);
	nist_set_224(t_d, buf, 0, 13, 12, 11, 0, 0, 0);
	carry += bn_add_words(r_d, r_d, t_d, BN_NIST_224_TOP);
	nist_set_224(t_d, buf, 13, 12, 11, 10, 9, 8, 7);
	carry -= bn_sub_words(r_d, r_d, t_d, BN_NIST_224_TOP);
	nist_set_224(t_d, buf, 0, 0, 0, 0, 13, 12, 11);
	carry -= bn_sub_words(r_d, r_d, t_d, BN_NIST_224_TOP);

#if BN_BITS2==64
	carry = (int)(r_d[BN_NIST_224_TOP-1]>>32);
#endif
	u.f = bn_sub_words;
	if (carry > 0)
		{
		carry = bn_sub_words(r_d,r_d,_nist_p_224[carry-1],BN_NIST_224_TOP);
#if BN_BITS2==64
		carry=(int)(~(r_d[BN_NIST_224_TOP-1]>>32))&1;
#endif
		}
	else if (carry < 0)
		{
		/* it's a bit more comlicated logic in this case.
		 * if bn_add_words yields no carry, then result
		 * has to be adjusted by unconditionally *adding*
		 * the modulus. but if it does, then result has
		 * to be compared to the modulus and conditionally
		 * adjusted by *subtracting* the latter. */
		carry = bn_add_words(r_d,r_d,_nist_p_224[-carry-1],BN_NIST_224_TOP);
		mask = 0-(size_t)carry;
		u.p = ((size_t)bn_sub_words&mask) | ((size_t)bn_add_words&~mask);
		}
	else
		carry = 1;

	/* otherwise it's effectively same as in BN_nist_mod_192... */
	mask  = 0-(size_t)(*u.f)(c_d,r_d,_nist_p_224[0],BN_NIST_224_TOP);
	mask &= 0-(size_t)carry;
	res   = (BN_ULONG *)(((size_t)c_d&~mask) | ((size_t)r_d&mask));
	nist_cp_bn(r_d, res, BN_NIST_224_TOP);
	r->top = BN_NIST_224_TOP;
	bn_correct_top(r);

	return 1;
	}