BN_CTX-related fixes.
diff --git a/CHANGES b/CHANGES
index 8e53374..df8d4b1 100644
--- a/CHANGES
+++ b/CHANGES
@@ -4,6 +4,10 @@
 
  Changes between 0.9.6 and 0.9.7  [xx XXX 2000]
 
+  *) Increase BN_CTX_NUM (the number of BIGNUMs in a BN_CTX) to 16.
+     The previous value, 12, was not always sufficient for BN_mod_exp().
+     [Bodo Moeller]
+
   *) Make DSO load along a path given through an environment variable
      (SHLIB_PATH) with shl_load().
      [Richard Levitte]
diff --git a/crypto/bn/bn.h b/crypto/bn/bn.h
index dad488f..b6e8b7c 100644
--- a/crypto/bn/bn.h
+++ b/crypto/bn/bn.h
@@ -239,7 +239,7 @@
 	} BIGNUM;
 
 /* Used for temp variables */
-#define BN_CTX_NUM	12
+#define BN_CTX_NUM	16
 #define BN_CTX_NUM_POS	12
 typedef struct bignum_ctx
 	{
diff --git a/crypto/bn/bn_ctx.c b/crypto/bn/bn_ctx.c
index b1a8d75..28b334f 100644
--- a/crypto/bn/bn_ctx.c
+++ b/crypto/bn/bn_ctx.c
@@ -112,8 +112,14 @@
 	ctx->depth++;
 	}
 
+
 BIGNUM *BN_CTX_get(BN_CTX *ctx)
 	{
+	/* Note: If BN_CTX_get is ever changed to allocate BIGNUMs dynamically,
+	 * make sure that if BN_CTX_get fails once it will return NULL again
+	 * until BN_CTX_end is called.  (This is so that callers have to check
+	 * only the last return value.)
+	 */
 	if (ctx->depth > BN_CTX_NUM_POS || ctx->tos >= BN_CTX_NUM)
 		{
 		if (!ctx->too_many)
diff --git a/crypto/bn/bn_div.c b/crypto/bn/bn_div.c
index c3772c2..999bba7 100644
--- a/crypto/bn/bn_div.c
+++ b/crypto/bn/bn_div.c
@@ -180,13 +180,13 @@
 
 	BN_CTX_start(ctx);
 	tmp=BN_CTX_get(ctx);
-	tmp->neg=0;
 	snum=BN_CTX_get(ctx);
 	sdiv=BN_CTX_get(ctx);
 	if (dv == NULL)
 		res=BN_CTX_get(ctx);
 	else	res=dv;
-	if (res == NULL) goto err;
+	if (sdiv == NULL || res == NULL) goto err;
+	tmp->neg=0;
 
 	/* First we normalise the numbers */
 	norm_shift=BN_BITS2-((BN_num_bits(divisor))%BN_BITS2);