--- fileutils-4.1/src/ls.c	2001-04-29 19:42:47.000000000 +1000
+++ fileutils-4.1.clicolor/src/ls.c	2003-03-19 18:05:30.000000000 +1100
@@ -1075,6 +1075,12 @@
 	}
     }
 
+  /* Set default color mode to color_if_tty if CLICOLOR is set.  */
+  if (!getenv ("POSIXLY_CORRECT") && getenv ("CLICOLOR"))
+    {
+      print_with_color = color_if_tty;
+    }
+
   while ((c = getopt_long (argc, argv,
 			   "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
 			   long_options, NULL)) != -1)
@@ -1294,23 +1300,11 @@
 
 	case COLOR_OPTION:
 	  if (optarg)
-	    i = XARGMATCH ("--color", optarg, color_args, color_types);
+	    print_with_color = XARGMATCH ("--color", optarg, color_args, color_types);
 	  else
 	    /* Using --color with no argument is equivalent to using
 	       --color=always.  */
-	    i = color_always;
-
-	  print_with_color = (i == color_always
-			      || (i == color_if_tty
-				  && isatty (STDOUT_FILENO)));
-
-	  if (print_with_color)
-	    {
-	      /* Don't use TAB characters in output.  Some terminal
-		 emulators can't handle the combination of tabs and
-		 color codes on the same line.  */
-	      tabsize = 0;
-	    }
+	    print_with_color = color_always;
 	  break;
 
 	case INDICATOR_STYLE_OPTION:
@@ -1341,6 +1335,25 @@
 	default:
 	  usage (EXIT_FAILURE);
 	}
+
+    }
+
+  /* print_with_color can be set inside the case statement if the
+     --color option is specified or outside the case statement
+     if the CLICOLOR environment variable is set, so handle it after
+     all command line options are processed.  */
+  if ((print_with_color == color_if_tty) && !isatty (STDOUT_FILENO))
+    {
+      /* If the color mode is color_if_tty, but output is not a
+         terminal, turn colors off.  */
+      print_with_color = 0;
+    }
+  if (print_with_color)
+    {
+      /* Don't use TAB characters in output.  Some terminal
+         emulators can't handle the combination of tabs and
+         color codes on the same line.  */
+      tabsize = 0;
     }
 
   filename_quoting_options = clone_quoting_options (NULL);
