* lib/inttypes_.h (_LONG_LONG_FORMAT_PREFIX): New macro.
[gnulib.git] / gnulib-tool
index 4df7612..4fb7d5e 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 #
-# Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+# Copyright (C) 2002-2006 Free Software Foundation, Inc.
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -13,8 +13,8 @@
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 #
 
 # This program is meant for authors or maintainers which want to import
 
 progname=$0
 package=gnulib
-cvsdatestamp='$Date: 2005-11-04 18:25:19 $'
+cvsdatestamp='$Date: 2006-10-07 14:54:51 $'
 last_checkin_date=`echo "$cvsdatestamp" | sed -e 's,^\$[D]ate: ,,'`
 version=`echo "$last_checkin_date" | sed -e 's/ .*$//' -e 's,/,-,g'`
+nl='
+'
 
 # You can set AUTOCONFPATH to empty if autoconf 2.57 is already in your PATH.
 AUTOCONFPATH=
@@ -35,7 +37,29 @@ AUTOCONFPATH=
 #    ;;
 #esac
 
-AUTORECONF="${AUTOCONFPATH}autoreconf"
+# You can set AUTOMAKEPATH to empty if automake 1.9.x is already in your PATH.
+AUTOMAKEPATH=
+
+# If you didn't set AUTOCONFPATH and AUTOMAKEPATH, you can also set the
+# variables AUTOCONF, ACLOCAL, AUTOMAKE, AUTORECONF individually.
+if test -z "${AUTOCONF}" || test -n "${AUTOCONFPATH}"; then
+  AUTOCONF="${AUTOCONFPATH}autoconf"
+fi
+if test -z "${ACLOCAL}" || test -n "${AUTOMAKEPATH}"; then
+  ACLOCAL="${AUTOMAKEPATH}aclocal"
+fi
+if test -z "${AUTOMAKE}" || test -n "${AUTOMAKEPATH}"; then
+  AUTOMAKE="${AUTOMAKEPATH}automake"
+fi
+if test -z "${AUTORECONF}" || test -n "${AUTOCONFPATH}"; then
+  AUTORECONF="${AUTOCONFPATH}autoreconf"
+fi
+
+# GNU sort is needed. Set SORT to its location (not needed if it's called
+# 'sort' and already in the PATH).
+if test -z "$SORT"; then
+  SORT=sort
+fi
 
 # func_usage
 # outputs to stdout the --help usage message.
@@ -61,7 +85,11 @@ Usage: gnulib-tool --list
 
 Operation modes:
       --list                print the available module names
-      --import              import the given modules into the current package
+      --import              import the given modules into the current package;
+                            if no modules are specified, update the current
+                            package from the current gnulib
+      --update              update the current package, restore files omitted
+                            from CVS
       --create-testdir      create a scratch package with the given modules
       --create-megatestdir  create a mega scratch package with the given modules
                             one by one and all together
@@ -73,28 +101,34 @@ Operation modes:
       --extract-filelist           extract the list of files
       --extract-dependencies       extract the dependencies
       --extract-autoconf-snippet   extract the snippet for configure.ac
-      --extract-automake-snippet   extract the snippet for lib/Makefile.am
+      --extract-automake-snippet   extract the snippet for library makefile
       --extract-include-directive  extract the #include directive
       --extract-license            report the license terms of the source files
                                    under lib/
       --extract-maintainer         report the maintainer(s) inside gnulib
       --extract-tests-module       report the unit test module, if it exists
 
-Options:
-      --dir=DIRECTORY       specify the target directory
+General options:
+      --dir=DIRECTORY       Specify the target directory.
                             For --import, this specifies where your
                             configure.ac can be found.  Defaults to current
                             directory.
+      --local-dir=DIRECTORY  Specify a local override directory where to look
+                            up files before looking in gnulib's directory.
+
+Options for --import:
       --lib=LIBRARY         Specify the library name.  Defaults to 'libgnu'.
       --source-base=DIRECTORY
-                            Directory relative --dir where source code is
-                            placed (default \"lib\"), for --import.
-      --m4-base=DIRECTORY   Directory relative --dir where *.m4 macros are
-                            placed (default \"m4\"), for --import.
+                            Directory relative to --dir where source code is
+                            placed (default \"lib\").
+      --m4-base=DIRECTORY   Directory relative to --dir where *.m4 macros are
+                            placed (default \"m4\").
+      --doc-base=DIRECTORY  Directory relative to --dir where doc files are
+                            placed (default \"doc\").
       --tests-base=DIRECTORY
-                            Directory relative --dir where unit tests are
-                            placed (default \"tests\"), for --import.
-      --aux-dir=DIRECTORY   Directory relative --dir where auxiliary build
+                            Directory relative to --dir where unit tests are
+                            placed (default \"tests\").
+      --aux-dir=DIRECTORY   Directory relative to --dir where auxiliary build
                             tools are placed (default \"build-aux\").
       --with-tests          Include unit tests for the included modules.
       --avoid=MODULE        Avoid including the given MODULE. Useful if you
@@ -102,10 +136,16 @@ Options:
                             This option can be repeated.
       --lgpl                Abort if modules aren't available under the LGPL.
                             Also modify license template from GPL to LGPL.
-      --libtool             Use libtool rules, for --import.
+      --makefile-name=NAME  Name of makefile in automake syntax in the
+                            source-base and tests-base directories
+                            (default \"Makefile.am\").
+      --libtool             Use libtool rules.
+      --no-libtool          Don't use libtool rules.
       --macro-prefix=PREFIX  Specify the prefix of the macros 'gl_EARLY' and
                             'gl_INIT'. Default is 'gl'.
       --no-changelog        don't update or create ChangeLog files
+
+Options for --import and --update:
       --dry-run             For --import, only print what would have been done.
   -s, --symbolic, --symlink Make symbolic links instead of copying files.
 
@@ -116,11 +156,35 @@ Report bugs to <bug-gnulib@gnu.org>."
 # outputs to stdout the --version message.
 func_version ()
 {
-  echo "$progname (GNU $package) $version"
-  echo "Copyright (C) 2002-2005 Free Software Foundation, Inc.
+  year=`echo "$last_checkin_date" | sed -e 's,/.*$,,'`
+  echo "\
+$progname (GNU $package) $version
+Copyright (C) $year Free Software Foundation, Inc.
 This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-  echo "Written by" "Bruno Haible" "and" "Simon Josefsson"
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+Written by" "Bruno Haible" "and" "Simon Josefsson"
+}
+
+# func_emit_copyright_notice
+# outputs to stdout a header for a generated file.
+func_emit_copyright_notice ()
+{
+  echo "# Copyright (C) 2004-2006 Free Software Foundation, Inc."
+  echo "#"
+  echo "# This file is free software, distributed under the terms of the GNU"
+  echo "# General Public License.  As a special exception to the GNU General"
+  echo "# Public License, this file may be distributed as part of a program"
+  echo "# that contains a configuration script generated by Autoconf, under"
+  echo "# the same distribution terms as the rest of that program."
+  echo "#"
+  echo "# Generated by gnulib-tool."
+}
+
+# func_exit STATUS
+# exit with status
+func_exit ()
+{
+  (exit $1); exit $1
 }
 
 # func_tmpdir
@@ -136,7 +200,7 @@ func_tmpdir ()
   {
     # Use the mktemp program if available. If not available, hide the error
     # message.
-    tmp=`(umask 077 && mktemp -d -q "$TMPDIR/glXXXXXX") 2>/dev/null` &&
+    tmp=`(umask 077 && mktemp -d "$TMPDIR/glXXXXXX") 2>/dev/null` &&
     test -n "$tmp" && test -d "$tmp"
   } ||
   {
@@ -150,17 +214,33 @@ func_tmpdir ()
   } ||
   {
     echo "$0: cannot create a temporary directory in $TMPDIR" >&2
-    { (exit 1); exit 1; }
+    func_exit 1
   }
 }
 
+# func_append var value
+# appends the given value to the shell variable var.
+if ( foo=bar; foo+=baz && test "$foo" = barbaz ) >/dev/null 2>&1; then
+  # Use bash's += operator. It reduces complexity of appending repeatedly to
+  # a single variable from O(n^2) to O(n).
+  func_append ()
+  {
+    eval "$1+=\"\$2\""
+  }
+else
+  func_append ()
+  {
+    eval "$1=\"\$$1\$2\""
+  }
+fi
+
 # func_fatal_error message
 # outputs to stderr a fatal error message, and terminates the program.
 func_fatal_error ()
 {
   echo "gnulib-tool: *** $1" 1>&2
   echo "gnulib-tool: *** Stop." 1>&2
-  exit 1
+  func_exit 1
 }
 
 # func_readlink SYMLINK
@@ -195,33 +275,136 @@ func_ln_if_changed ()
   fi
 }
 
+# func_relativize DIR1 DIR2
+# computes a relative pathname RELDIR such that DIR1/RELDIR = DIR2.
+# Input:
+# - DIR1            relative pathname, relative to the current directory
+# - DIR2            relative pathname, relative to the current directory
+# Output:
+# - reldir          relative pathname of DIR2, relative to DIR1
+func_relativize ()
+{
+  dir0=`pwd`
+  dir1="$1"
+  dir2="$2"
+  sed_first='s,^\([^/]*\)/.*$,\1,'
+  sed_rest='s,^[^/]*/*,,'
+  sed_last='s,^.*/\([^/]*\)$,\1,'
+  sed_butlast='s,/*[^/]*$,,'
+  while test -n "$dir1"; do
+    first=`echo "$dir1" | sed -e "$sed_first"`
+    if test "$first" != "."; then
+      if test "$first" = ".."; then
+        dir2=`echo "$dir0" | sed -e "$sed_last"`/"$dir2"
+        dir0=`echo "$dir0" | sed -e "$sed_butlast"`
+      else
+        first2=`echo "$dir2" | sed -e "$sed_first"`
+        if test "$first2" = "$first"; then
+          dir2=`echo "$dir2" | sed -e "$sed_rest"`
+        else
+          dir2="../$dir2"
+        fi
+        dir0="$dir0"/"$first"
+      fi
+    fi
+    dir1=`echo "$dir1" | sed -e "$sed_rest"`
+  done
+  reldir="$dir2"
+}
+
+# func_relconcat DIR1 DIR2
+# computes a relative pathname DIR1/DIR2, with obvious simplifications.
+# Input:
+# - DIR1            relative pathname, relative to the current directory
+# - DIR2            relative pathname, relative to DIR1
+# Output:
+# - relconcat       DIR1/DIR2, relative to the current directory
+func_relconcat ()
+{
+  dir1="$1"
+  dir2="$2"
+  sed_first='s,^\([^/]*\)/.*$,\1,'
+  sed_rest='s,^[^/]*/*,,'
+  sed_last='s,^.*/\([^/]*\)$,\1,'
+  sed_butlast='s,/*[^/]*$,,'
+  while true; do
+    first=`echo "$dir2" | sed -e "$sed_first"`
+    if test "$first" = "."; then
+      dir2=`echo "$dir2" | sed -e "$sed_rest"`
+      if test -z "$dir2"; then
+        relconcat="$dir1"
+        break
+      fi
+    else
+      last=`echo "$dir1" | sed -e "$sed_last"`
+      while test "$last" = "."; do
+        dir1=`echo "$dir1" | sed -e "$sed_butlast"`
+        last=`echo "$dir1" | sed -e "$sed_last"`
+      done
+      if test -z "$dir1"; then
+        relconcat="$dir2"
+        break
+      fi
+      if test "$first" = ".."; then
+        if test "$last" = ".."; then
+          relconcat="$dir1/$dir2"
+          break
+        fi
+        dir1=`echo "$dir1" | sed -e "$sed_butlast"`
+        dir2=`echo "$dir2" | sed -e "$sed_rest"`
+        if test -z "$dir1"; then
+          relconcat="$dir2"
+          break
+        fi
+        if test -z "$dir2"; then
+          relconcat="$dir1"
+          break
+        fi
+      else
+        relconcat="$dir1/$dir2"
+        break
+      fi
+    fi
+  done
+}
+
 # Command-line option processing.
 # Removes the OPTIONS from the arguments. Sets the variables:
 # - mode            list or import or create-testdir or create-megatestdir
 # - destdir         from --dir
+# - local_gnulib_dir  from --local-dir
 # - libname, supplied_libname  from --lib
 # - sourcebase      from --source-base
 # - m4base          from --m4-base
+# - docbase         from --doc-base
 # - testsbase       from --tests-base
 # - auxdir          from --aux-dir
 # - inctests        true if --with-tests was given, blank otherwise
 # - avoidlist       list of modules to avoid, from --avoid
 # - lgpl            true if --lgpl was given, blank otherwise
-# - libtool         true if --libtool was given, blank otherwise
+# - makefile_name   from --makefile-name
+# - libtool         true if --libtool was given, false if --no-libtool was
+#                   given, blank otherwise
+# - macro_prefix    from --macro-prefix
+# - autoconf_minversion  minimum supported autoconf version
 # - do_changelog    false if --no-changelog was given, : otherwise
 # - doit            : if actions shall be executed, false if only to be printed
+# - symbolic        true if --symbolic was given, blank otherwise
 {
   mode=
   destdir=
+  local_gnulib_dir=
   libname=libgnu
   supplied_libname=
   sourcebase=
   m4base=
+  docbase=
   testsbase=
   auxdir=
   inctests=
   avoidlist=
   lgpl=
+  makefile_name=
   libtool=
   macro_prefix=
   do_changelog=:
@@ -266,6 +449,16 @@ func_ln_if_changed ()
       --dir=* )
         destdir=`echo "X$1" | sed -e 's/^X--dir=//'`
         shift ;;
+      --local-dir )
+        shift
+        if test $# = 0; then
+          func_fatal_error "missing argument for --local-dir"
+        fi
+        local_gnulib_dir=$1
+        shift ;;
+      --local-dir=* )
+        local_gnulib_dir=`echo "X$1" | sed -e 's/^X--local-dir=//'`
+        shift ;;
       --lib )
         shift
         if test $# = 0; then
@@ -298,6 +491,16 @@ func_ln_if_changed ()
       --m4-base=* )
         m4base=`echo "X$1" | sed -e 's/^X--m4-base=//'`
         shift ;;
+      --doc-base )
+        shift
+        if test $# = 0; then
+          func_fatal_error "missing argument for --doc-base"
+        fi
+        docbase=$1
+        shift ;;
+      --doc-base=* )
+        docbase=`echo "X$1" | sed -e 's/^X--doc-base=//'`
+        shift ;;
       --tests-base )
         shift
         if test $# = 0; then
@@ -326,17 +529,31 @@ func_ln_if_changed ()
         if test $# = 0; then
           func_fatal_error "missing argument for --avoid"
         fi
-        avoidlist="$avoidlist $1"
+        func_append avoidlist " $1"
         shift ;;
       --avoid=* )
-        avoidlist="$avoidlist "`echo "X$1" | sed -e 's/^X--avoid=//'`
+        arg=`echo "X$1" | sed -e 's/^X--avoid=//'`
+        func_append avoidlist " $arg"
         shift ;;
       --lgpl )
         lgpl=true
         shift ;;
+      --makefile-name )
+        shift
+        if test $# = 0; then
+          func_fatal_error "missing argument for --makefile-name"
+        fi
+        makefile_name="$1"
+        shift ;;
+      --makefile-name=* )
+        makefile_name=`echo "X$1" | sed -e 's/^X--makefile-name=//'`
+        shift ;;
       --libtool )
         libtool=true
         shift ;;
+      --no-libtool )
+        libtool=false
+        shift ;;
       --macro-prefix )
         shift
         if test $# = 0; then
@@ -358,10 +575,10 @@ func_ln_if_changed ()
         shift ;;
       --help | --hel | --he | --h )
         func_usage
-        exit 0 ;;
+        func_exit $? ;;
       --version | --versio | --versi | --vers | --ver | --ve | --v )
         func_version
-        exit 0 ;;
+        func_exit $? ;;
       -- )
         # Stop option processing
         shift
@@ -369,7 +586,7 @@ func_ln_if_changed ()
       -* )
         echo "gnulib-tool: unknown option $1" 1>&2
         echo "Try 'gnulib-tool --help' for more information." 1>&2
-        exit 1 ;;
+        func_exit 1 ;;
       * )
         break ;;
     esac
@@ -381,29 +598,86 @@ func_ln_if_changed ()
       echo "Try 'gnulib-tool --help' for more information." 1>&2
       echo "If you really want to modify the gnulib configuration of your project," 1>&2
       echo "you need to use 'gnulib --import' - at your own risk!" 1>&2
-      exit 1
+      func_exit 1
     fi
-    if test -n "$libname" || test -n "$sourcebase" || test -n "$m4base" \
-       || test -n "$testsbase" || test -n "$auxdir" || test -n "$inctests" \
-       || test -n "$avoidlist" || test -n "$lgpl" || test -n "$macro_prefix"; then
+    if test -n "$local_gnulib_dir" || test -n "$supplied_libname" \
+       || test -n "$sourcebase" || test -n "$m4base" \
+       || test -n "$docbase" || test -n "$testsbase" || test -n "$auxdir" \
+       || test -n "$inctests" || test -n "$avoidlist" || test -n "$lgpl" \
+       || test -n "$makefile_name" || test -n "$macro_prefix"; then
       echo "gnulib-tool: invalid options for 'update' mode" 1>&2
       echo "Try 'gnulib-tool --help' for more information." 1>&2
       echo "If you really want to modify the gnulib configuration of your project," 1>&2
       echo "you need to use 'gnulib --import' - at your own risk!" 1>&2
-      exit 1
+      func_exit 1
     fi
     do_changelog=false
   fi
 
+  # Determine the minimum supported autoconf version from the project's
+  # configure.ac.
+  DEFAULT_AUTOCONF_MINVERSION="2.59"
+  autoconf_minversion=
+  configure_ac=
+  if { test "$mode" = import || test "$mode" = update; } && test -n "$destdir"; then
+    if test -f "$destdir"/configure.ac; then
+      configure_ac="$destdir/configure.ac"
+    else
+      if test -f "$destdir"/configure.in; then
+        configure_ac="$destdir/configure.in"
+      fi
+    fi
+  else
+    if test -f configure.ac; then
+      configure_ac="configure.ac"
+    else
+      if test -f configure.in; then
+        configure_ac="configure.in"
+      fi
+    fi
+  fi
+  if test -n "$configure_ac"; then
+    # Use sed, not autoconf --trace, to look for the AC_PREREQ invocation,
+    # because when some m4 files are omitted from a CVS repository,
+    # "autoconf --trace=AC_PREREQ" fails with an error message like this:
+    #   m4: aclocal.m4:851: Cannot open m4/absolute-header.m4: No such file or directory
+    #   autom4te: m4 failed with exit status: 1
+    prereqs=
+    my_sed_traces='
+      s,#.*$,,
+      s,^dnl .*$,,
+      s, dnl .*$,,
+      /AC_PREREQ/ {
+        s,^.*AC_PREREQ([[ ]*\([^])]*\).*$,prereqs="$prereqs \1",p
+      }'
+    eval `sed -n -e "$my_sed_traces" < "$configure_ac"`
+    if test -n "$prereqs"; then
+      autoconf_minversion=`for version in $prereqs; do echo $version; done | $SORT -g -u | tail -1`
+    fi
+  fi
+  if test -z "$autoconf_minversion"; then
+    autoconf_minversion=$DEFAULT_AUTOCONF_MINVERSION
+  fi
+  case "$autoconf_minversion" in
+    1.* | 2.[0-4]* | 2.5[0-8]*)
+      func_fatal_error "minimum supported autoconf version is 2.59. Try adding AC_PREREQ([$DEFAULT_AUTOCONF_MINVERSION]) to your configure.ac." ;;
+  esac
+
   # Remove trailing slashes from the directory names. This is necessary for
   # m4base (to avoid an error in func_import) and optional for the others.
   sed_trimtrailingslashes='s,\([^/]\)//*$,\1,'
+  case "$local_gnulib_dir" in
+    */ ) sourcebase=`echo "$local_gnulib_dir" | sed -e "$sed_trimtrailingslashes"` ;;
+  esac
   case "$sourcebase" in
     */ ) sourcebase=`echo "$sourcebase" | sed -e "$sed_trimtrailingslashes"` ;;
   esac
   case "$m4base" in
     */ ) m4base=`echo "$m4base" | sed -e "$sed_trimtrailingslashes"` ;;
   esac
+  case "$docbase" in
+    */ ) docbase=`echo "$docbase" | sed -e "$sed_trimtrailingslashes"` ;;
+  esac
   case "$testsbase" in
     */ ) testsbase=`echo "$testsbase" | sed -e "$sed_trimtrailingslashes"` ;;
   esac
@@ -437,28 +711,91 @@ while test -h "$self_abspathname"; do
 done
 gnulib_dir=`echo "$self_abspathname" | sed -e 's,/[^/]*$,,'`
 
+func_tmpdir
+trap 'exit_status=$?
+      if test "$signal" != 0; then
+        echo "caught signal $signal" >&2
+      fi
+      rm -rf "$tmp"
+      exit $exit_status' 0
+for signal in 1 2 3 13 15; do
+  trap '{ signal='$signal'; func_exit 1; }' $signal
+done
+signal=0
+
+# func_lookup_file file
+# looks up a file in $local_gnulib_dir or $gnulib_dir, or combines it through
+# 'patch'.
+# Input:
+# - local_gnulib_dir  from --local-dir
+# Output:
+# - lookedup_file   name of the merged (combined) file
+# - lookedup_tmp    true if it is located in the tmp directory, blank otherwise
+func_lookup_file ()
+{
+  lkfile="$1"
+  if test -n "$local_gnulib_dir" && test -f "$local_gnulib_dir/$lkfile"; then
+    lookedup_file="$local_gnulib_dir/$lkfile"
+    lookedup_tmp=
+  else
+    if test -f "$gnulib_dir/$lkfile"; then
+      if test -n "$local_gnulib_dir" && test -f "$local_gnulib_dir/$lkfile.diff"; then
+        lkbase=`echo "$lkfile" | sed -e 's,^.*/,,'`
+        rm -f "$tmp/$lkbase"
+        cp "$gnulib_dir/$lkfile" "$tmp/$lkbase"
+        patch -s "$tmp/$lkbase" < "$local_gnulib_dir/$lkfile.diff" \
+          || func_fatal_error "patch file $local_gnulib_dir/$lkfile.diff didn't apply cleanly"
+        lookedup_file="$tmp/$lkbase"
+        lookedup_tmp=true
+      else
+        lookedup_file="$gnulib_dir/$lkfile"
+        lookedup_tmp=
+      fi
+    else
+      func_fatal_error "file $gnulib_dir/$lkfile not found"
+    fi
+  fi
+}
+
 # func_all_modules
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_all_modules ()
 {
   # Filter out metainformation files like README, which are not modules.
   # Filter out unit test modules; they can be retrieved through
   # --extract-tests-module if desired.
-  (cd "$gnulib_dir/modules" && ls -1) \
-      | sed -e '/^CVS$/d' -e '/^ChangeLog$/d' -e '/^README$/d' -e '/^TEMPLATE$/d' -e '/^TEMPLATE-TESTS$/d' -e '/~$/d' \
+  {
+    (cd "$gnulib_dir/modules" && ls -1)
+    if test -n "$local_gnulib_dir" && test -d "$local_gnulib_dir/modules"; then
+      (cd "$local_gnulib_dir/modules" && ls -1 | sed -e 's,\.diff$,,')
+    fi
+  } \
+      | sed -e '/^CVS$/d' -e '/^ChangeLog$/d' -e '/^COPYING$/d' -e '/^README$/d' -e '/^TEMPLATE$/d' -e '/^TEMPLATE-TESTS$/d' -e '/~$/d' \
       | sed -e '/-tests$/d' \
-      | LC_ALL=C sort
+      | LC_ALL=C sort -u
 }
 
 # func_verify_module
 # verifies a module name
+# Input:
+# - local_gnulib_dir  from --local-dir
+# - module          module name argument
 func_verify_module ()
 {
-  if test ! -f "$gnulib_dir/modules/$module" \
-     || test "CVS" = "$module" \
-     || test "ChangeLog" = "$module" \
-     || test "README" = "$module" \
-     || test "TEMPLATE" = "$module" \
-     || test "TEMPLATE-TESTS" = "$module"; then
+  if { test -f "$gnulib_dir/modules/$module" \
+       || { test -n "$local_gnulib_dir" && test -d "$local_gnulib_dir/modules" \
+            && test -f "$local_gnulib_dir/modules/$module"; }; } \
+     && test "CVS" != "$module" \
+     && test "ChangeLog" != "$module" \
+     && test "COPYING" != "$module" \
+     && test "README" != "$module" \
+     && test "TEMPLATE" != "$module" \
+     && test "TEMPLATE-TESTS" != "$module"; then
+    # OK, $module is a correct module name.
+    # Verify that building the module description with 'patch' succeeds.
+    func_lookup_file "modules/$module"
+  else
     echo "gnulib-tool: module $module doesn't exist" 1>&2
     module=
   fi
@@ -466,6 +803,9 @@ func_verify_module ()
 
 # func_verify_nontests_module
 # verifies a module name, excluding tests modules
+# Input:
+# - local_gnulib_dir  from --local-dir
+# - module          module name argument
 func_verify_nontests_module ()
 {
   case "$module" in
@@ -476,6 +816,9 @@ func_verify_nontests_module ()
 
 # func_verify_tests_module
 # verifies a module name, considering only tests modules
+# Input:
+# - local_gnulib_dir  from --local-dir
+# - module          module name argument
 func_verify_tests_module ()
 {
   case "$module" in
@@ -484,17 +827,17 @@ func_verify_tests_module ()
   esac
 }
 
-sed_extract_prog=':[   ]*$/ {
+sed_extract_prog=':[    ]*$/ {
   :a
     n
-    s/^Description:[   ]*$//
-    s/^Files:[         ]*$//
-    s/^Depends-on:[    ]*$//
-    s/^configure\.ac:[         ]*$//
-    s/^Makefile\.am:[  ]*$//
-    s/^Include:[       ]*$//
-    s/^License:[       ]*$//
-    s/^Maintainer:[    ]*$//
+    s/^Description:[    ]*$//
+    s/^Files:[  ]*$//
+    s/^Depends-on:[     ]*$//
+    s/^configure\.ac:[  ]*$//
+    s/^Makefile\.am:[   ]*$//
+    s/^Include:[        ]*$//
+    s/^License:[        ]*$//
+    s/^Maintainer:[     ]*$//
     tb
     p
     ba
@@ -502,64 +845,96 @@ sed_extract_prog=':[      ]*$/ {
 }'
 
 # func_get_description module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_description ()
 {
-  sed -n -e "/^Description$sed_extract_prog" < "$gnulib_dir/modules/$1"
+  func_lookup_file "modules/$1"
+  sed -n -e "/^Description$sed_extract_prog" < "$lookedup_file"
 }
 
 # func_get_filelist module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_filelist ()
 {
-  sed -n -e "/^Files$sed_extract_prog" < "$gnulib_dir/modules/$1"
-  #echo m4/onceonly.m4
-  echo m4/onceonly_2_57.m4
+  func_lookup_file "modules/$1"
+  sed -n -e "/^Files$sed_extract_prog" < "$lookedup_file"
+  case "$autoconf_minversion" in
+    2.59)
+      #echo m4/onceonly.m4
+      echo m4/onceonly_2_57.m4
+      ;;
+  esac
 }
 
 # func_get_dependencies module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_dependencies ()
 {
   # ${module}-tests always implicitly depends on ${module}.
   echo "$1" | sed -n -e 's/-tests//p'
   # Then the explicit dependencies listed in the module description.
-  sed -n -e "/^Depends-on$sed_extract_prog" < "$gnulib_dir/modules/$1"
+  func_lookup_file "modules/$1"
+  sed -n -e "/^Depends-on$sed_extract_prog" < "$lookedup_file"
 }
 
 # func_get_autoconf_snippet module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_autoconf_snippet ()
 {
-  sed -n -e "/^configure\.ac$sed_extract_prog" < "$gnulib_dir/modules/$1"
+  func_lookup_file "modules/$1"
+  sed -n -e "/^configure\.ac$sed_extract_prog" < "$lookedup_file"
 }
 
 # func_get_automake_snippet module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_automake_snippet ()
 {
-  sed -n -e "/^Makefile\.am$sed_extract_prog" < "$gnulib_dir/modules/$1"
+  func_lookup_file "modules/$1"
+  sed -n -e "/^Makefile\.am$sed_extract_prog" < "$lookedup_file"
 }
 
 # func_get_include_directive module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_include_directive ()
 {
-  sed -n -e "/^Include$sed_extract_prog" < "$gnulib_dir/modules/$1" | \
+  func_lookup_file "modules/$1"
+  sed -n -e "/^Include$sed_extract_prog" < "$lookedup_file" | \
   sed -e 's/^\(["<]\)/#include \1/'
 }
 
 # func_get_license module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_license ()
 {
-  sed -n -e "/^License$sed_extract_prog" < "$gnulib_dir/modules/$1"
+  func_lookup_file "modules/$1"
+  sed -n -e "/^License$sed_extract_prog" < "$lookedup_file"
 }
 
 # func_get_maintainer module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_maintainer ()
 {
-  sed -n -e "/^Maintainer$sed_extract_prog" < "$gnulib_dir/modules/$1"
+  func_lookup_file "modules/$1"
+  sed -n -e "/^Maintainer$sed_extract_prog" < "$lookedup_file"
 }
 
 # func_get_tests_module module
+# Input:
+# - local_gnulib_dir  from --local-dir
 func_get_tests_module ()
 {
   # The naming convention for tests modules is hardwired: ${module}-tests.
-  if test -f modules/"$1"-tests; then
+  if test -f "$gnulib_dir/modules/$1"-tests \
+     || { test -n "$local_gnulib_dir" && test -d "$local_gnulib_dir/modules" \
+          && test -f "$local_gnulib_dir/modules/$1"-tests; }; then
     echo "$1"-tests
   fi
 }
@@ -580,56 +955,94 @@ func_acceptable ()
 
 # func_modules_transitive_closure
 # Input:
+# - local_gnulib_dir  from --local-dir
 # - modules         list of specified modules
 # - inctests        true if tests should be included, blank otherwise
 # - avoidlist       list of modules to avoid
+# - tmp             pathname of a temporary directory
 # Output:
 # - modules         list of modules, including dependencies
 func_modules_transitive_closure ()
 {
-  while true; do
-    xmodules=
-    for module in $modules; do
+  # In order to process every module only once (for speed), process an "input
+  # list" of modules, producing an "output list" of modules. During each round,
+  # more modules can be queued in the input list. Once a module on the input
+  # list has been processed, it is added to the "handled list", so we can avoid
+  # to process it again.
+  handledmodules=
+  inmodules="$modules"
+  outmodules=
+  while test -n "$inmodules"; do
+    inmodules_this_round="$inmodules"
+    inmodules=                    # Accumulator, queue for next round
+    for module in $inmodules_this_round; do
       func_verify_module
       if test -n "$module"; then
-        # Duplicate dependencies are harmless, but Jim wants a warning.
-        duplicated_deps=`func_get_dependencies $module | LC_ALL=C sort | LC_ALL=C uniq -d`
-        if test -n "$duplicated_deps"; then
-          echo "warning: module $module has duplicated dependencies: "`echo $duplicated_deps` 1>&2
-        fi
         if func_acceptable $module; then
-          xmodules="$xmodules $module"
-          for depmodule in `func_get_dependencies $module`; do
-            if func_acceptable $depmodule; then
-              xmodules="$xmodules $depmodule"
-            fi
-          done
+          func_append outmodules " $module"
+          deps=`func_get_dependencies $module`
+          # Duplicate dependencies are harmless, but Jim wants a warning.
+          duplicated_deps=`echo "$deps" | LC_ALL=C sort | LC_ALL=C uniq -d`
+          if test -n "$duplicated_deps"; then
+            echo "warning: module $module has duplicated dependencies: "`echo $duplicated_deps` 1>&2
+          fi
+          func_append inmodules " $deps"
           if test -n "$inctests"; then
             testsmodule=`func_get_tests_module $module`
             if test -n "$testsmodule"; then
-              if func_acceptable $testsmodule; then
-                xmodules="$xmodules $testsmodule"
-                for depmodule in `func_get_dependencies $testsmodule`; do
-                  if func_acceptable $depmodule; then
-                    xmodules="$xmodules $depmodule"
-                  fi
-                done
-              fi
+              func_append inmodules " $testsmodule"
             fi
           fi
         fi
       fi
     done
-    xmodules=`for m in $xmodules; do echo $m; done | LC_ALL=C sort | LC_ALL=C uniq`
-    if test "$xmodules" = "$modules"; then
-      break
+    handledmodules=`for m in $handledmodules $inmodules_this_round; do echo $m; done | LC_ALL=C sort -u`
+    # Remove $handledmodules from $inmodules.
+    for m in $inmodules; do echo $m; done | LC_ALL=C sort -u > "$tmp"/queued-modules
+    inmodules=`echo "$handledmodules" | LC_ALL=C join -v 2 - "$tmp"/queued-modules`
+  done
+  modules=`for m in $outmodules; do echo $m; done | LC_ALL=C sort -u`
+  rm -f "$tmp"/queued-modules
+}
+
+# func_modules_add_dummy
+# Input:
+# - local_gnulib_dir  from --local-dir
+# - modules         list of modules, including dependencies
+# Output:
+# - modules         list of modules, including 'dummy' if needed
+func_modules_add_dummy ()
+{
+  have_lib_SOURCES=
+  sed_remove_backslash_newline=':a
+/\\$/{
+s/\\$//
+N
+s/\n//
+ba
+}'
+  for module in $modules; do
+    func_verify_nontests_module
+    if test -n "$module"; then
+      # Extract the value of "lib_SOURCES += ...".
+      for file in `func_get_automake_snippet "$module" | sed -e "$sed_remove_backslash_newline" | sed -n -e 's,^lib_SOURCES[    ]*+=\([^#]*\).*$,\1,p'`; do
+        # Ignore .h files since they are not compiled.
+        case "$file" in
+          *.h) ;;
+          *) have_lib_SOURCES=yes ;;
+        esac
+      done
     fi
-    modules="$xmodules"
   done
+  # Add the dummy module, to make sure the library will be non-empty.
+  if test -z "$have_lib_SOURCES"; then
+    func_append modules " dummy"
+  fi
 }
 
 # func_modules_to_filelist
 # Input:
+# - local_gnulib_dir  from --local-dir
 # - modules         list of modules, including dependencies
 # Output:
 # - files           list of files
@@ -639,122 +1052,205 @@ func_modules_to_filelist ()
   for module in $modules; do
     func_verify_module
     if test -n "$module"; then
-      files="$files "`func_get_filelist $module`
+      fs=`func_get_filelist $module`
+      func_append files " $fs"
     fi
   done
-  files=`for f in $files; do echo $f; done | LC_ALL=C sort | LC_ALL=C uniq`
+  files=`for f in $files; do echo $f; done | LC_ALL=C sort -u`
 }
 
 # func_emit_lib_Makefile_am
-# emits the contents of lib/Makefile.am to standard output.
+# emits the contents of library makefile to standard output.
 # Input:
+# - local_gnulib_dir  from --local-dir
 # - modules         list of modules, including dependencies
 # - libname         library name
-# - libtool         true if libtool will be used, blank otherwise
+# - makefile_name   from --makefile-name
+# - libtool         true if libtool will be used, false or blank otherwise
 # - actioncmd       (optional) command that will reproduce this invocation
 func_emit_lib_Makefile_am ()
 {
-  if test -n "$libtool"; then
+  # When creating an includable Makefile.am snippet, augment variables with
+  # += instead of assigning them.
+  if test -n "$makefile_name"; then
+    assign='+='
+  else
+    assign='='
+  fi
+  if test "$libtool" = true; then
     libext=la
     perhapsLT=LT
+    sed_eliminate_LDFLAGS=
   else
     libext=a
     perhapsLT=
+    sed_eliminate_LDFLAGS='/^lib_LDFLAGS[       ]*+=/d'
   fi
+  echo "## DO NOT EDIT! GENERATED AUTOMATICALLY!"
   echo "## Process this file with automake to produce Makefile.in."
-  echo "# Copyright (C) 2004 Free Software Foundation, Inc."
-  echo "#"
-  echo "# This file is free software, distributed under the terms of the GNU"
-  echo "# General Public License.  As a special exception to the GNU General"
-  echo "# Public License, this file may be distributed as part of a program"
-  echo "# that contains a configuration script generated by Automake, under"
-  echo "# the same distribution terms as the rest of that program."
-  echo "#"
-  echo "# Generated by gnulib-tool."
+  func_emit_copyright_notice
   if test -n "$actioncmd"; then
     echo "# Reproduce by: $actioncmd"
   fi
   echo
-  # No need to generate dependencies since the sources are in gnulib, not here.
-  echo "AUTOMAKE_OPTIONS = 1.5 gnits no-dependencies"
-  echo
-  echo "noinst_${perhapsLT}LIBRARIES = $libname.$libext"
-  echo
-  echo "${libname}_${libext}_SOURCES ="
-  echo "${libname}_${libext}_LIBADD = @${perhapsLT}LIBOBJS@"
-  echo "EXTRA_DIST ="
-  echo "BUILT_SOURCES ="
-  echo "SUFFIXES ="
-  echo "MOSTLYCLEANFILES ="
-  echo "CLEANFILES ="
-  echo "DISTCLEANFILES ="
-  echo "MAINTAINERCLEANFILES ="
+  if test -z "$makefile_name"; then
+    echo "AUTOMAKE_OPTIONS = 1.5 gnits"
+  fi
   echo
-  for module in $modules; do
-    func_verify_nontests_module
-    if test -n "$module"; then
-      {
-        func_get_automake_snippet "$module" |
-          sed -e 's,lib_\([A-Z][A-Z]*\),'"${libname}_${libext}"'_\1,g'
-        if test "$module" = 'alloca'; then
-          echo "${libname}_${libext}_LIBADD += @${perhapsLT}ALLOCA@"
+  (
+    for module in $modules; do
+      func_verify_nontests_module
+      if test -n "$module"; then
+        {
+          func_get_automake_snippet "$module" |
+            sed -e 's,lib_LIBRARIES,lib%_LIBRARIES,g' \
+                -e 's,lib_LTLIBRARIES,lib%_LTLIBRARIES,g' |
+            sed -e "$sed_eliminate_LDFLAGS" |
+            sed -e 's,lib_\([A-Z][A-Z]*\),'"${libname}_${libext}"'_\1,g' |
+            sed -e 's,lib%_LIBRARIES,lib_LIBRARIES,g' \
+                -e 's,lib%_LTLIBRARIES,lib_LTLIBRARIES,g'
+          if test "$module" = 'alloca'; then
+            echo "${libname}_${libext}_LIBADD += @${perhapsLT}ALLOCA@"
+          fi
+        } > amsnippet.tmp
+        # Skip the contents if its entirely empty.
+        if grep '[^     ]' amsnippet.tmp > /dev/null ; then
+          echo "## begin gnulib module $module"
+          echo
+          cat amsnippet.tmp
+          echo "## end   gnulib module $module"
+          echo
         fi
-      } > amsnippet.tmp
-      # Skip the contents if its entirely empty.
-      if grep '[^      ]' amsnippet.tmp > /dev/null ; then
-        echo "## begin gnulib module $module"
-        echo
-        cat amsnippet.tmp
-        echo "## end   gnulib module $module"
-        echo
+        rm -f amsnippet.tmp
       fi
-      rm -f amsnippet.tmp
+    done
+  ) > allsnippets.tmp
+  if grep "^[a-zA-Z0-9_]*_${perhapsLT}LIBRARIES *= *$libname\\.$libext\$" allsnippets.tmp > /dev/null; then
+    # One of the snippets already specifies an installation location for the
+    # library. Don't confuse automake by saying it should not be installed.
+    :
+  else
+    # By default, the generated library should not be installed.
+    echo "noinst_${perhapsLT}LIBRARIES $assign $libname.$libext"
+  fi
+  echo
+  echo "${libname}_${libext}_SOURCES ="
+  # Here we use $(LIBOBJS), not @LIBOBJS@. The value is the same. However,
+  # automake during its analyses looks for $(LIBOBJS), not for @LIBOBJS@.
+  echo "${libname}_${libext}_LIBADD = \$(${perhapsLT}LIBOBJS)"
+  if test "$libtool" = true; then
+    echo "${libname}_${libext}_LDFLAGS = \$(AM_LDFLAGS)"
+  fi
+  if test -z "$makefile_name"; then
+    echo "noinst_HEADERS ="
+    # Automake versions < 1.9b create an empty pkgdatadir at installation time
+    # if you specify pkgdata_DATA to empty. This is a workaround.
+    if grep '^pkgdata_DATA *+=' allsnippets.tmp > /dev/null; then
+      echo "pkgdata_DATA ="
     fi
-  done
+    echo "EXTRA_DIST ="
+    echo "BUILT_SOURCES ="
+    echo "SUFFIXES ="
+  fi
+  echo "MOSTLYCLEANFILES $assign core *.stackdump"
+  if test -z "$makefile_name"; then
+    echo "MOSTLYCLEANDIRS ="
+    echo "CLEANFILES ="
+    echo "DISTCLEANFILES ="
+    echo "MAINTAINERCLEANFILES ="
+    echo
+    echo "AM_CPPFLAGS ="
+  fi
+  echo
+  cat allsnippets.tmp
   echo
-  echo "# Makefile.am ends here"
+  echo "mostlyclean-local: mostlyclean-generic"
+  echo "       @test -z \"\$(MOSTLYCLEANDIRS)\" || \\"
+  echo "         for dir in \$(MOSTLYCLEANDIRS); do \\"
+  echo "           if test -d \$\$dir; then \\"
+  echo "             echo \"rmdir \$\$dir\"; rmdir \$\$dir; \\"
+  echo "           fi; \\"
+  echo "         done"
+  rm -f allsnippets.tmp
 }
 
 # func_emit_tests_Makefile_am
-# emits the contents of tests/Makefile.am to standard output.
+# emits the contents of tests makefile to standard output.
 # Input:
+# - local_gnulib_dir  from --local-dir
 # - modules         list of modules, including dependencies
 # - libname         library name
-# - libtool         true if libtool will be used, blank otherwise
+# - makefile_name   from --makefile-name
+# - libtool         true if libtool will be used, false or blank otherwise
 # - sourcebase      relative directory containing lib source code
 # - m4base          relative directory containing autoconf macros
 # - testsbase       relative directory containing unit test code
 func_emit_tests_Makefile_am ()
 {
-  if test -n "$libtool"; then
+  if test "$libtool" = true; then
+    libext=la
+  else
+    libext=a
+  fi
+  if test "$libtool" = true; then
     libext=la
+    sed_eliminate_LDFLAGS=
   else
     libext=a
+    sed_eliminate_LDFLAGS='/^lib_LDFLAGS[       ]*+=/d'
   fi
   testsbase_inverse=`echo "$testsbase" | sed -e 's,/$,,' | sed -e 's,[^/][^/]*,..,g'`
+  echo "## DO NOT EDIT! GENERATED AUTOMATICALLY!"
   echo "## Process this file with automake to produce Makefile.in."
-  echo "# Copyright (C) 2004-2005 Free Software Foundation, Inc."
-  echo "#"
-  echo "# This file is free software, distributed under the terms of the GNU"
-  echo "# General Public License.  As a special exception to the GNU General"
-  echo "# Public License, this file may be distributed as part of a program"
-  echo "# that contains a configuration script generated by Automake, under"
-  echo "# the same distribution terms as the rest of that program."
-  echo "#"
-  echo "# Generated by gnulib-tool."
+  func_emit_copyright_notice
   echo
   # Generate dependencies here, since it eases the debugging of test failures.
   echo "AUTOMAKE_OPTIONS = 1.5 foreign"
   echo
   echo "ACLOCAL_AMFLAGS = -I ${testsbase_inverse}/${m4base}"
   echo
+  (
+    for module in $modules; do
+      func_verify_tests_module
+      if test -n "$module"; then
+        {
+          func_get_automake_snippet "$module" |
+            sed -e 's,lib_LIBRARIES,lib%_LIBRARIES,g' \
+                -e 's,lib_LTLIBRARIES,lib%_LTLIBRARIES,g' |
+            sed -e "$sed_eliminate_LDFLAGS" |
+            sed -e 's,lib_\([A-Z][A-Z]*\),'"${libname}_${libext}"'_\1,g' |
+            sed -e 's,lib%_LIBRARIES,lib_LIBRARIES,g' \
+                -e 's,lib%_LTLIBRARIES,lib_LTLIBRARIES,g'
+        } > amsnippet.tmp
+        # Skip the contents if its entirely empty.
+        if grep '[^     ]' amsnippet.tmp > /dev/null ; then
+          echo "## begin gnulib module $module"
+          echo
+          cat amsnippet.tmp
+          echo "## end   gnulib module $module"
+          echo
+        fi
+        rm -f amsnippet.tmp
+      fi
+    done
+  ) > allsnippets.tmp
+  # Nothing is being added to SUBDIRS; nevertheless the existence of this
+  # variable is needed to avoid an error from automake:
+  #   "AM_GNU_GETTEXT used but SUBDIRS not defined"
+  echo "SUBDIRS ="
   echo "TESTS ="
   echo "TESTS_ENVIRONMENT ="
   echo "noinst_PROGRAMS ="
+  echo "check_PROGRAMS ="
+  echo "noinst_HEADERS ="
+  if grep '^pkgdata_DATA *+=' allsnippets.tmp > /dev/null; then
+    echo "pkgdata_DATA ="
+  fi
   echo "EXTRA_DIST ="
   echo "BUILT_SOURCES ="
   echo "SUFFIXES ="
-  echo "MOSTLYCLEANFILES ="
+  echo "MOSTLYCLEANFILES = core *.stackdump"
+  echo "MOSTLYCLEANDIRS ="
   echo "CLEANFILES ="
   echo "DISTCLEANFILES ="
   echo "MAINTAINERCLEANFILES ="
@@ -766,62 +1262,67 @@ func_emit_tests_Makefile_am ()
   echo
   echo "LDADD = ${testsbase_inverse}/${sourcebase-lib}/${libname}.${libext}"
   echo
-  for module in $modules; do
-    func_verify_tests_module
-    if test -n "$module"; then
-      func_get_automake_snippet "$module" > amsnippet.tmp
-      # Skip the contents if its entirely empty.
-      if grep '[^      ]' amsnippet.tmp > /dev/null ; then
-        echo "## begin gnulib module $module"
-        echo
-        cat amsnippet.tmp
-        echo "## end   gnulib module $module"
-        echo
-      fi
-      rm -f amsnippet.tmp
-    fi
-  done
+  cat allsnippets.tmp
   echo "# Clean up after Solaris cc."
   echo "clean-local:"
   echo "       rm -rf SunWS_cache"
   echo
-  echo "# Makefile.am ends here"
+  echo "mostlyclean-local: mostlyclean-generic"
+  echo "       @test -z \"\$(MOSTLYCLEANDIRS)\" || \\"
+  echo "         for dir in \$(MOSTLYCLEANDIRS); do \\"
+  echo "           if test -d \$\$dir; then \\"
+  echo "             echo \"rmdir \$\$dir\"; rmdir \$\$dir; \\"
+  echo "           fi; \\"
+  echo "         done"
+  rm -f allsnippets.tmp
 }
 
 # func_import modules
 # Uses also the variables
 # - destdir         target directory
+# - local_gnulib_dir  from --local-dir
 # - libname         library name
 # - sourcebase      directory relative to destdir where to place source code
 # - m4base          directory relative to destdir where to place *.m4 macros
+# - docbase         directory relative to destdir where to place doc files
 # - testsbase       directory relative to destdir where to place unit test code
 # - auxdir          directory relative to destdir where to place build aux files
 # - inctests        true if --with-tests was given, blank otherwise
 # - avoidlist       list of modules to avoid, from --avoid
 # - lgpl            true if library's license shall be LGPL, blank otherwise
-# - libtool         true if libtool will be used, blank otherwise
-# - guessed_libtool true if the configure.ac file uses libtool, blank otherwise
+# - makefile_name   from --makefile-name
+# - libtool         true if --libtool was given, false if --no-libtool was
+#                   given, blank otherwise
+# - guessed_libtool true if the configure.ac file uses libtool, false otherwise
 # - macro_prefix    prefix of gl_EARLY, gl_INIT macros to use
+# - autoconf_minversion  minimum supported autoconf version
 # - doit            : if actions shall be executed, false if only to be printed
 # - symbolic        true if files should be symlinked, copied otherwise
 func_import ()
 {
   # Get the cached settings.
+  cached_local_gnulib_dir=
   cached_specified_modules=
   cached_avoidlist=
   cached_sourcebase=
   cached_m4base=
+  cached_docbase=
   cached_testsbase=
   cached_libname=
   cached_lgpl=
+  cached_makefile_name=
   cached_libtool=
   cached_macro_prefix=
   cached_files=
   if test -f "$destdir"/$m4base/gnulib-cache.m4; then
+    cached_libtool=false
     my_sed_traces='
       s,#.*$,,
       s,^dnl .*$,,
       s, dnl .*$,,
+      /gl_LOCAL_DIR(/ {
+        s,^.*gl_LOCAL_DIR([[ ]*\([^])]*\).*$,cached_local_gnulib_dir="\1",p
+      }
       /gl_MODULES(/ {
         s,^.*gl_MODULES([[ ]*\([^])]*\).*$,cached_specified_modules="\1",p
       }
@@ -834,6 +1335,9 @@ func_import ()
       /gl_M4_BASE(/ {
         s,^.*gl_M4_BASE([[ ]*\([^])]*\).*$,cached_m4base="\1",p
       }
+      /gl_DOC_BASE(/ {
+        s,^.*gl_DOC_BASE([[ ]*\([^])]*\).*$,cached_docbase="\1",p
+      }
       /gl_TESTS_BASE(/ {
         s,^.*gl_TESTS_BASE([[ ]*\([^])]*\).*$,cached_testsbase="\1",p
       }
@@ -843,6 +1347,9 @@ func_import ()
       /gl_LGPL/ {
         s,^.*$,cached_lgpl=true,p
       }
+      /gl_MAKEFILE_NAME(/ {
+        s,^.*gl_MAKEFILE_NAME([[ ]*\([^])]*\).*$,cached_makefile_name="\1",p
+      }
       /gl_LIBTOOL/ {
         s,^.*$,cached_libtool=true,p
       }
@@ -877,6 +1384,24 @@ func_import ()
   if test -n "$cached_m4base" && test "$cached_m4base" != "$m4base"; then
     func_fatal_error "$m4base/gnulib-cache.m4 is expected to contain gl_M4_BASE([$m4base])"
   fi
+  # The local_gnulib_dir defaults to the cached one. Recall that the cached one
+  # is relative to $destdir, whereas the one we use is relative to . or absolute.
+  if test -z "$local_gnulib_dir"; then
+    if test -n "$cached_local_gnulib_dir"; then
+      case "$destdir" in
+        /*)
+          local_gnulib_dir="$destdir/$cached_local_gnulib_dir" ;;
+        *)
+          case "$cached_local_gnulib_dir" in
+            /*)
+              local_gnulib_dir="$destdir/$cached_local_gnulib_dir" ;;
+            *)
+              func_relconcat "$destdir" "$cached_local_gnulib_dir"
+              local_gnulib_dir="$relconcat" ;;
+          esac ;;
+      esac
+    fi
+  fi
   # Append the cached and the specified module names. So that
   # "gnulib-tool --import foo" means to add the module foo.
   specified_modules="$cached_specified_modules $1"
@@ -890,6 +1415,13 @@ func_import ()
       func_fatal_error "missing --source-base option"
     fi
   fi
+  # The docbase defaults to the cached one.
+  if test -z "$docbase"; then
+    docbase="$cached_docbase"
+    if test -z "$docbase"; then
+      func_fatal_error "missing --doc-base option. --doc-base has been introduced on 2006-07-11; if your last invocation of 'gnulib-tool --import' is before that date, you need to run 'gnulib-tool --import' once, with a --doc-base option."
+    fi
+  fi
   # The testsbase defaults to the cached one.
   if test -z "$testsbase"; then
     testsbase="$cached_testsbase"
@@ -908,6 +1440,10 @@ func_import ()
   if test -z "$lgpl"; then
     lgpl="$cached_lgpl"
   fi
+  # The makefile_name defaults to the cached one.
+  if test -z "$makefile_name"; then
+    makefile_name="$cached_makefile_name"
+  fi
   # Use libtool if specified either way, or if guessed.
   if test -z "$libtool"; then
     if test -n "$cached_m4base"; then
@@ -925,7 +1461,7 @@ func_import ()
   fi
 
   # Canonicalize the list of specified modules.
-  specified_modules=`for m in $specified_modules; do echo $m; done | LC_ALL=C sort | LC_ALL=C uniq`
+  specified_modules=`for m in $specified_modules; do echo $m; done | LC_ALL=C sort -u`
 
   # Determine final module list.
   modules="$specified_modules"
@@ -933,17 +1469,40 @@ func_import ()
   echo "Module list with included dependencies:"
   echo "$modules" | sed -e 's/^/  /'
 
-  # If --lgpl, check the license of modules are compatible.
+  # Add the dummy module if needed.
+  func_modules_add_dummy
+
+  # If --lgpl, verify that the licenses of modules are compatible.
   if test -n "$lgpl"; then
     for module in $modules; do
       license=`func_get_license $module`
       case $license in
-        LGPL | 'public domain' | 'unlimited') ;;
+        LGPL | 'GPLed build tool') ;;
+        'public domain' | 'unlimited' | 'unmodifiable license text') ;;
         *) func_fatal_error "incompatible license on module $module: $license" ;;
       esac
     done
   fi
 
+  # Determine script to apply to imported library files.
+  sed_transform_lib_file=
+  for module in $modules; do
+    if test $module = config-h; then
+      # Assume config.h exists, and that -DHAVE_CONFIG_H is omitted.
+      sed_transform_lib_file=$sed_transform_lib_file'
+        s/^#ifdef[      ]*HAVE_CONFIG_H[        ]*$/#if 1/
+      '
+      break
+    fi
+  done
+  if test -n "$lgpl"; then
+    # Update license.
+    sed_transform_lib_file=$sed_transform_lib_file'
+      s/GNU General/GNU Lesser General/g
+      s/version 2\([ ,]\)/version 2.1\1/g
+    '
+  fi
+
   # Determine final file list.
   func_modules_to_filelist
   echo "File list:"
@@ -956,7 +1515,7 @@ func_import ()
   new_files="$files m4/gnulib-tool.m4"
   old_files="$cached_files"
   if test -f "$destdir"/$m4base/gnulib-tool.m4; then
-    old_files="$old_files m4/gnulib-tool.m4"
+    func_append old_files " m4/gnulib-tool.m4"
   fi
 
   # Create directories.
@@ -976,6 +1535,17 @@ func_import ()
       echo "Create directory $destdir/$m4base"
     fi
   fi
+  docfiles=`echo "$files" | sed -n -e 's,^doc/,,p'`
+  if test -n "$docfiles"; then
+    if test ! -d "$destdir/$docbase"; then
+      if $doit; then
+        echo "Creating directory $destdir/$docbase"
+        mkdir "$destdir/$docbase" || func_fatal_error "failed"
+      else
+        echo "Create directory $destdir/$docbase"
+      fi
+    fi
+  fi
   if test -n "$inctests"; then
     if test ! -d "$destdir/$testsbase"; then
       if $doit; then
@@ -995,32 +1565,52 @@ func_import ()
     fi
   fi
 
+  # func_dest_tmpfilename file
+  # determines the name of a temporary file (file is relative to destdir).
+  # Sets variable:
+  #   - tmpfile       absolute filename of the temporary file
+  func_dest_tmpfilename ()
+  {
+    if $doit; then
+      # Put the new contents of $file in a file in the same directory (needed
+      # to guarantee that an 'mv' to "$destdir/$file" works).
+      tmpfile="$destdir/$1.tmp"
+    else
+      # Put the new contents of $file in a file in a temporary directory
+      # (because the directory of "$file" might not exist).
+      tmpfile="$tmp"/`basename "$1"`.tmp
+    fi
+  }
+
   # Copy files or make symbolic links. Remove obsolete files.
-  func_tmpdir
-  trap 'rm -rf "$tmp"' 0 1 2 3 15
   delimiter='  '
-  for f in $old_files; do
-    case "$f" in
-      build-aux/*) g=`echo "$f" | sed -e "s,^build-aux/,$auxdir/,"` ;;
-      lib/*) g=`echo "$f" | sed -e "s,^lib/,$cached_sourcebase/,"` ;;
-      m4/*) g=`echo "$f" | sed -e "s,^m4/,$cached_m4base/,"` ;;
-      tests/*) g=`echo "$f" | sed -e "s,^tests/,$cached_testsbase/,"` ;;
-      *) g="$f" ;;
-    esac
-    echo "$g""$delimiter""$f"
-  done | LC_ALL=C sort > "$tmp"/old-files
-  for f in $new_files; do
-    case "$f" in
-      build-aux/*) g=`echo "$f" | sed -e "s,^build-aux/,$auxdir/,"` ;;
-      lib/*) g=`echo "$f" | sed -e "s,^lib/,$sourcebase/,"` ;;
-      m4/*) g=`echo "$f" | sed -e "s,^m4/,$m4base/,"` ;;
-      tests/*) g=`echo "$f" | sed -e "s,^tests/,$testsbase/,"` ;;
-      *) g="$f" ;;
-    esac
-    echo "$g""$delimiter""$f"
-  done | LC_ALL=C sort > "$tmp"/new-files
+  sed_rewrite_old_files="\
+    s,^build-aux/,$auxdir/,
+    s,^doc/,$cached_docbase/,
+    s,^lib/,$cached_sourcebase/,
+    s,^m4/,$cached_m4base/,
+    s,^tests/,$cached_testsbase/,"
+  sed_rewrite_new_files="\
+    s,^build-aux/,$auxdir/,
+    s,^doc/,$docbase/,
+    s,^lib/,$sourcebase/,
+    s,^m4/,$m4base/,
+    s,^tests/,$testsbase/,"
+  # Construct a table with 2 columns: rewritten-file-name original-file-name,
+  # representing the files according to the last gnulib-tool invocation.
+  for f in $old_files; do echo $f; done \
+    | sed -e "s,^.*\$,&$delimiter&," -e "$sed_rewrite_old_files" \
+    | LC_ALL=C sort \
+    > "$tmp"/old-files
+  # Construct a table with 2 columns: rewritten-file-name original-file-name,
+  # representing the files after this gnulib-tool invocation.
+  for f in $new_files; do echo $f; done \
+    | sed -e "s,^.*\$,&$delimiter&," -e "$sed_rewrite_new_files" \
+    | LC_ALL=C sort \
+    > "$tmp"/new-files
   # First the files that are in old-files, but not in new-files:
-  for g in `LC_ALL=C join -t"$delimiter" -v1 "$tmp"/old-files "$tmp"/new-files | sed -e 's,'"$delimiter"'.*,,'`; do
+  sed_take_first_column='s,'"$delimiter"'.*,,'
+  for g in `LC_ALL=C join -t"$delimiter" -v1 "$tmp"/old-files "$tmp"/new-files | sed -e "$sed_take_first_column"`; do
     # Remove the file. Do nothing if the user already removed it.
     if test -f "$destdir/$g"; then
       if $doit; then
@@ -1032,23 +1622,26 @@ func_import ()
     fi
   done
   # func_add_or_update handles a file that ought to be present afterwards.
-  # Uses parameters f, g, already_present.
+  # Uses parameters
+  # - f             the original file name
+  # - g             the rewritten file name
+  # - already_present  nonempty if the file already exists, empty otherwise
   func_add_or_update ()
   {
-    cp "$gnulib_dir/$f" "$destdir/$g.tmp" || func_fatal_error "failed"
-    if test -n "$lgpl"; then
-      # Update license.
+    func_dest_tmpfilename "$g"
+    func_lookup_file "$f"
+    cp "$lookedup_file" "$tmpfile" || func_fatal_error "failed"
+    if test -n "$sed_transform_lib_file"; then
       case "$f" in
         lib/*)
-          sed -e 's/GNU General/GNU Lesser General/g' \
-              -e 's/version 2\([ ,]\)/version 2.1\1/g' \
-            < "$gnulib_dir/$f" > "$destdir/$g.tmp" || func_fatal_error "failed"
+          sed -e "$sed_transform_lib_file" \
+            < "$lookedup_file" > "$tmpfile" || func_fatal_error "failed"
           ;;
       esac
     fi
     if test -f "$destdir/$g"; then
       # The file already exists.
-      if cmp "$destdir/$g" "$destdir/$g.tmp" > /dev/null; then
+      if cmp "$destdir/$g" "$tmpfile" > /dev/null; then
         : # The file has not changed.
       else
         # Replace the file.
@@ -1059,10 +1652,11 @@ func_import ()
             echo "Replacing file $g (non-gnulib code backuped in ${g}~) !!"
           fi
           mv -f "$destdir/$g" "$destdir/${g}~" || func_fatal_error "failed"
-          if test -n "$symbolic" && cmp "$gnulib_dir/$f" "$destdir/$g.tmp" > /dev/null; then
-            func_ln_if_changed "$gnulib_dir/$f" "$destdir/$g"
+          if test -n "$symbolic" && test -z "$lookedup_tmp" \
+             && cmp "$lookedup_file" "$tmpfile" > /dev/null; then
+            func_ln_if_changed "$lookedup_file" "$destdir/$g"
           else
-            mv -f "$destdir/$g.tmp" "$destdir/${g}" || func_fatal_error "failed"
+            mv -f "$tmpfile" "$destdir/${g}" || func_fatal_error "failed"
           fi
         else
           if test -n "$already_present"; then
@@ -1078,98 +1672,111 @@ func_import ()
       # frequently that developers don't put autogenerated files into CVS.
       if $doit; then
         echo "Copying file $g"
-        if test -n "$symbolic" && cmp "$gnulib_dir/$f" "$destdir/$g.tmp" > /dev/null; then
-          func_ln_if_changed "$gnulib_dir/$f" "$destdir/$g"
+        if test -n "$symbolic" && test -z "$lookedup_tmp" \
+           && cmp "$lookedup_file" "$tmpfile" > /dev/null; then
+          func_ln_if_changed "$lookedup_file" "$destdir/$g"
         else
-          mv -f "$destdir/$g.tmp" "$destdir/${g}" || func_fatal_error "failed"
+          mv -f "$tmpfile" "$destdir/${g}" || func_fatal_error "failed"
         fi
       else
         echo "Copy file $g"
       fi
     fi
-    rm -f "$destdir/$g.tmp"
+    rm -f "$tmpfile"
   }
   # Then the files that are in new-files, but not in old-files:
+  sed_take_last_column='s,^.*'"$delimiter"',,'
   already_present=
-  for f in `LC_ALL=C join -t"$delimiter" -v2 "$tmp"/old-files "$tmp"/new-files | sed -e 's,'^.*"$delimiter"',,'`; do
-    case "$f" in
-      build-aux/*) g=`echo "$f" | sed -e "s,^build-aux/,$auxdir/,"` ;;
-      lib/*) g=`echo "$f" | sed -e "s,^lib/,$sourcebase/,"` ;;
-      m4/*) g=`echo "$f" | sed -e "s,^m4/,$m4base/,"` ;;
-      tests/*) g=`echo "$f" | sed -e "s,^tests/,$testsbase/,"` ;;
-      *) g="$f" ;;
-    esac
-    func_add_or_update
-  done
+  LC_ALL=C join -t"$delimiter" -v2 "$tmp"/old-files "$tmp"/new-files \
+    | sed -e "$sed_take_last_column" \
+    | sed -e "s,^.*\$,&$delimiter&," -e "$sed_rewrite_new_files" > "$tmp"/added-files
+  { # Rearrange file descriptors. Needed because "while ... done < ..."
+    # constructs are executed in a subshell e.g. by Solaris 10 /bin/sh.
+    exec 5<&0 < "$tmp"/added-files
+    while read g f; do
+      func_add_or_update
+    done
+    exec 0<&5 5<&-
+  }
   # Then the files that are in new-files and in old-files:
   already_present=true
-  for f in `LC_ALL=C join -t"$delimiter" "$tmp"/old-files "$tmp"/new-files | sed -e 's,'^.*"$delimiter"',,'`; do
-    case "$f" in
-      build-aux/*) g=`echo "$f" | sed -e "s,^build-aux/,$auxdir/,"` ;;
-      lib/*) g=`echo "$f" | sed -e "s,^lib/,$sourcebase/,"` ;;
-      m4/*) g=`echo "$f" | sed -e "s,^m4/,$m4base/,"` ;;
-      tests/*) g=`echo "$f" | sed -e "s,^tests/,$testsbase/,"` ;;
-      *) g="$f" ;;
-    esac
-    func_add_or_update
-  done
-  rm -rf "$tmp"
-  trap - 0 1 2 3 15
+  LC_ALL=C join -t"$delimiter" "$tmp"/old-files "$tmp"/new-files \
+    | sed -e "$sed_take_last_column" \
+    | sed -e "s,^.*\$,&$delimiter&," -e "$sed_rewrite_new_files" > "$tmp"/kept-files
+  { # Rearrange file descriptors. Needed because "while ... done < ..."
+    # constructs are executed in a subshell e.g. by Solaris 10 /bin/sh.
+    exec 5<&0 < "$tmp"/kept-files
+    while read g f; do
+      func_add_or_update
+    done
+    exec 0<&5 5<&-
+  }
 
   # Command-line invocation printed in a comment in generated gnulib-cache.m4.
   actioncmd="gnulib-tool --import"
-  actioncmd="$actioncmd --dir=$destdir"
-  actioncmd="$actioncmd --lib=$libname"
-  actioncmd="$actioncmd --source-base=$sourcebase"
-  actioncmd="$actioncmd --m4-base=$m4base"
-  actioncmd="$actioncmd --aux-dir=$auxdir"
+  func_append actioncmd " --dir=$destdir"
+  if test -n "$local_gnulib_dir"; then
+    func_append actioncmd " --local-dir=$local_gnulib_dir"
+  fi
+  func_append actioncmd " --lib=$libname"
+  func_append actioncmd " --source-base=$sourcebase"
+  func_append actioncmd " --m4-base=$m4base"
+  func_append actioncmd " --doc-base=$docbase"
+  func_append actioncmd " --aux-dir=$auxdir"
   for module in $avoidlist; do
-    actioncmd="$actioncmd --avoid=$module"
+    func_append actioncmd " --avoid=$module"
   done
   if test -n "$lgpl"; then
-    actioncmd="$actioncmd --lgpl"
+    func_append actioncmd " --lgpl"
+  fi
+  if test -n "$makefile_name"; then
+    func_append actioncmd " --makefile_name=$makefile_name"
+  fi
+  if test "$libtool" = true; then
+    func_append actioncmd " --libtool"
+  else
+    func_append actioncmd " --no-libtool"
   fi
-  if test -n "$libtool"; then
-    actioncmd="$actioncmd --libtool"
+  func_append actioncmd " --macro-prefix=$macro_prefix"
+  func_append actioncmd " `echo $specified_modules`"
+
+  # Default the makefile name to Makefile.am.
+  if test -n "$makefile_name"; then
+    makefile_am=$makefile_name
+  else
+    makefile_am=Makefile.am
   fi
-  actioncmd="$actioncmd --macro-prefix=$macro_prefix"
-  actioncmd="$actioncmd `echo $specified_modules`"
-
-  # Create lib/Makefile.am.
-  func_emit_lib_Makefile_am > "$destdir"/$sourcebase/Makefile.am.tmp
-  if test -f "$destdir"/$sourcebase/Makefile.am; then
-    if cmp "$destdir"/$sourcebase/Makefile.am "$destdir"/$sourcebase/Makefile.am.tmp > /dev/null; then
-      rm -f "$destdir"/$sourcebase/Makefile.am.tmp
+
+  # Create library makefile.
+  func_dest_tmpfilename $sourcebase/$makefile_am
+  func_emit_lib_Makefile_am > "$tmpfile"
+  if test -f "$destdir"/$sourcebase/$makefile_am; then
+    if cmp "$destdir"/$sourcebase/$makefile_am "$tmpfile" > /dev/null; then
+      rm -f "$tmpfile"
     else
       if $doit; then
-        echo "Updating $sourcebase/Makefile.am (backup in $sourcebase/Makefile.am~)"
-        mv -f "$destdir"/$sourcebase/Makefile.am "$destdir"/$sourcebase/Makefile.am~
-        mv -f "$destdir"/$sourcebase/Makefile.am.tmp "$destdir"/$sourcebase/Makefile.am
+        echo "Updating $sourcebase/$makefile_am (backup in $sourcebase/$makefile_am~)"
+        mv -f "$destdir"/$sourcebase/$makefile_am "$destdir"/$sourcebase/$makefile_am~
+        mv -f "$tmpfile" "$destdir"/$sourcebase/$makefile_am
       else
-        echo "Update $sourcebase/Makefile.am (backup in $sourcebase/Makefile.am~)"
-        rm -f "$destdir"/$sourcebase/Makefile.am.tmp
+        echo "Update $sourcebase/$makefile_am (backup in $sourcebase/$makefile_am~)"
+        rm -f "$tmpfile"
       fi
     fi
   else
     if $doit; then
-      echo "Creating $sourcebase/Makefile.am"
-      mv -f "$destdir"/$sourcebase/Makefile.am.tmp "$destdir"/$sourcebase/Makefile.am
+      echo "Creating $sourcebase/$makefile_am"
+      mv -f "$tmpfile" "$destdir"/$sourcebase/$makefile_am
     else
-      echo "Create $sourcebase/Makefile.am"
-      rm -f "$destdir"/$sourcebase/Makefile.am.tmp
+      echo "Create $sourcebase/$makefile_am"
+      rm -f "$tmpfile"
     fi
   fi
 
   # Create m4/gnulib-cache.m4.
+  func_dest_tmpfilename $m4base/gnulib-cache.m4
   (
-    echo "# Copyright (C) 2004 Free Software Foundation, Inc."
-    echo "# This file is free software, distributed under the terms of the GNU"
-    echo "# General Public License.  As a special exception to the GNU General"
-    echo "# Public License, this file may be distributed as part of a program"
-    echo "# that contains a configuration script generated by Autoconf, under"
-    echo "# the same distribution terms as the rest of that program."
-    echo "#"
-    echo "# Generated by gnulib-tool."
+    func_emit_copyright_notice
     echo "#"
     echo "# This file represents the specification of how gnulib-tool is used."
     echo "# It acts as a cache: It is written and read by gnulib-tool."
@@ -1181,55 +1788,68 @@ func_import ()
     echo "#   $actioncmd"
     echo
     echo "# Specification in the form of a few gnulib-tool.m4 macro invocations:"
+    # Store the local_gnulib_dir relative to destdir.
+    case "$local_gnulib_dir" in
+      "" | /*)
+        relative_local_gnulib_dir="$local_gnulib_dir" ;;
+      * )
+        case "$destdir" in
+          /*) relative_local_gnulib_dir="$local_gnulib_dir" ;;
+          *)
+            # destdir, local_gnulib_dir are both relative.
+            func_relativize "$destdir" "$local_gnulib_dir"
+            relative_local_gnulib_dir="$reldir" ;;
+        esac ;;
+    esac
+    echo "gl_LOCAL_DIR([$relative_local_gnulib_dir])"
     echo "gl_MODULES(["`echo $specified_modules`"])"
     echo "gl_AVOID([$avoidlist])"
     echo "gl_SOURCE_BASE([$sourcebase])"
     echo "gl_M4_BASE([$m4base])"
+    echo "gl_DOC_BASE([$docbase])"
     echo "gl_TESTS_BASE([$testsbase])"
     echo "gl_LIB([$libname])"
     test -z "$lgpl" || echo "gl_LGPL"
-    test -z "$libtool" || echo "gl_LIBTOOL"
+    echo "gl_MAKEFILE_NAME([$makefile_name])"
+    if test "$libtool" = true; then
+      echo "gl_LIBTOOL"
+    fi
     echo "gl_MACRO_PREFIX([$macro_prefix])"
-  ) > "$destdir"/$m4base/gnulib-cache.m4.tmp
+  ) > "$tmpfile"
   if test -f "$destdir"/$m4base/gnulib-cache.m4; then
-    if cmp "$destdir"/$m4base/gnulib-cache.m4 "$destdir"/$m4base/gnulib-cache.m4.tmp > /dev/null; then
-      rm -f "$destdir"/$m4base/gnulib-cache.m4.tmp
+    if cmp "$destdir"/$m4base/gnulib-cache.m4 "$tmpfile" > /dev/null; then
+      rm -f "$tmpfile"
     else
       if $doit; then
         echo "Updating $m4base/gnulib-cache.m4 (backup in $m4base/gnulib-cache.m4~)"
         mv -f "$destdir"/$m4base/gnulib-cache.m4 "$destdir"/$m4base/gnulib-cache.m4~
-        mv -f "$destdir"/$m4base/gnulib-cache.m4.tmp "$destdir"/$m4base/gnulib-cache.m4
+        mv -f "$tmpfile" "$destdir"/$m4base/gnulib-cache.m4
       else
         echo "Update $m4base/gnulib-cache.m4 (backup in $m4base/gnulib-cache.m4~)"
         if false; then
-          cat "$destdir"/$m4base/gnulib-cache.m4.tmp
+          cat "$tmpfile"
           echo
           echo "# gnulib-cache.m4 ends here"
         fi
-        rm -f "$destdir"/$m4base/gnulib-cache.m4.tmp
+        rm -f "$tmpfile"
       fi
     fi
   else
     if $doit; then
       echo "Creating $m4base/gnulib-cache.m4"
-      mv -f "$destdir"/$m4base/gnulib-cache.m4.tmp "$destdir"/$m4base/gnulib-cache.m4
+      mv -f "$tmpfile" "$destdir"/$m4base/gnulib-cache.m4
     else
       echo "Create $m4base/gnulib-cache.m4"
-      cat "$destdir"/$m4base/gnulib-cache.m4.tmp
-      rm -f "$destdir"/$m4base/gnulib-cache.m4.tmp
+      cat "$tmpfile"
+      rm -f "$tmpfile"
     fi
   fi
 
   # Create m4/gnulib-comp.m4.
+  func_dest_tmpfilename $m4base/gnulib-comp.m4
   (
-    echo "# Copyright (C) 2004 Free Software Foundation, Inc."
-    echo "# This file is free software, distributed under the terms of the GNU"
-    echo "# General Public License.  As a special exception to the GNU General"
-    echo "# Public License, this file may be distributed as part of a program"
-    echo "# that contains a configuration script generated by Autoconf, under"
-    echo "# the same distribution terms as the rest of that program."
-    echo "#"
-    echo "# Generated by gnulib-tool."
+    echo "# DO NOT EDIT! GENERATED AUTOMATICALLY!"
+    func_emit_copyright_notice
     echo "#"
     echo "# This file represents the compiled summary of the specification in"
     echo "# gnulib-cache.m4. It lists the computed macro invocations that need"
@@ -1242,28 +1862,53 @@ func_import ()
     echo "# any checks for libraries, header files, types and library functions."
     echo "AC_DEFUN([${macro_prefix}_EARLY],"
     echo "["
-    if grep AC_GNU_SOURCE "$destdir"/$m4base/*.m4 > /dev/null; then
+    echo "  m4_pattern_forbid([^gl_[A-Z]])dnl the gnulib macro namespace"
+    echo "  m4_pattern_allow([^gl_ES$])dnl a valid locale name"
+    echo "  AC_REQUIRE([AC_PROG_RANLIB])"
+    if grep AC_GNU_SOURCE "$destdir"/$m4base/*.m4 >/dev/null 2>/dev/null; then
       echo "  AC_REQUIRE([AC_GNU_SOURCE])"
     fi
-    if grep gl_USE_SYSTEM_EXTENSIONS "$destdir"/$m4base/*.m4 > /dev/null; then
+    if grep gl_USE_SYSTEM_EXTENSIONS "$destdir"/$m4base/*.m4 >/dev/null 2>/dev/null; then
       echo "  AC_REQUIRE([gl_USE_SYSTEM_EXTENSIONS])"
     fi
+    if grep gl_LOCK "$destdir"/$m4base/*.m4 >/dev/null 2>/dev/null; then
+      echo "  AC_REQUIRE([gl_LOCK_EARLY])"
+    fi
     echo "])"
     echo
     echo "# This macro should be invoked from $configure_ac, in the section"
     echo "# \"Check for header files, types and library functions\"."
     echo "AC_DEFUN([${macro_prefix}_INIT],"
     echo "["
-    if test -z "$libtool"; then
-      echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [false])"
+    if test "$libtool" = true; then
+      echo "  AM_CONDITIONAL([GL_COND_LIBTOOL], [true])"
+      echo "  gl_cond_libtool=true"
+    else
+      echo "  AM_CONDITIONAL([GL_COND_LIBTOOL], [false])"
+      echo "  gl_cond_libtool=false"
+      echo "  gl_libdeps="
+      echo "  gl_ltlibdeps="
+    fi
+    echo "  gl_source_base='$sourcebase'"
+    if test "$auxdir" != "build-aux"; then
+      sed_replace_build_aux='
+        :a
+        /AC_CONFIG_FILES(.*:build-aux\/.*)/{
+          s|AC_CONFIG_FILES(\(.*\):build-aux/\(.*\))|AC_CONFIG_FILES(\1:'"$auxdir"'/\2)|
+          ba
+        }'
+      sed_replace_build_aux=`echo "$sed_replace_build_aux" | sed -e 1d -e 's/^ *//'`
     else
-      echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [true])"
+      sed_replace_build_aux=
     fi
     for module in $modules; do
       func_verify_module
       if test -n "$module"; then
-        func_get_autoconf_snippet "$module" | sed -e '/^$/d;' -e 's/^/  /' -e 's/AM_GNU_GETTEXT(\[external\])/dnl you must add AM_GNU_GETTEXT([external]) or similar to configure.ac./'
-        if test "$module" = 'alloca' && test -n "$libtool"; then
+        func_get_autoconf_snippet "$module" \
+          | sed -e '/^$/d;' -e 's/^/  /' \
+                -e 's/AM_GNU_GETTEXT(\[external\])/dnl you must add AM_GNU_GETTEXT([external]) or similar to configure.ac./' \
+                -e "$sed_replace_build_aux"
+        if test "$module" = 'alloca' && test "$libtool" = true; then
           echo 'changequote(,)dnl'
           echo 'LTALLOCA=`echo "$ALLOCA" | sed '"'"'s/\.[^.]* /.lo /g;s/\.[^.]*$/.lo/'"'"'`'
           echo 'changequote([, ])dnl'
@@ -1271,6 +1916,15 @@ func_import ()
         fi
       fi
     done
+    # _LIBDEPS and _LTLIBDEPS variables are not needed if this library is
+    # created using libtool, because libtool already handles the dependencies.
+    if test "$libtool" != true; then
+      libname_upper=`echo "$libname" | tr 'a-z' 'A-Z'`
+      echo "  ${libname_upper}_LIBDEPS=\"\$gl_libdeps\""
+      echo "  AC_SUBST([${libname_upper}_LIBDEPS])"
+      echo "  ${libname_upper}_LTLIBDEPS=\"\$gl_ltlibdeps\""
+      echo "  AC_SUBST([${libname_upper}_LTLIBDEPS])"
+    fi
     echo "])"
     echo
     echo "# This macro records the list of files which have been installed by"
@@ -1278,59 +1932,60 @@ func_import ()
     echo "AC_DEFUN([${macro_prefix}_FILE_LIST], ["
     echo "$files" | sed -e 's,^,  ,'
     echo "])"
-  ) > "$destdir"/$m4base/gnulib-comp.m4.tmp
+  ) > "$tmpfile"
   if test -f "$destdir"/$m4base/gnulib-comp.m4; then
-    if cmp "$destdir"/$m4base/gnulib-comp.m4 "$destdir"/$m4base/gnulib-comp.m4.tmp > /dev/null; then
-      rm -f "$destdir"/$m4base/gnulib-comp.m4.tmp
+    if cmp "$destdir"/$m4base/gnulib-comp.m4 "$tmpfile" > /dev/null; then
+      rm -f "$tmpfile"
     else
       if $doit; then
         echo "Updating $m4base/gnulib-comp.m4 (backup in $m4base/gnulib-comp.m4~)"
         mv -f "$destdir"/$m4base/gnulib-comp.m4 "$destdir"/$m4base/gnulib-comp.m4~
-        mv -f "$destdir"/$m4base/gnulib-comp.m4.tmp "$destdir"/$m4base/gnulib-comp.m4
+        mv -f "$tmpfile" "$destdir"/$m4base/gnulib-comp.m4
       else
         echo "Update $m4base/gnulib-comp.m4 (backup in $m4base/gnulib-comp.m4~)"
         if false; then
-          cat "$destdir"/$m4base/gnulib-comp.m4.tmp
+          cat "$tmpfile"
           echo
           echo "# gnulib-comp.m4 ends here"
         fi
-        rm -f "$destdir"/$m4base/gnulib-comp.m4.tmp
+        rm -f "$tmpfile"
       fi
     fi
   else
     if $doit; then
       echo "Creating $m4base/gnulib-comp.m4"
-      mv -f "$destdir"/$m4base/gnulib-comp.m4.tmp "$destdir"/$m4base/gnulib-comp.m4
+      mv -f "$tmpfile" "$destdir"/$m4base/gnulib-comp.m4
     else
       echo "Create $m4base/gnulib-comp.m4"
-      cat "$destdir"/$m4base/gnulib-comp.m4.tmp
-      rm -f "$destdir"/$m4base/gnulib-comp.m4.tmp
+      cat "$tmpfile"
+      rm -f "$tmpfile"
     fi
   fi
 
   if test -n "$inctests"; then
-    # Create tests/Makefile.am.
-    func_emit_tests_Makefile_am > "$destdir"/$testsbase/Makefile.am.tmp
-    if test -f "$destdir"/$testsbase/Makefile.am; then
-      if cmp "$destdir"/$testsbase/Makefile.am "$destdir"/$testsbase/Makefile.am.tmp > /dev/null; then
-        rm -f "$destdir"/$testsbase/Makefile.am.tmp
+    # Create tests makefile.
+    func_dest_tmpfilename $testsbase/$makefile_am
+    func_emit_tests_Makefile_am > "$tmpfile"
+    if test -f "$destdir"/$testsbase/$makefile_am; then
+      if cmp "$destdir"/$testsbase/$makefile_am "$tmpfile" > /dev/null; then
+        rm -f "$tmpfile"
       else
         if $doit; then
-          echo "Updating $testsbase/Makefile.am (backup in $testsbase/Makefile.am~)"
-          mv -f "$destdir"/$testsbase/Makefile.am "$destdir"/$testsbase/Makefile.am~
-          mv -f "$destdir"/$testsbase/Makefile.am.tmp "$destdir"/$testsbase/Makefile.am
+          echo "Updating $testsbase/$makefile_am (backup in $testsbase/$makefile_am~)"
+          mv -f "$destdir"/$testsbase/$makefile_am "$destdir"/$testsbase/$makefile_am~
+          mv -f "$tmpfile" "$destdir"/$testsbase/$makefile_am
         else
-          echo "Update $testsbase/Makefile.am (backup in $testsbase/Makefile.am~)"
-          rm -f "$destdir"/$testsbase/Makefile.am.tmp
+          echo "Update $testsbase/$makefile_am (backup in $testsbase/$makefile_am~)"
+          rm -f "$tmpfile"
         fi
       fi
     else
       if $doit; then
-        echo "Creating $testsbase/Makefile.am"
-        mv -f "$destdir"/$testsbase/Makefile.am.tmp "$destdir"/$testsbase/Makefile.am
+        echo "Creating $testsbase/$makefile_am"
+        mv -f "$tmpfile" "$destdir"/$testsbase/$makefile_am
       else
-        echo "Create $testsbase/Makefile.am"
-        rm -f "$destdir"/$testsbase/Makefile.am.tmp
+        echo "Create $testsbase/$makefile_am"
+        rm -f "$tmpfile"
       fi
     fi
   fi
@@ -1338,22 +1993,53 @@ func_import ()
   echo "Finished."
   echo
   echo "You may need to add #include directives for the following .h files."
+  # First the #include <...> directives without #ifs, sorted for convenience,
+  # then the #include "..." directives without #ifs, sorted for convenience,
+  # then the #include directives that are surrounded by #ifs. Not sorted.
   for module in $modules; do
-    func_get_include_directive "$module"
-  done | LC_ALL=C sort -u | sed -e '/^$/d;' -e 's/^/  /'
+    include_directive=`func_get_include_directive "$module"`
+    case "$nl$include_directive" in
+      *"$nl#if"*)
+        echo "$include_directive" 1>&5
+        ;;
+      *)
+        echo "$include_directive" | grep -v 'include "' 1>&6
+        echo "$include_directive" | grep 'include "' 1>&7
+        ;;
+    esac
+  done 5> "$tmp"/include-if 6> "$tmp"/include-angles 7> "$tmp"/include-quotes
+  (
+   LC_ALL=C sort -u "$tmp"/include-angles
+   LC_ALL=C sort -u "$tmp"/include-quotes
+   cat "$tmp"/include-if
+  ) | sed -e '/^$/d' -e 's/^/  /'
+  rm -f "$tmp"/include-angles "$tmp"/include-quotes "$tmp"/include-if
+
   echo
   echo "Don't forget to"
-  echo "  - add \"$sourcebase/Makefile\" to AC_CONFIG_FILES in $configure_ac,"
+  if test "$makefile_am" = Makefile.am; then
+    echo "  - add \"$sourcebase/Makefile\" to AC_CONFIG_FILES in $configure_ac,"
+  else
+    echo "  - \"include $makefile_name\" from within \"$sourcebase/Makefile.am\","
+  fi
   if test -n "$inctests"; then
-    echo "  - add \"$testsbase/Makefile\" to AC_CONFIG_FILES in $configure_ac,"
+    if test "$makefile_am" = Makefile.am; then
+      echo "  - add \"$testsbase/Makefile\" to AC_CONFIG_FILES in $configure_ac,"
+    else
+      echo "  - \"include $makefile_name\" from within \"$testsbase/Makefile.am\","
+    fi
+  fi
+  if test "$makefile_am" = Makefile.am; then
+    sourcebase_dir=`echo "$sourcebase" | sed -n -e 's,/[^/]*$,/,p'`
+    sourcebase_base=`basename "$sourcebase"`
+    echo "  - mention \"${sourcebase_base}\" in SUBDIRS in ${sourcebase_dir}Makefile.am,"
   fi
-  sourcebase_dir=`echo "$sourcebase" | sed -n -e 's,/[^/]*$,/,p'`
-  sourcebase_base=`basename "$sourcebase"`
-  echo "  - mention \"${sourcebase_base}\" in SUBDIRS in ${sourcebase_dir}Makefile.am,"
   if test -n "$inctests"; then
-    testsbase_dir=`echo "$testsbase" | sed -n -e 's,/[^/]*$,/,p'`
-    testsbase_base=`basename "$testsbase"`
-    echo "  - mention \"${testsbase_base}\" in SUBDIRS in ${testsbase_dir}Makefile.am,"
+    if test "$makefile_am" = Makefile.am; then
+      testsbase_dir=`echo "$testsbase" | sed -n -e 's,/[^/]*$,/,p'`
+      testsbase_base=`basename "$testsbase"`
+      echo "  - mention \"${testsbase_base}\" in SUBDIRS in ${testsbase_dir}Makefile.am,"
+    fi
   fi
   echo "  - mention \"-I ${m4base}\" in ACLOCAL_AMFLAGS in Makefile.am,"
   echo "  - invoke ${macro_prefix}_EARLY in $configure_ac, right after AC_PROG_CC,"
@@ -1362,18 +2048,28 @@ func_import ()
 
 # func_create_testdir testdir modules
 # Input:
+# - local_gnulib_dir  from --local-dir
 # - auxdir          directory relative to destdir where to place build aux files
 func_create_testdir ()
 {
   testdir="$1"
   modules="$2"
-  modules=`for m in $modules; do echo $m; done | LC_ALL=C sort | LC_ALL=C uniq`
+  modules=`for m in $modules; do echo $m; done | LC_ALL=C sort -u`
+
+  # Subdirectory names.
+  sourcebase=gllib
+  m4base=glm4
+  docbase=gldoc
+  testsbase=gltests
 
   # Determine final module list.
   func_modules_transitive_closure
   echo "Module list with included dependencies:"
   echo "$modules" | sed -e 's/^/  /'
 
+  # Add the dummy module if needed.
+  func_modules_add_dummy
+
   # Determine final file list.
   func_modules_to_filelist
   echo "File list:"
@@ -1381,33 +2077,53 @@ func_create_testdir ()
 
   # Create directories.
   for d in `echo "$files" | sed -n -e 's,^\(.*\)/[^/]*,\1,p'`; do
-    if test "$d" = build-aux; then
-      mkdir -p "$testdir/$auxdir"
-    else
-      mkdir -p "$testdir/$d"
-    fi
+    case "$d" in
+      build-aux) mkdir -p "$testdir/$auxdir" ;;
+      doc)       mkdir -p "$testdir/$docbase" ;;
+      lib)       mkdir -p "$testdir/$sourcebase" ;;
+      m4)        mkdir -p "$testdir/$m4base" ;;
+      tests)     mkdir -p "$testdir/$testsbase" ;;
+      *)         mkdir -p "$testdir/$d" ;;
+    esac
   done
 
   # Copy files or make symbolic links.
-  for f in $files; do
-    case "$f" in
-      build-aux/*) g=`echo "$f" | sed -e "s,^build-aux/,$auxdir/,"` ;;
-      *) g="$f" ;;
-    esac
-    ln "$gnulib_dir/$f" "$testdir/$g" 2>/dev/null ||
-    if test -z "$symbolic"; then
-      cp -p "$gnulib_dir/$f" "$testdir/$g"
-    else
-      ln -s "$gnulib_dir/$f" "$testdir/$g"
-    fi
-  done
+  delimiter='  '
+  sed_rewrite_files="\
+    s,^build-aux/,$auxdir/,
+    s,^doc/,$docbase/,
+    s,^lib/,$sourcebase/,
+    s,^m4/,$m4base/,
+    s,^tests/,$testsbase/,"
+  for f in $files; do echo $f; done \
+    | sed -e "s,^.*\$,&$delimiter&," -e "$sed_rewrite_files" \
+    | LC_ALL=C sort \
+    > "$tmp"/files
+  { # Rearrange file descriptors. Needed because "while ... done < ..."
+    # constructs are executed in a subshell e.g. by Solaris 10 /bin/sh.
+    exec 5<&0 < "$tmp"/files
+    while read g f; do
+      func_lookup_file "$f"
+      if test -n "$lookedup_tmp"; then
+        cp -p "$lookedup_file" "$testdir/$g"
+      else
+        ln "$lookedup_file" "$testdir/$g" 2>/dev/null ||
+        if test -z "$symbolic"; then
+          cp -p "$lookedup_file" "$testdir/$g"
+        else
+          ln -s "$lookedup_file" "$testdir/$g"
+        fi
+      fi
+    done
+    exec 0<&5 5<&-
+  }
 
-  # Create lib/Makefile.am.
-  mkdir -p "$testdir/lib"
-  func_emit_lib_Makefile_am > "$testdir/lib/Makefile.am"
+  # Create $sourcebase/Makefile.am.
+  mkdir -p "$testdir/$sourcebase"
+  func_emit_lib_Makefile_am > "$testdir/$sourcebase/Makefile.am"
 
-  # Create m4/Makefile.am.
-  mkdir -p "$testdir/m4"
+  # Create $m4base/Makefile.am.
+  mkdir -p "$testdir/$m4base"
   (echo "## Process this file with automake to produce Makefile.in."
    echo
    echo "EXTRA_DIST ="
@@ -1417,28 +2133,25 @@ func_create_testdir ()
          echo "EXTRA_DIST += "`echo "$f" | sed -e 's,^m4/,,'` ;;
      esac
    done
-  ) > "$testdir/m4/Makefile.am"
+  ) > "$testdir/$m4base/Makefile.am"
 
-  subdirs="lib m4"
+  subdirs="$sourcebase $m4base"
   subdirs_with_configure_ac=""
 
-  if test -f "$testdir"/m4/gettext.m4; then
+  if test -f "$testdir"/$m4base/gettext.m4; then
     # Avoid stupid error message from automake:
     # "AM_GNU_GETTEXT used but `po' not in SUBDIRS"
     mkdir -p "$testdir/po"
     (echo "## Process this file with automake to produce Makefile.in."
     ) > "$testdir/po/Makefile.am"
-    subdirs="$subdirs po"
+    func_append subdirs " po"
   fi
 
   if test -n "$inctests"; then
-    test -d "$testdir/tests" || mkdir "$testdir/tests"
-    # Create tests/Makefile.am.
-    sourcebase=lib
-    m4base=m4
-    testsbase=tests
-    func_emit_tests_Makefile_am > "$testdir/tests/Makefile.am"
-    # Create tests/configure.ac.
+    test -d "$testdir/$testsbase" || mkdir "$testdir/$testsbase"
+    # Create $testsbase/Makefile.am.
+    func_emit_tests_Makefile_am > "$testdir/$testsbase/Makefile.am"
+    # Create $testsbase/configure.ac.
     (echo "# Process this file with autoconf to produce a configure script."
      echo "AC_INIT([dummy], [0])"
      echo "AC_CONFIG_AUX_DIR([../$auxdir])"
@@ -1451,18 +2164,46 @@ func_create_testdir ()
      echo "AC_PROG_MAKE_SET"
      echo "AC_PROG_RANLIB"
      echo
-     if grep AC_GNU_SOURCE "$testdir"/m4/*.m4 > /dev/null; then
+     if grep AC_GNU_SOURCE "$testdir/$m4base"/*.m4 >/dev/null 2>/dev/null; then
        echo "AC_GNU_SOURCE"
        echo
      fi
-     if grep gl_USE_SYSTEM_EXTENSIONS "$testdir"/m4/*.m4 > /dev/null; then
+     if grep gl_USE_SYSTEM_EXTENSIONS "$testdir/$m4base"/*.m4 >/dev/null 2>/dev/null; then
        echo "gl_USE_SYSTEM_EXTENSIONS"
        echo
      fi
-     if test -z "$libtool"; then
+     if grep gl_LOCK "$testdir/$m4base"/*.m4 >/dev/null 2>/dev/null; then
+       echo "gl_LOCK_EARLY"
+       echo
+     fi
+     if test "$libtool" = true; then
+       echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [true])"
+       echo "gl_cond_libtool=true"
+     else
        echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [false])"
+       echo "gl_cond_libtool=false"
+       echo "gl_libdeps="
+       echo "gl_ltlibdeps="
+     fi
+     echo "gl_source_base='$testsbase'"
+     # Wrap the set of autoconf snippets into an autoconf macro that is then
+     # invoked. This is needed because autoconf does not support AC_REQUIRE
+     # at the top level:
+     #   error: AC_REQUIRE(gt_CSHARPCOMP): cannot be used outside of an AC_DEFUN'd macro
+     # but we want the AC_REQUIRE to have its normal meaning (provide one
+     # expansion of the required macro before the current point, and only one
+     # expansion total).
+     echo "AC_DEFUN([gl_INIT], ["
+     if test "$auxdir" != "build-aux"; then
+       sed_replace_build_aux='
+         :a
+         /AC_CONFIG_FILES(.*:build-aux\/.*)/{
+           s|AC_CONFIG_FILES(\(.*\):build-aux/\(.*\))|AC_CONFIG_FILES(\1:../'"$auxdir"'/\2)|
+           ba
+         }'
+       sed_replace_build_aux=`echo "$sed_replace_build_aux" | sed -e 1d -e 's/^ *//'`
      else
-       echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [true])"
+       sed_replace_build_aux=
      fi
      # We don't have explicit ordering constraints between the various
      # autoconf snippets. It's cleanest to put those of the library before
@@ -1470,24 +2211,37 @@ func_create_testdir ()
      for module in $modules; do
        func_verify_nontests_module
        if test -n "$module"; then
-         func_get_autoconf_snippet "$module"
+         func_get_autoconf_snippet "$module" \
+           | sed -e "$sed_replace_build_aux"
        fi
      done
      for module in $modules; do
        func_verify_tests_module
        if test -n "$module"; then
-         func_get_autoconf_snippet "$module"
+         func_get_autoconf_snippet "$module" \
+           | sed -e "$sed_replace_build_aux"
        fi
      done
+     # _LIBDEPS and _LTLIBDEPS variables are not needed if this library is
+     # created using libtool, because libtool already handles the dependencies.
+     if test "$libtool" != true; then
+       libname_upper=`echo "$libname" | tr 'a-z' 'A-Z'`
+       echo "  ${libname_upper}_LIBDEPS=\"\$gl_libdeps\""
+       echo "  AC_SUBST([${libname_upper}_LIBDEPS])"
+       echo "  ${libname_upper}_LTLIBDEPS=\"\$gl_ltlibdeps\""
+       echo "  AC_SUBST([${libname_upper}_LTLIBDEPS])"
+     fi
+     echo "])"
+     echo "gl_INIT"
      echo
-     # Usually tests/config.h will be a superset of config.h. Verify this by
-     # "merging" config.h into tests/config.h; look out for gcc warnings.
+     # Usually $testsbase/config.h will be a superset of config.h. Verify this
+     # by "merging" config.h into $testsbase/config.h; look out for gcc warnings.
      echo "AH_TOP([#include \"../config.h\"])"
      echo
      echo "AC_OUTPUT([Makefile])"
-    ) > "$testdir/tests/configure.ac"
-    subdirs="$subdirs tests"
-    subdirs_with_configure_ac="$subdirs_with_configure_ac tests"
+    ) > "$testdir/$testsbase/configure.ac"
+    func_append subdirs " $testsbase"
+    subdirs_with_configure_ac="$subdirs_with_configure_ac $testsbase"
   fi
 
   # Create Makefile.am.
@@ -1497,7 +2251,7 @@ func_create_testdir ()
    echo
    echo "SUBDIRS = $subdirs"
    echo
-   echo "ACLOCAL_AMFLAGS = -I m4"
+   echo "ACLOCAL_AMFLAGS = -I $m4base"
   ) > "$testdir/Makefile.am"
 
   # Create configure.ac.
@@ -1513,27 +2267,71 @@ func_create_testdir ()
    echo "AC_PROG_CC"
    echo "AC_PROG_INSTALL"
    echo "AC_PROG_MAKE_SET"
+   echo
+   echo "m4_pattern_forbid([^gl_[A-Z]])dnl the gnulib macro namespace"
+   echo "m4_pattern_allow([^gl_ES$])dnl a valid locale name"
+   echo
    echo "AC_PROG_RANLIB"
    echo
-   if grep AC_GNU_SOURCE "$testdir"/m4/*.m4 > /dev/null; then
+   if grep AC_GNU_SOURCE "$testdir/$m4base"/*.m4 >/dev/null 2>/dev/null; then
      echo "AC_GNU_SOURCE"
      echo
    fi
-   if grep gl_USE_SYSTEM_EXTENSIONS "$testdir"/m4/*.m4 > /dev/null; then
+   if grep gl_USE_SYSTEM_EXTENSIONS "$testdir/$m4base"/*.m4 >/dev/null 2>/dev/null; then
      echo "gl_USE_SYSTEM_EXTENSIONS"
      echo
    fi
-   if test -z "$libtool"; then
+   if grep gl_LOCK "$testdir/$m4base"/*.m4 >/dev/null 2>/dev/null; then
+     echo "gl_LOCK_EARLY"
+     echo
+   fi
+   if test "$libtool" = true; then
+     echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [true])"
+     echo "gl_cond_libtool=true"
+   else
      echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [false])"
+     echo "gl_cond_libtool=false"
+     echo "gl_libdeps="
+     echo "gl_ltlibdeps="
+   fi
+   echo "gl_source_base='$sourcebase'"
+   # Wrap the set of autoconf snippets into an autoconf macro that is then
+   # invoked. This is needed because autoconf does not support AC_REQUIRE
+   # at the top level:
+   #   error: AC_REQUIRE(gt_CSHARPCOMP): cannot be used outside of an AC_DEFUN'd macro
+   # but we want the AC_REQUIRE to have its normal meaning (provide one
+   # expansion of the required macro before the current point, and only one
+   # expansion total).
+   echo "AC_DEFUN([gl_INIT], ["
+   if test "$auxdir" != "build-aux"; then
+     sed_replace_build_aux='
+       :a
+       /AC_CONFIG_FILES(.*:build-aux\/.*)/{
+         s|AC_CONFIG_FILES(\(.*\):build-aux/\(.*\))|AC_CONFIG_FILES(\1:'"$auxdir"'/\2)|
+         ba
+       }'
+     sed_replace_build_aux=`echo "$sed_replace_build_aux" | sed -e 1d -e 's/^ *//'`
    else
-     echo "AM_CONDITIONAL([GL_COND_LIBTOOL], [true])"
+     sed_replace_build_aux=
    fi
    for module in $modules; do
      func_verify_nontests_module
      if test -n "$module"; then
-       func_get_autoconf_snippet "$module"
+       func_get_autoconf_snippet "$module" \
+         | sed -e "$sed_replace_build_aux"
      fi
    done
+   # _LIBDEPS and _LTLIBDEPS variables are not needed if this library is
+   # created using libtool, because libtool already handles the dependencies.
+   if test "$libtool" != true; then
+     libname_upper=`echo "$libname" | tr 'a-z' 'A-Z'`
+     echo "  ${libname_upper}_LIBDEPS=\"\$gl_libdeps\""
+     echo "  AC_SUBST([${libname_upper}_LIBDEPS])"
+     echo "  ${libname_upper}_LTLIBDEPS=\"\$gl_ltlibdeps\""
+     echo "  AC_SUBST([${libname_upper}_LTLIBDEPS])"
+   fi
+   echo "])"
+   echo "gl_INIT"
    echo
    if test -n "$subdirs_with_configure_ac"; then
      echo "AC_CONFIG_SUBDIRS(["`echo $subdirs_with_configure_ac`"])"
@@ -1544,7 +2342,7 @@ func_create_testdir ()
      # configure.ac which creates the subdir's Makefile.am, not this one.
      case " $subdirs_with_configure_ac " in
        *" $d "*) ;;
-       *) makefiles="$makefiles $d/Makefile" ;;
+       *) func_append makefiles " $d/Makefile" ;;
      esac
    done
    echo "AC_OUTPUT([$makefiles])"
@@ -1555,10 +2353,10 @@ func_create_testdir ()
    echo "executing ${AUTORECONF} --force --install"
    ${AUTORECONF} --force --install
   )
-  if grep '^BUILT_SOURCES *+=' "$testdir/lib/Makefile.am" > /dev/null; then
+  if grep '^BUILT_SOURCES *+=' "$testdir/$sourcebase/Makefile.am" > /dev/null; then
     (cd "$testdir"
      ./configure
-       cd lib
+       cd "$sourcebase"
        echo 'built_sources: $(BUILT_SOURCES)' >> Makefile
        make built_sources
        cd ..
@@ -1569,6 +2367,7 @@ func_create_testdir ()
 
 # func_create_megatestdir megatestdir allmodules
 # Input:
+# - local_gnulib_dir  from --local-dir
 # - auxdir          directory relative to destdir where to place build aux files
 func_create_megatestdir ()
 {
@@ -1582,13 +2381,14 @@ func_create_megatestdir ()
   # First, all modules one by one.
   for onemodule in $allmodules; do
     func_create_testdir "$megatestdir/$onemodule" $onemodule
-    megasubdirs="${megasubdirs}$onemodule "
+    func_append megasubdirs "$onemodule "
   done
   # Then, all modules all together.
+  # Except config-h, which breaks all modules which use HAVE_CONFIG_H.
   # Except fnmatch-posix, which conflicts with fnmatch-gnu. FIXME.
-  allmodules=`for m in $allmodules; do if test $m != fnmatch-posix; then echo $m; fi; done`
+  allmodules=`for m in $allmodules; do if test $m != config-h && test $m != fnmatch-posix; then echo $m; fi; done`
   func_create_testdir "$megatestdir/ALL" "$allmodules"
-  megasubdirs="${megasubdirs}ALL"
+  func_append megasubdirs "ALL"
 
   # Create Makefile.am.
   (echo "## Process this file with automake to produce Makefile.in."
@@ -1614,8 +2414,17 @@ func_create_megatestdir ()
 
   # Create autogenerated files.
   (cd "$megatestdir"
-   echo "executing ${AUTORECONF} --install"
-   ${AUTORECONF} --install
+   # Do not use "${AUTORECONF} --install", because autoreconf operates
+   # recursively, but the subdirectories are already finished, therefore
+   # calling autoreconf here would only waste lots of CPU time.
+   echo "executing ${ACLOCAL}"
+   ${ACLOCAL}
+   echo "executing mkdir build-aux"
+   mkdir build-aux
+   echo "executing ${AUTOCONF}"
+   ${AUTOCONF}
+   echo "executing ${AUTOMAKE} --add-missing --copy"
+   ${AUTOMAKE} --add-missing --copy
   )
 }
 
@@ -1628,7 +2437,7 @@ case $mode in
     ;;
 
   import | update )
-    
+
     # Where to import.
     if test -z "$destdir"; then
       destdir=.
@@ -1647,12 +2456,9 @@ case $mode in
       fi
     fi
 
-    test -f "$destdir"/Makefile.am \
-      || func_fatal_error "cannot find $destdir/Makefile.am"
-
     # Analyze configure.ac.
     guessed_auxdir="."
-    guessed_libtool=
+    guessed_libtool=false
     my_sed_traces='
       s,#.*$,,
       s,^dnl .*$,,
@@ -1677,6 +2483,7 @@ case $mode in
         # First use of gnulib in the given m4base.
         test -n "$supplied_libname" || supplied_libname=true
         test -n "$sourcebase" || sourcebase="lib"
+        test -n "$docbase" || docbase="doc"
         test -n "$testsbase" || testsbase="tests"
         test -n "$macro_prefix" || macro_prefix="gl"
       fi
@@ -1686,36 +2493,48 @@ case $mode in
       # To get this list of directories, look at Makefile.am. (Not at
       # configure, because it may be omitted from CVS. Also, don't run
       # "find $destdir -name gnulib-cache.m4", as it might be too expensive.)
-      aclocal_amflags=`grep '^ACLOCAL_AMFLAGS[         ]*=' "$destdir"/Makefile.am | sed -e 's/^ACLOCAL_AMFLAGS[       ]*=\(.*\)$/\1/'`
       m4dirs=
       m4dirs_count=0
-      m4dir_is_next=
-      for arg in $aclocal_amflags; do
-        if test -n "$m4dir_is_next"; then
-          # Ignore absolute directory pathnames, like /usr/local/share/aclocal.
-          case "$arg" in
-            /*) ;;
-            *)
-              if test -f "$destdir/$arg"/gnulib-cache.m4; then
-                m4dirs="$m4dirs $arg"
-                m4dirs_count=`expr $m4dirs_count + 1`
-              fi
-              ;;
-          esac
-        else
-          if test "X$arg" = "X-I"; then
-            m4dir_is_next=yes
+      if test -f "$destdir"/Makefile.am; then
+        aclocal_amflags=`grep '^ACLOCAL_AMFLAGS[        ]*=' "$destdir"/Makefile.am | sed -e 's/^ACLOCAL_AMFLAGS[       ]*=\(.*\)$/\1/'`
+        m4dir_is_next=
+        for arg in $aclocal_amflags; do
+          if test -n "$m4dir_is_next"; then
+            # Ignore absolute directory pathnames, like /usr/local/share/aclocal.
+            case "$arg" in
+              /*) ;;
+              *)
+                if test -f "$destdir/$arg"/gnulib-cache.m4; then
+                  func_append m4dirs " $arg"
+                  m4dirs_count=`expr $m4dirs_count + 1`
+                fi
+                ;;
+            esac
           else
-            m4dir_is_next=
+            if test "X$arg" = "X-I"; then
+              m4dir_is_next=yes
+            else
+              m4dir_is_next=
+            fi
           fi
+        done
+      else
+        # No Makefile.am! Oh well. Look at the last generated aclocal.m4.
+        if test -f "$destdir"/aclocal.m4; then
+          sedexpr1='s,^m4_include(\[\(.*\)])$,\1,p'
+          sedexpr2='s,^[^/]*$,.,'
+          sedexpr3='s,/[^/]*$,,'
+          m4dirs=`sed -n -e "$sedexpr1" aclocal.m4 | sed -e "$sedexpr2" -e "$sedexpr3" | LC_ALL=C sort -u`
+          m4dirs_count=`echo "$m4dirs" | wc -l`
         fi
-      done
+      fi
       if test $m4dirs_count = 0; then
         # First use of gnulib in a package.
         # Any number of additional modules can be given.
         test -n "$supplied_libname" || supplied_libname=true
         test -n "$sourcebase" || sourcebase="lib"
         m4base="m4"
+        test -n "$docbase" || docbase="doc"
         test -n "$testsbase" || testsbase="tests"
         test -n "$macro_prefix" || macro_prefix="gl"
         func_import "$*"
@@ -1731,7 +2550,12 @@ case $mode in
           if test $# = 0; then
             # No further arguments. Guess the user wants to update all of them.
             for m4base in $m4dirs; do
-              func_import
+              # Perform func_import in a subshell, so that variable values
+              # such as
+              #   local_gnulib_dir, avoidlist, sourcebase, m4base, docbase,
+              #   testsbase, libname, lgpl, makefile_name, libtool, macro_prefix
+              # don't propagate from one directory to another.
+              (func_import) || func_exit 1
             done
           else
             # Really ambiguous.
@@ -1778,7 +2602,7 @@ case $mode in
         if test -n "$remaining"; then
           echo "Remaining files:" $remaining 1>&2
           echo "gnulib-tool: *** Stop." 1>&2
-          exit 1
+          func_exit 1
         fi
       cd ..
     cd ..
@@ -1801,7 +2625,7 @@ case $mode in
         if test -n "$remaining"; then
           echo "Remaining files:" $remaining 1>&2
           echo "gnulib-tool: *** Stop." 1>&2
-          exit 1
+          func_exit 1
         fi
       cd ..
     cd ..
@@ -1902,4 +2726,18 @@ case $mode in
     func_fatal_error "unknown operation mode --$mode" ;;
 esac
 
+rm -rf "$tmp"
+# Undo the effect of the previous 'trap' command. Some shellology:
+# We cannot use "trap - 0 1 2 3 13 15", because Solaris sh would attempt to
+# execute the command "-". "trap '' ..." is fine only for signal 0 (= normal
+# exit); for the others we need to call 'exit' explicitly. The value of $? is
+# 128 + signal number and is set before the trap-registered command is run.
+trap '' 0
+trap 'func_exit $?' 1 2 3 13 15
+
 exit 0
+
+# Local Variables:
+# indent-tabs-mode: nil
+# whitespace-check-buffer-indent: nil
+# End: