diff --git a/bstraux.c b/bstraux.c
index 3f86efd84003f3f0a12342da0e5632a264369096_YnN0cmF1eC5j..fcec18c164be2487d2f9c995f549c94e8de0d813_YnN0cmF1eC5j 100644
--- a/bstraux.c
+++ b/bstraux.c
@@ -600,7 +600,5 @@
 	b = bfromcstralloc (256, "");
 	if (NULL == b || 0 > bsread (b, d, INT_MAX)) {
 		bdestroy (b);
-		bsclose (d);
-		bsclose (s);
-		return NULL;
+		b = NULL;
 	}
@@ -606,4 +604,6 @@
 	}
+	bsclose (d);
+	bsclose (s);
 	return b;
 }
 
@@ -838,6 +838,24 @@
 	return out;
 }
 
+/*  int bSGMLEncode (bstring b)
+ *
+ *  Change the string into a version that is quotable in SGML (HTML, XML).
+ */
+int bSGMLEncode (bstring b) {
+static struct tagbstring fr[4][2] = {
+	{ bsStatic("&"), bsStatic("&") },
+	{ bsStatic("\""), bsStatic(""") },
+	{ bsStatic("<"), bsStatic("&lt;") },
+	{ bsStatic(">"), bsStatic("&gt;") } };
+int i;
+	for (i = 0; i < 4; i++) {
+		int ret = bfindreplace (b, &fr[i][0], &fr[i][1], 0);
+		if (0 > ret) return ret;
+	}
+	return 0;
+}
+
 /*  bstring bStrfTime (const char * fmt, const struct tm * timeptr)
  *
  *  Takes a format string that is compatible with strftime and a struct tm
diff --git a/bstraux.h b/bstraux.h
index 3f86efd84003f3f0a12342da0e5632a264369096_YnN0cmF1eC5o..fcec18c164be2487d2f9c995f549c94e8de0d813_YnN0cmF1eC5o 100644
--- a/bstraux.h
+++ b/bstraux.h
@@ -76,6 +76,7 @@
 extern bstring bUuEncode (const_bstring src);
 extern bstring bYEncode (const_bstring src);
 extern bstring bYDecode (const_bstring src);
+extern int bSGMLEncode (bstring b);
 
 /* Writable stream */
 typedef int (* bNwrite) (const void * buf, size_t elsize, size_t nelem, void * parm);
diff --git a/testaux.c b/testaux.c
index 3f86efd84003f3f0a12342da0e5632a264369096_dGVzdGF1eC5j..fcec18c164be2487d2f9c995f549c94e8de0d813_dGVzdGF1eC5j 100644
--- a/testaux.c
+++ b/testaux.c
@@ -379,6 +379,23 @@
 	return ret;
 }
 
+int test14_aux(bstring b, const char* chkVal) {
+int ret = 0;
+	ret += 0 != bSGMLEncode (b);
+	ret += 1 != biseqcstr (b, chkVal);
+	return ret;
+}
+
+int test14 (void) {
+bstring b;
+int ret = 0;
+
+	printf ("TEST: bSGMLEncode.\n");
+	ret += test14_aux (b = bfromStatic ("<\"Hello, you, me, & world\">"), "&lt;&quot;Hello, you, me, &amp; world&quot;&gt;");
+	printf ("\t# failures: %d\n", ret);
+	return ret;
+}
+
 int main () {
 int ret = 0;
 
@@ -398,6 +415,7 @@
 	ret += test11 ();
 	ret += test12 ();
 	ret += test13 ();
+	ret += test14 ();
 
 	printf ("# test failures: %d\n", ret);