diff --git a/libgfortran/ChangeLog b/libgfortran/ChangeLog
index 38326632b4bd1c1cd7f8d1d398b441cf26fe1dc3..709500bc535d856202879b6f22f93a9917ebf9d9 100644
--- a/libgfortran/ChangeLog
+++ b/libgfortran/ChangeLog
@@ -1,3 +1,12 @@
+2006-09-22  Danny Smith  <dannysmith@users.sourceforge.net>
+
+	PR libfortran/27964
+	* configure.ac: Check for setmode() function.
+	* configure: Regenerate.
+	* config.h.in: Regenerate.
+	* io/unix.c (output_stream): Force stdout to binary mode. 
+	(error_stream): Force stderr to binary mode.
+
 2006-09-15  Jerry DeLisle  <jvdelisle@gcc.gnu.org>
 
 	PR libgfortran/29099
diff --git a/libgfortran/config.h.in b/libgfortran/config.h.in
index 11f8e72e1bc62a6e9a8ef1c8803cedf5d711ec84..444cd2bbb0b2591fd8808f46f8c265c2d8918dbe 100644
--- a/libgfortran/config.h.in
+++ b/libgfortran/config.h.in
@@ -492,6 +492,9 @@
 /* libm includes scalbnl */
 #undef HAVE_SCALBNL
 
+/* Define to 1 if you have the `setmode' function. */
+#undef HAVE_SETMODE
+
 /* Define to 1 if you have the `signal' function. */
 #undef HAVE_SIGNAL
 
diff --git a/libgfortran/configure b/libgfortran/configure
index 7af0b3209e157fd6ae1e33ad3d40fcb2e1025425..75872aa861db76510c86f7b2cb7f93915de27044 100755
--- a/libgfortran/configure
+++ b/libgfortran/configure
@@ -10037,7 +10037,7 @@ fi
 done
 
 
-for ac_func in wait
+for ac_func in wait setmode
 do
 as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
 echo "$as_me:$LINENO: checking for $ac_func" >&5
diff --git a/libgfortran/configure.ac b/libgfortran/configure.ac
index 5e8efd49b355f84d19c014ab8a29c81b6e4c5deb..4784fa575099959d00ca8d8f44431ad7a4d3d9db 100644
--- a/libgfortran/configure.ac
+++ b/libgfortran/configure.ac
@@ -172,7 +172,7 @@ AC_CHECK_MEMBERS([struct stat.st_rdev])
 AC_CHECK_FUNCS(getrusage times mkstemp strtof strtold snprintf ftruncate chsize)
 AC_CHECK_FUNCS(chdir strerror getlogin gethostname kill link symlink perror)
 AC_CHECK_FUNCS(sleep time ttyname signal alarm ctime clock access fork execl)
-AC_CHECK_FUNCS(wait)
+AC_CHECK_FUNCS(wait setmode)
 
 # Check libc for getgid, getpid, getuid
 AC_CHECK_LIB([c],[getgid],[AC_DEFINE([HAVE_GETGID],[1],[libc includes getgid])])
diff --git a/libgfortran/io/unix.c b/libgfortran/io/unix.c
index 560047f88f8e9aebe86594f9756089117f640254..57883e0f4e3964aa4a7f8f5237ac4a9aa6deba37 100644
--- a/libgfortran/io/unix.c
+++ b/libgfortran/io/unix.c
@@ -1289,6 +1289,9 @@ input_stream (void)
 stream *
 output_stream (void)
 {
+#if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
+  setmode (STDOUT_FILENO, O_BINARY);
+#endif
   return fd_to_stream (STDOUT_FILENO, PROT_WRITE);
 }
 
@@ -1299,6 +1302,9 @@ output_stream (void)
 stream *
 error_stream (void)
 {
+#if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
+  setmode (STDERR_FILENO, O_BINARY);
+#endif
   return fd_to_stream (STDERR_FILENO, PROT_WRITE);
 }