root/mpich2/branches/dev/kumudb/maint/simplemake.in @ 4898

Revision 4898, 173.4 KB (checked in by kumudb, 5 months ago)

executable works except mpiexec

Line 
1#! @PERL@ -w
2# -*- Mode: perl; -*-
3$abs_mpich2srcdir = "@abs_mpich2srcdir@";
4#
5# (C) 2006 by Argonne National Laboratory.
6#     See COPYRIGHT in top-level directory.
7#
8#
9# Set some defaults
10$includedir = ".";
11$skipAction = 0;
12$makefilebase = "Makefile.base";
13$ranliblib    = 1;   # only set to 0 on systems where ar
14                     # computes a symbol table index.  Also see RANLIBNEEDED
15                     # environment variable
16$useinclude = 0;     # set to 1 to make the Makefiles refer to a single
17                     # base makefile.
18$include_list = "";
19$vpath_config = 0;   # set to 1 for @VPATH@
20$nocomments = 0;     # set to 1 to exclude comments from the source file
21$commonmake = "";    # Common entries for each generated Makefile
22$maint_targets = 1;  # set to 0 for distribution versions
23$maint_perf_targets = 0; # set to 1 to get extra targets to aid in
24                         # performance tuning.  These may cause problems
25                         # if the generated files are sometimes used
26                         # in preference to the original source files,
27                         # so this is not the default
28$verbose = 0;        # set to 1 to get more information
29$am_a = "";          # set to _a for automake style input
30$do_dependencies = "dynamic"; # set to no, static, or dynamic to attempt
31                              # to generate dependency information
32                              # use "ignore" to produce a target (for
33                              # recursive ops) but no actions
34$dependenciesDummy = "no";    # set to yes to create a dummy target for
35                              # dependencies
36$makeInclude = "include";     # set to the include command to use.
37                              # This is more robust if it ignores missing files
38                              # (e.g., the gnumake "-include")
39$gCheckForTargets = 0;        # Set to 1 to look for files not included
40                              # in the Makefile.sm
41$gSubdirSMVarsSeen = "";      # Set to contain the names of variables in
42                              # Makefile.sm that override variables for
43                              # a subdirectory
44@subdirsSMVars = ();          # Stack used with gSubdirSMVarsSeen
45
46$smrootdir = "";              # Location of simplemake - this will override
47                              # the automatic setting if used.
48
49# makeBlockSep is used to deliniate blocks of code in the generated makefile
50# to enhance readability
51$makeBlockSep =
52"# --------------------------------------------------------------------------\n";
53
54# Set the names for the autoconf and autoheader program, along with
55# the optional args and the argument used to specify the include dir for
56# autoconf/autoheader (autoconf 2.57 changed the command-line interface
57# without maintaining backward compatibility)
58if (defined($ENV{"AUTOCONF"})) {
59    $autoconf_prog = $ENV{"AUTOCONF"};
60}
61else {
62    $autoconf_prog = "autoconf";
63}
64if (defined($ENV{"AUTOHEADER"})) {
65    $autoheader_prog = $ENV{"AUTOHEADER"};
66}
67else {
68    $autoheader_prog = "autoheader";
69}
70if (defined($ENV{"CHECKTARGETS"})) {
71    $gCheckForTargets = 1;
72}
73$autoconf_args = ""; # Extra arguments for autoconf
74$acincdir_arg = "-l";
75
76$do_sharedlibs  = 1; # set to 1 the generate targets for shared libraries
77$found_sharedlib = 0;# set to 1 if a specific shared library target is found
78
79$root_tags = 1;      # set to 1 to create a tags file in the root dir
80$local_tags = 0;     # set to 1 to create a tags file in the local dir
81#$do_libmember = 0;   # set to 1 to generate library member rules in makefiles
82$do_docs = 1;        # set to 1 to generate documentation
83
84$convert_Ldir_to_relative = 1; # set to 1 to convert -Ldir to ../../lib
85                     # relative to the rootdir
86#
87# The following two symbols are defined for future use in generating
88# the dependency information for programs that are created.  This
89# allows us to ensure that test programs are rebuilt if we rebuild the
90# libraries
91#$project_libs = "";  # name of the libraries that are created by
92#                     # this project
93#$project_libdir = "";# name of the directory (may contain ROOTDIR) in which
94#                     # the libraries are created                   
95#
96# Perhaps a better approach is to provide
97# <program>_DEPS = other program dependencies
98# DEPSALL = dependencies for *all* programs
99
100$make_depend = "gcc -MM -MT '_$$*.o $$*.o'"; 
101           # Set to command to create dependency list.  Include the
102           # Profiling objects (_xxx.o).  If gcc includes -MF, we can
103           # output directly: -MF '.deps/$*.d'
104$fixup_autoconf_cd = 0; # set to 1 to (partially) fixup configure for
105                        # pathnames that contain blanks
106$autoconf = "autoconf"; # Name of autoconf program to use
107$autoconf_version = ""; # Require a specific version
108$configure_has_config_headers = "no";
109#
110$quietmake = "@";       # set to "" for echo commands, @ to suppress them
111$quietLine = "@";       # set to "" to make the clean targets echo commands
112#
113# Defaults for building MPICH
114$doc_heading = "MPI";
115#%doc_extra   = ();  # for kinds html, man, latex
116#
117# Set to 1 if make doesn't handle time stamps properly (some makes, including
118# some versions of gnumake, improperly and inconsistently
119# handle comparisons of less than a second
120$fixup_for_timestamps = 0;
121# Set a default sleepTime.
122$sleepTime = 1;
123$useSleepFast = 1;
124# The sleep amount should be parameterized.  One developer at IBM
125# needed 10 seconds, not 1, because of the variation in file system times
126# between the local machine and the file server. The environment
127# variable INTERDIR_SLEEP , for inter-directory sleep, sets both the
128# time and selects the use of slow sleep
129
130if (defined($ENV{'INTERDIR_SLEEP'})) {
131    $sleepTime = $ENV{'INTERDIR_SLEEP'};
132    $useSleepFast = 0;
133    $fixup_for_timestamps = 1;
134}
135
136$SleepSlow = "sleep $sleepTime";
137$SleepFast = "perl -e \'\$\$now=time;\$\$now-=10;utime \$\$now, \$\$now, \"LIB\";\'";
138
139# Set the default (it can be overridden by the command line)
140if ($useSleepFast) {
141    $Sleep = $SleepFast;
142}
143else {
144    $Sleep = $SleepSlow;
145}
146
147# Check environment variable to see if ranlib is needed.
148if (defined($ENV{"RANLIBNEEDED"})) {
149    my $val = $ENV{"RANLIBNEEDED"};
150    if ($val eq "YES" || $val eq "yes" || $val == 1) {
151        $ranliblib = 1;
152    }
153    elsif ($val eq "NO" || $val eq "no" || $val == 0) {
154        $ranliblib = 0;
155    }
156}
157
158#
159# Output File end-of-line character
160$newline = "\n";
161
162$create_configure_input = 1;  # Changes file.sm to file.in .  Set to 0
163                              # for file.sm to file .
164$smdir=$0;         # directory containing simplemake
165if ($smdir =~/^[^\/]/) {
166    $curpwd = $ENV{'PWD'};
167    #chomp($curpwd = `pwd`);
168    #print "curdir = $curpwd\n";
169    #print "\$0 = $0\n";
170    $smdir = $curpwd . "/$0";
171}
172$smdir =~ s/\/?simplemake$//;
173#print "smdir = $smdir\n";
174
175$debug = 0;                 # General debugging
176$debug_dirs = 0;            # Debug the choice of directories
177$debug_confdir = 0;         # Track the directory containing the controlling
178                            # configure.in
179$gDebugWhy = 0;             # Provide an explanation of why certain
180                            # targets are created
181$gDebugSubdirVar = 0;       # Track changes to internal variables that
182                            # apply to a subdirectory
183$debugConfigHeaderDepend = 0;    # Print the config header targets added to
184                                 # makefile.in's
185# Allow us to set the debug variables from the environment:
186if (defined($ENV{"DEBUG"})) { $debug = 1; }
187if (defined($ENV{"DEBUG_DIRS"})) { $debug_dirs = 1; }
188if (defined($ENV{"DEBUG_CONFDIR"})) { $debug_confdir = 1; }
189if (defined($ENV{"DEBUG_SUBDIRVAR"})) { $gDebugSubdirVar = 1; }
190
191# Initialize global variables used in informal modules
192&printInit();
193
194$quiet = 0;
195
196%libdir = ();
197#
198# While simplemake doesn't support ext->other (e.g., .c to .s),
199# the rules have been added.
200%extrules = ( 'c:o' => '$(C_COMPILE) -c $<',
201              'f:o' => '$(F77_COMPILE) -c $<',
202              'cxx:o' => '$(CXX_COMPILE) -c $<',
203              'cpp:o' => '$(CXX_COMPILE) -c $<',
204              's:o' => '$(AS_COMPILE) $<',
205              'f90:o' => '$(F90_COMPILE) -c $<',
206# Assembler *output* definitions
207              'c:s' => '$(C_COMPILE) -S $<',
208              'f:s' => '$(F77_COMPILE) -S $<',
209# C preprocessor *output* definitions.  We don't use cpp as the
210# output suffix to avoid conflicts with C++
211              'c:txt' => '$(CPP) $(INCLUDES) $(CPPFLAGS) $< >$*.txt',
212              'F:txt' => '$(CPP) $(INCLUDES) $(CPPFLAGS) $<  >$*.txt',
213              'cxx:txt' => '$(CXXCPP) $(INCLUDES) $(CPPFLAGS) $< >$*.txt',
214# Program from source rules
215              'c:' => '$(C_COMPILE) -o $* $< $(LDFLAGS) $(LIBS)',
216              'f:' => '$(F77_COMPILE) -o $* $< $(LDFLAGS) $(LIBS)',
217              'f90:' => '$(F90_COMPILE) -o $* $< $(LDFLAGS) $(LIBS)',
218              'cxx:' => '$(CXX_COMPILE) -o $* $< $(LDFLAGS) $(LIBS)',
219# LaTeX definitions
220              'tex:dvi' => 'latex $<',
221              'dvi:ps' => 'dvips $<',
222              'dvi:pdf' => 'dvipdfm $<',
223# Shared object definitions           
224# To avoid overwritting the .o file, we use a specific output file name
225# Note that many compilers insist that that file have a .o extension,
226# so we change the *name*.  We us _s for the shared lib intermediates
227              'c:lo' => '$(C_COMPILE_SHL) -c $< -o _s$*.o
228        @mv -f _s$*.o $*.lo',
229              'f:lo' => '$(F77_COMPILE_SHL) -c $< -o _s$*.o
230        @mv -f _s$*.o $*.lo',
231              'cxx:lo' => '$(CXX_COMPILE_SHL) -c $< -o _s$*.o
232        @mv -f _s$*.o $*.lo',
233              'cpp:lo' => '$(CXX_COMPILE_SHL) -c $< -o _s$*.o
234        @mv -f _s$*.o $*.lo',
235              'f90:lo' => '$(F90_COMPILE_SHL) -c $< -o _s$*.o
236        @mv -f _s$*.o $*.lo',
237## This has an MPICH-specific definition that we should eventually generalize
238## We use -o on the compile line to keep from overwriting the .o file;
239## this improves the behavior when weak symbols are not supported
240## We use _ for the profiling lib intermediates
241#              'c:pf' => '${C_COMPILE} -c $< -o _$*.o
242             );
243
244# When we are building profiled versions, we use a separate ext rule
245%extrules_with_profile = %extrules;
246# PROFILE_DEF_MPI is set when needed to create the profiling libraries.
247#$extrules_with_profile{'c:o'} =~ s/-c/-c \@PROFILE_DEF_MPI\@/;
248#print "rule = $extrules_with_profile{'c:o'}\n" if $debug;
249
250# Definitions for each extension (these are the defs needed for each ext->o
251# extension)
252%extdef = ( 'c:o'   => 'CC              = @CC@
253CFLAGS          = @CFLAGS@ $(MPICH2_MAKE_CFLAGS)
254C_COMPILE       = $(CC) $(DEFS) $(INCLUDES) $(CFLAGS) $(CPPFLAGS)',
255            'f:o'   => 'FC              = @FC@
256FFLAGS          = @FFLAGS@
257F77_COMPILE     = $(FC) $(FFLAGS) $(F77INCLUDES)',
258            'cxx:o' => 'CXX             = @CXX@
259CXXFLAGS        = @CXXFLAGS@
260CXX_COMPILE     = $(CXX) $(DEFS) $(INCLUDES) $(CXXFLAGS) $(CPPFLAGS)',
261            'cpp:o' => 'CXX             = @CXX@
262CXXFLAGS        = @CXXFLAGS@
263CXX_COMPILE     = $(CXX) $(DEFS) $(INCLUDES) $(CXXFLAGS) $(CPPFLAGS)',
264            'cs:o'  => 'CSHARP          = @CSHARP@
265CSFLAGS         = @CSFLAGS@
266CSHARP_COMPILE  = $(CSHARP) $(DEFS) $(INCLUDES) $(CSFLAGS) $(CPPFLAGS)',
267            's:o'   => 'AS              = @AS@
268AS_COMPILE      = $(AS)',
269            'f90:o'   => 'F90              = @F90@
270F90FLAGS        = @F90FLAGS@
271F90_COMPILE     = $(F90) $(F90FLAGS) $(F90INCLUDES)',
272# Similarly, but for shared-library versions
273            'c:lo'   => 'CC_SHL          = @CC_SHL@
274C_COMPILE_SHL   = $(CC_SHL) $(DEFS) $(INCLUDES) $(CFLAGS) $(CPPFLAGS)',
275            'f:lo'   => 'FC_SHL          = @FC_SHL@
276F77_COMPILE_SHL = $(FC_SHL) $(FFLAGS) $(F77INCLUDES)',
277            'f90:lo'   => 'F90_SHL          = @F90_SHL@
278F90_COMPILE_SHL = $(F90_SHL) $(F90FLAGS) $(F90INCLUDES)',
279            'cxx:lo' => 'CXX_SHL         = @CXX_SHL@
280CXX_COMPILE_SHL = $(CXX_SHL) $(DEFS) $(INCLUDES) $(CXXFLAGS) $(CPPFLAGS)',
281            'cpp:lo' => 'CXX_SHL         = @CXX_SHL@
282CXX_COMPILE_SHL = $(CXX_SHL) $(DEFS) $(INCLUDES) $(CXXFLAGS) $(CPPFLAGS)',
283           );
284
285%extstring = ( 'c:o'    => '  CC              $<',
286               'c:'     => '  CC              $<',
287               'f:o'    => '  FC              $<',
288               'cxx:o'  => '  CXX             $<',
289               'cpp:o'  => '  CXX             $<',
290               'cs:o'   => '  CS              $<',
291               's:o'    => '  AS              $<',
292               'f90:o'  => '  F90             $<',
293               'c:lo'   => '  CC              $<',
294               'f:lo'   => '  FC              $<',
295               'f90:lo' => '  F90             $<',
296               'cxx:lo' => '  CXX             $<',
297               'cpp:lo' => '  CPP             $<',
298    );
299
300#
301# Rules to build programs (.o:)
302#
303# We need to include the <lang>FLAGS, because configure links programs
304# that way when it tests programs.
305%progrules = ( 'c' => '$(C_LINK) $(CFLAGS) $(LDFLAGS)',
306               'cxx' => '$(CXX_LINK) $(CXXFLAGS) $(LDFLAGS)',
307               'cpp' => '$(CXX_LINK) $(CXXFLAGS) $(LDFLAGS)',
308               'cs'  => '$(CSHARP_LINK) $(LDFLAGS)',
309               'f'   => '$(F77_LINK) $(FFLAGS) $(LDFLAGS)',
310               'f90' => '$(F90_LINK) $(F90FLAGS) $(LDFLAGS)',
311              );
312%progdefs = ( 'c' =>   'C_LINK         = $(CC)',
313              'cxx' => 'CXX_LINK       = $(CXX)',
314              'cpp' => 'CXX_LINK       = $(CXX)',
315              'cs'  => 'CSHARP_LINK    = $(CSHARP)',
316              'f'   => 'F77_LINK       = $(FC)',
317              'f90' => 'F90_LINK       = $(F90)',
318             );
319
320# Rules to build shared libraries (these are like programs
321# Question: Do we want a common rule or separate rules for each language?
322# These are out-of-date.
323%shlibdefs = ( 'c' =>   'C_LINK_SHL      = @C_LINK_SHL@',
324               'cxx' => 'CXX_LINK_SHL    = @CXX_LINK_SHL@',
325               'cpp' => 'CXX_LINK_SHL    = @CXX_LINK_SHL@',
326               'f'   => 'F77_LINK_SHL    = @F77_LINK_SHL@',
327               'f90' => 'F90_LINK_SHL    = @F90_LINK_SHL@',
328             );
329#%shlibrules = ( 'c' => '$(C_LINK_SHL) $(LDFLAGS)',
330#              'cxx' => '$(CXX_LINK_SHL) $(LDFLAGS)',
331#              'cpp' => '$(CXX_LINK_SHL) $(LDFLAGS)',
332#              'f'   => '$(F77_LINK_SHL) $(LDFLAGS)',
333#              'f90' => '$(F90_LINK_SHL) $(LDFLAGS)',
334#             );
335
336#
337# Directories needed.  These are the prefix etc.  Many are needed only
338# at the top level, particularly for installation.  srcdir is needed only for
339# VPATH builds
340$srcdir_name =               "srcdir          = \@srcdir\@";
341$abs_srcdir_name =           "abs_srcdir      = \@abs_srcdir\@";
342$master_topsrcdir_name =     "master_top_srcdir  = \@master_top_srcdir\@";
343$topsrcdir_name =            "top_srcdir      = \@top_srcdir\@";
344$prefix_name =               "prefix          = \@prefix\@";
345$exec_prefix_name =          "exec_prefix     = \@exec_prefix\@";
346$bindir_name =               "bindir          = \@bindir\@";
347$sbindir_name =              "sbindir         = \@sbindir\@";
348$libdir_name =               "libdir          = \@libdir\@";
349$includedir_name =           "includedir      = \@includedir\@";
350$mandir_name =               "mandir          = \@mandir\@";
351$htmldir_name =              "htmldir         = \@htmldir\@";
352$docdir_name =               "docdir          = \@docdir\@";
353# datarootdir is new in autoconf 2.60, and is needed for other
354# dirs like mandir (much as prefix and execprefix are also needed)
355$datarootdir_name =          "datarootdir     = \@datarootdir\@";
356$datadir_name =              "datadir         = \@datadir\@";
357$sysconfdir_name =           "sysconfdir      = \@sysconfdir\@";
358$pkgconfigdir_name =         "pkgconfigdir    = \@libdir\@/pkgconfig";
359$builddir_name =             "builddir        = \@builddir\@";
360$abs_builddir_name =         "abs_builddir    = \@abs_builddir\@";
361# top_builddir is used by libtool.  We use master_top_builddir because
362# the various configure scripts need to use the root of the build (that
363# is the model that we use for simplemake projects)
364$top_builddir_name =         "top_builddir    = \@master_top_builddir\@";
365
366%dirdefs = ( 'srcdir'     => $srcdir_name,
367             'abs_srcdir' => $abs_srcdir_name,
368             'top_srcdir' => $topsrcdir_name,
369             'prefix'     => $prefix_name,
370             'exec_prefix'=> $exec_prefix_name,
371             'bindir'     => $bindir_name,
372             'sbindir'    => $sbindir_name,
373             'libdir'     => $libdir_name,
374             'includedir' => $includedir_name,
375             'master_top_srcdir' => $master_topsrcdir_name,
376             'top_builddir' => $top_builddir_name,
377             'builddir'     => $builddir_name,
378             'abs_builddir' => $abs_builddir_name,
379             'mandir'       => $mandir_name,
380             'datarootdir'  => $datarootdir_name,
381             'htmldir'      => $htmldir_name,
382             'docdir'       => $docdir_name,
383             'sysconfdir'   => $sysconfdir_name,
384             'pkgconfigdir' => $pkgconfigdir_name,
385             'datadir'      => $datadir_name,
386            );
387
388#InstallDirFromKind maps XXX from install_XXX into the GNU name
389%InstallDirFromKind = ( 'LIB' => 'libdir',
390                 'SHLIB' => 'libdir',    # SHLIB also signals library to build
391                 'DLLLIB' => 'libdir',   # DLLLIB also signals library to build
392                 'BIN' => 'bindir',
393                 'SCRIPT' => 'bindir',
394                 'INCLUDE' => 'includedir',
395                 'MAN' => 'mandir',
396                 'HTML' => 'htmldir',
397                 'DOC' => 'docdir',
398                 'ETC' => 'sysconfdir',
399                 'DATADIR' => 'datadir',
400                 'PKGCONFIG' => 'pkgconfigdir',
401                );
402# We add the -p switch to install for the libraries because libraries
403# that require ranlib may fail if installed without preserving the
404# data/time on the file.  This should work because configure looks for
405# a BSD-style install.
406# Sigh.  ginstall (!!!) doesn't support the -p switch.
407# This means that there is no way to install a library under Darwin
408# without defining INSTALL_DATA as install -p, which configure
409# does not figure out(!).  The MPICH2 configure does check for
410# whether install works with or without -p.
411#
412# CREATESHLIB is a special script for shared libraries
413%install_methods = ( 'LIB'     => '$(INSTALL_DATA)',
414                     'BIN'     => '$(INSTALL_PROGRAM) $(INSTALL_STRIP_FLAG)',
415                     'SCRIPT'  => '$(INSTALL_SCRIPT)',
416                     'SHLIB'   => '$(CREATESHLIB) --mode=install',
417                     'DLLLIB'  => '$(CREATESHLIB) --mode=install',
418                     'INCLUDE' => '$(INSTALL_DATA)',
419                     'MAN'     => '$(INSTALL_DATA)',
420                     'HTML'    => '$(INSTALL_DATA)',
421                     'DOC'     => '$(INSTALL_DATA)',
422                     'ETC'     => '$(INSTALL_DATA)',
423                     'DATADIR' => '$(INSTALL_DATA)',
424                     'PKGCONFIG' => '$(INSTALL_DATA)',
425                    );
426%uninstall_methods = ( 'SHLIB'   => '$(CREATESHLIB) --mode=uninstall',
427                       'DLLLIB'  => '$(CREATESHLIB) --mode=uninstall',
428                     );
429# These give the directories that autoconf will require for the
430%required_dirs = ( 'libdir'      => 'exec_prefix prefix',
431                   'bindir'      => 'exec_prefix prefix',
432                   'mandir'      => 'prefix datarootdir',
433                   'htmldir'     => 'prefix datarootdir',
434                   'docdir'      => 'prefix datarootdir',
435                   'includedir'  => 'prefix',
436                   'exec_prefix' => 'prefix',
437                   'sysconfdir'  => 'prefix',
438                   'exec_prefix' => 'prefix',
439                   'pkgconfigdir'=> 'libdir exec_prefix prefix',
440                   'datadir'     => 'prefix',
441                  );
442# etc.
443#
444# Remember which document types we've seen
445%globaldockind = ( "html" => 0, "man" => 0, "latex" => 0 );
446# Set globaldocdir to the location to use if no specific directory is
447# chosen.  It may contain ROOTDIR.
448$globaldocdir  = 'ROOTDIR/$dockinddirval';
449# Directories for documentation
450# These may be overridden how by setting docthiskinddir
451%dockinddir = ( "html" => "www/www3",
452                "man" => "man/man3",
453                "latex" => "doc/refman" );
454%docthiskinddir = ();
455# man targets for documentation
456%docTargetName = ( "html" => "htmldoc",
457                   "man" => "mandoc",
458                  "latex" => "latexdoc" );
459# doctext name to produce documentation
460%doctextOptionName = ( "html" => "-html",
461                       "man" => "-man",       # New version allows -man
462                      "latex" => "-latex" );
463$doc_namedefs   = "";
464$doc_attop = 1;
465#
466# Rules
467# (need a way to quote the rule here and unquote it when used)
468#
469# Need a way to substitute for additional or replacement default rules
470# Other global data
471$do_profilelibs   = 1; # Set to one if a profiling version of the library
472                       # should be created (required for MPI)
473$found_profilelib = 0;
474
475# Default values
476$distcleanfiles = "";
477
478@subdirs = ();
479@doc_subdirs = ();
480
481%notSimplemakeDirs = (); # This hash is used to note directories that
482                         # are part of the subdirs but are not
483                         # simplemake dirs
484
485# ---------------------------------------------------------------------------
486# Global variables that describe extensions
487#   Each extension has a name, related to the command-field in the
488#   Makefile.sm, and must be added to this array
489@KnownActions = ();
490# Load any extension definitions, in this order
491&SMReadDefnFiles( "maint/smlib" );
492# If we're not in the root of the source directory, then
493# also read that directory.  We can use stat to check the inode numbers of the
494# directories; if they are the same, the directories are the same.
495# (Only read if there is a local maint/smlib directory)
496@d1 = stat( "maint/smlib" );
497@d2 = stat( "$abs_mpich2srcdir/maint/smlib" );
498if ( (! -d "maint/smlib") || $d1[1] != $d2[1]) {
499    &SMReadDefnFiles( "$abs_mpich2srcdir/maint/smlib" );
500}
501if (defined($ENV{"SMDIR"})) {
502    &SMReadDefnFiles( $ENV{"SMDIR"} );
503}
504&SMReadDefnFiles( "." );
505# ---------------------------------------------------------------------------
506@keepargs = ();    # Used to recreate simplemake invocation for make target
507$foundFile = "no";
508foreach $_ (@ARGV) {
509    $keepargs[$#keepargs+1] = $_;    # Add all args by default
510    if (/-nocomments/) { $nocomments = 1; }
511    elsif (/-v/) { $verbose = 1; }
512    elsif (/-am/) { $am_a = "_a"; }
513    elsif (/-libdir=([^=]*)=(.*)$/) {
514        print "libdir{$1} = $2$newline" if (!$quiet);
515        $libdir{$1}  = "$2/";
516        # Replace with an easier-to-preserve version
517        # FIXME: Replace a single $ with double $$ in $1?
518        my $lname = $1;
519        my $rname = $2;
520        # Replace a single $ with a double $ in lname *only*
521        $lname =~ s/\$/\$\$/;
522        $keepargs[$#keepargs] = "-libdir=\'$lname=$rname\'";
523    }
524    elsif (/-common=(.*)$/) {
525        $filename = $1;
526        open( CD,"<$filename" ) || die "Could not open $filename\n";
527        while (<CD>) {
528            s/\r//g; # Strip \r for DOS
529            $commonmake .= $_;
530        }
531        close(CD);
532        # Replace this argument with an updated version
533        if ($filename =~ /^[^\/]/) {
534            $keepargs[$#keepargs] = "-common=\${master_top_srcdir}/$filename";
535        }
536    }
537    elsif (/-autoconf=(.*)$/) {
538        $autoconf_args = $1;
539    }
540    elsif (/-include=(.*)$/) {
541        $include_list = $1;
542    }
543    elsif (/-distrib/) {
544        # Turn off the maintenance targets in the distribution version
545        $maint_targets = 0;
546        $maint_perf_targets = 0;
547        $do_docs = 0;
548        # Use the robust sleep, not the fast perl version
549        $useSleepFast = 0;
550        $Sleep = $SleepSlow;
551        # FIXME: Sleep code only used if fixup set to 1
552        #$fixup_for_timestamps = 1; # make is broken
553    }
554    elsif (/-interdirsleep/) {
555        $useSleepFast = 0;
556        $fixup_for_timestamps = 1;
557        if (/-interdirsleep=(\d*)/) {
558            $sleepTime = $1;
559            $SleepSlow = "sleep $sleepTime";
560        }
561        $Sleep = $SleepSlow;
562    }
563    elsif (/-perftargets/) {
564        # This option enables any performance targets of interest to
565        # maintainers (currently adds options to build asm (.s) files)
566        $maint_perf_targets = 1;
567    }
568    elsif (/-dos/) {
569        $newline = "\r\n";
570    }
571    elsif (/-shared/) {
572        $do_sharedlibs = 1;
573    }
574    elsif (/-noshared/) {
575        $do_sharedlibs = 0;
576    }
577    elsif (/-docs/) {
578        $do_docs = 1;
579    }
580    elsif (/-nodocs/) {
581        $do_docs = 0;
582    }
583    elsif (/-vpath=?(.*)/) {
584        $val = $1;
585        if ($val eq "no") { $vpath_config = 0; }
586        else { $vpath_config = 1; }
587    }
588    elsif (/-depend=static/) {
589        $do_dependencies = "static";
590    }
591    elsif (/-depend/) {
592        $do_dependencies = "dynamic";
593    }
594    elsif (/-nodepend/) {
595        $do_dependencies = "no";
596    }
597    elsif (/-rootdir=(.*)$/) {
598        $rootdirpath = $1;
599        $#keepargs--;  # remove this entry (it is explicitly recreated)
600    }
601    elsif (/-distcleanfiles=(.*)/) {
602        # extra files to remove in this directory
603        if ($distcleanfiles ne "") { $distcleanfiles .= " "; }
604        $distcleanfiles .= $1;
605    }
606    elsif (/-checktargets/) {
607        $gCheckForTargets = 1;
608    }
609    elsif (/-configdir=(.*)/) {
610        # Use this option to specify the location of the configure
611        # that controls the Makefile.in in this directory.
612        # This is normally used when rebuilding a single Makefile.in
613        # from a Makefile.sm .
614        $last_config_dir = $1;
615        $#keepargs--;  # remove this entry (it is explicitly recreated)
616    }
617    elsif (/-debugdirs/) {
618        $debug_dirs = 1;
619    }
620    elsif (/-debug/) {
621        $debug = 1;
622    }
623    elsif (/-smvar_([\w_]*)=(.*)/) {
624        # Allow the command-line to override internal variables
625        my $varname = $1;
626        my $varvalue   = $2;
627        $${varname} = $varvalue;
628    }
629    elsif (/-quietmake/) { $quietmake = "@"; }
630    elsif (/-noquietmake/) { $quietmake = ""; }
631    elsif (/-quiet/) { $quiet = 1; }
632    elsif (/-docheading=(.$)/) { $doc_heading = $1; }
633    elsif (/-docdestdir=(.*)/) { $globaldocdir = $1; }     
634    elsif (/-docnamedefs=(.*)/) { $doc_namedefs = $1; }   
635    elsif (/-smroot=(.*)/) { $smrootdir = $1; $smdir = $1; }
636    elsif (/-help/) {
637        &printHelp;
638        exit 0;
639    }
640    else {
641        $#keepargs--;  # Remove filename from list
642        $foundFile = "yes";
643        &ProcessFile ( $_ );
644    }
645}
646
647
648# If there is no argument and the default filename, then process it
649print "found file = $foundFile\n" if $debug;
650if ($foundFile ne "yes" && -s "Makefile.sm") {
651    print "about to process file\n";
652    &ProcessFile( "Makefile.sm" );
653}
654
655
656# Check that gcc is available if we need it
657if ($do_dependencies eq "static") {
658    if ($make_depend =~ /gcc\s.*-MM/) {
659        # (we use the pattern match to allow other options)
660        # This was | 2>&1 but the redirect should go before the pipe.
661        if (open (TFD, "gcc --version 2>&1 |" )) {
662            close TFD;
663        }
664        else {
665            $do_dependencies = "no";
666        }
667    }
668    # insert check here.  Perhaps we should try #include <stdio.h>?
669}
670
671# Routines
672# =========================================================================
673# Read Makefile.sm
674sub ReadMfile {
675    my $Mfile = $_[0];
676    my $linecount = 0;
677    open (MFILE,"<$Mfile" ) || die "Could not open $Mfile in $curdir\n";
678    &ClearVars;
679    while (<MFILE>) {
680        $linecount++;
681        s/\r//g;              # Remove \r for DOS
682        $origline = $_;
683        # Remove trailing newline (we had trouble with chomp on DOS)
684        #chomp;
685        s/[\r\n]*$//;
686
687        # Handle continuation lines
688        while (s/\\$//) {  # Match and remove a trailing \
689            if (eof(MFILE)) {
690                print STDERR "Unexpected EOF in $curdir$Mfile\n";
691                last;
692            }
693            $nextline = <MFILE>;
694            $nextline =~ s/\r//g; # Remove \r for DOS
695            $linecount++;
696            $origline .= $nextline;
697            #chomp $nextline;
698            $nextline =~ s/[\r\n]*$//;
699            $_ .= $nextline;
700        }
701
702        # Check for portability problems
703        # Check for a blank line that starts with a tab
704        if (/^\t\s*$/) {
705            print STDERR "File $curdir$Mfile contains a blank line beginning with a tab\nat line $linecount.  Some make programs will fail with a syntax error.\n";
706        }
707        if (/^\t#/) {
708            print STDERR "File $curdir$Mfile contains a comment line beginning with a tab\nat line $linecount.  Some make programs will fail if this comment is part\nof a command script in a target\n";
709        }
710
711        # Look for commands that are defined by extensions.  These are
712        # of the form
713        #    name_COMMAND
714        # where COMMAND is all uppercase.  "name" may itself be of the form
715        #    name_subcommand
716        # an example is
717        #   libfoo_la_SOURCES
718        # where the command is SOURCES and the subcommand is la
719        # We allow the names to include make variables and autoconf
720        # variables
721        if (/^([@\${}\(\)\w-]+)_([A-Z]+)\s*=(.*)/) {
722            my $name    = $1;
723            my $command = $2;
724            my $value   = $3;
725            # See if this is a known extension command
726            my $fcnName = "Action" . $command;
727            if (defined(&$fcnName)) {
728                # This is an extension.  Invoke its function
729                print "Executing $fcnName for $_\n" if $debug;
730                $skipAction = 0;
731                &$fcnName( $_ );
732                $origline = "";
733                # skip the processing of this line for the default commands
734                if (!defined($skipAction) || $skipAction == 1) {
735                    next;
736                }
737            }
738        }
739
740        # Look for reserved forms:
741        #lib([\w-]*)_SOURCES = names
742        #lib([\w-]*)_DIR = name
743        #install_local_DIR = name(s)
744        #SUBDIRS = names
745        #DOC_SUBDIRS = names
746        #DOCDESTDIRS = kind:dir [, kind:dir ]*
747        # Also keep track of Makefile usages:
748        #target: ...
749        #variable = value
750        #.SUFFIXES:value
751        # Using the _a_ in the library lines is necessary to distinguish
752        # between libraries and programs that start with lib...
753        if (/^lib([@\${}\(\)\w-]+)_a_SOURCES\s*=\s*(.*)$/) {
754            $libname   = $1;
755            $libsource = $2;
756            $libraries{ $libname } = $libsource;
757            # Keep a number for each library; this is used for
758            # alternate targets used to handle filesystem timestamp problems
759            $libnum{$libname} = $libcount++;
760            # Add to targets
761            $libloc = &GetLibLoc( $libname );
762            $alltargets[$#alltargets+1] = "${libloc}lib$libname.a";
763            &LibraryTimestampTarget( "${libloc}lib$libname.a",
764                                     ".libstamp" . $libnum{$libname} );
765            # Shared libraries should not be built unconditionally. 
766            # Instead of adding them to the alltargets, add them
767            # to a allshlibtargets
768            # FIXME: Sometimes, we want to use a separate library
769            # for the shared library (e.g., for the C++ bindings)
770            # while using a single library for the static linking.
771            # here is where we would do that, using a special
772            # mapping of library name to shared library name
773            if ($do_sharedlibs && !defined($libNotShared{$libname})) {
774                $allshlibtargets[$#allshlibtargets+1] =
775                    "${libloc}lib$libname.la";
776                $dirs_seen{'top_builddir'} = 1;   # For libtool
777                $libnum{$libname.".la"} = $libcount++;
778            }
779            # Keep track of source types
780            &FindSrcTypes( $libsource );
781            # Keep track of source files
782            &SaveSrcNames( $libsource );
783        }
784        # In some cases, there is a library that should only be built as
785        # a non-shared library (e.g., built with Fortran)
786        elsif (/^lib([@\${}\(\)\w-]*)_a_NOSHARED\s*$/) {
787            print "Adding $1 as not-shared\n" if $debug;
788            $libNotShared{$1} = 1;
789        }
790        # Using the _so_ in the library lines is necessary to distinguish
791        # between libraries and programs that start with lib...
792        # This target is used for libraries that are *always* needed
793        # as shared libraries (e.g., they are used only in a dynamic
794        # link context).  No _so_DIR for these yet because stand-alone
795        # shared libraries are usually contained within a single
796        # directory.
797        elsif (/^lib([@\${}\(\)\w-]*)_so_SOURCES\s*=\s*(.*)$/) {
798            $found_sharedlib = 1;
799            $libname = "$1";
800            $libsource = $2;
801            $shared_libraries{ $libname } = $libsource;
802            # Add to targets
803            $libloc = &GetLibLoc( $libname );
804            $allshlibtargets[$#allshlibtargets+1] = "${libloc}lib$libname.\@SHLIB_EXT\@";
805            $dirs_seen{'top_builddir'} = 1;   # For libtool
806            # Keep track of source types
807            &FindSrcTypes( $libsource );
808            # Keep track of source files
809            &SaveSrcNames( $libsource );
810            # We need to include .lo as a necessary suffix.
811        }
812        elsif (/^lib([@\${}\(\)\w-]*)_so_EXPORTS\s*=\s*(.*)$/) {
813            $libname = "$1";
814            $libexports = $2;
815            $shared_libraries_exports{ $libname } = $libexports;
816        }
817        elsif (/^lib([@\${}\(\)\w-]*)_so_LIBS\s*=\s*(.*)$/) {
818            # Specify dependent libraries for a shared library
819            # (Some systems require knowledge of all of the libraries
820            # needed when creating a shared library.)
821            $libname = "$1";
822            $dependentlibs = $2;
823            $shared_libraries_libs{ $libname } = $dependentlibs;
824        }
825        elsif (/^lib([@\${}\(\)\w-]*)_a_DIR\s*=\s*(\S+)\s*$/) {
826            # This is an extension over automake.  It makes it easy
827            # to modify a library in a different directory
828            # Add a trailing / because this way we can unconditionally
829            # specify the library directory
830            print "Setting libdir{$1} to $2/\n" if $debug;
831            $libdir{$1}  = "$2/";
832        }
833        elsif (/^install_local_DIR\s*=\s*(.*)\s*$/) {
834            $install_local_dirs = $1;
835        }
836        elsif (/^doc_([\w-]*)_SOURCES\s*=\s*(.*)\s*$/) {
837            # Lowercase the type
838            $docsrc{lc($1)} = $2;
839            $globaldockind{lc($1)} = 1;
840            # Add any autoconf dir in $doc_namedefs
841            &LookForAutoconfDirs( $doc_namedefs );
842        }
843        elsif (/^doc_([\w-]*)_DIR\s*=\s*(.*)\s*$/) {
844            # Lowercase the type
845            $docdir{lc($1)} = $2;
846        }
847        elsif (/^profilelib_([@\${}\(\)\w-]*)_SOURCES\s*=\s*(.*)\s*$/) {
848            # proflib_<oldname>_SOURCES = files
849            $profile_library_sources{$1} = $2;
850            $found_profilelib = 1;
851        }
852        elsif (/^profilelib_([@\${}\(\)\w-]*)\s*=\s*(.*)\s*$/) {
853            # proflib_<oldname> = <newname>
854            $profile_libraries{$1} = $2;
855            $profile_libraries_basename{$2} = $1;
856            $libnum{$2} = $libcount++;
857            if ($do_sharedlibs) {
858                $libnum{$2.".la"} = $libcount++;
859            }
860            $found_profilelib = 1;
861        }
862        elsif (/^EXT_(\w+)_([\{\}\$\w]+)_SOURCES\s*=\s*(.*)/) {
863            # This is the extension hook for EXT_foo_name_SOURCES = data
864            # We can't just use foo_name_SOURCES because we allow
865            # programs to be defined that way (foo_name with SOURCES)
866            my $optype = $1;
867            my $opname = $2;
868            my $opsources = $3;
869            &CallModule( $optype, $opname, $opsources );
870        }
871        elsif (/^install_([\w-]*)\s*=\s*(.*)\s*$/) {
872            $install_files{$1} .= "$2 ";
873        }
874        elsif (/^installdir_([\w-]*)\s*=\s*(.*)\s*$/) {
875            $install_dirs{$1} .= "$2 ";
876        }
877        elsif (/^optinstall_([\w-]*)\s*=\s*(.*)\s*$/) {
878            # This is for files that will be installed only if present
879            $optinstall_files{$1} .= "$2 ";
880            if ($1 eq "DLLLIB") {
881                my $libname = $2;
882                $libname =~ s/\.\@SHLIB_EXT\@//;
883                $libname =~ s/^\s*lib//;
884                $alldlllibtargets[$#alldlllibtargets+1] =
885                    "${libloc}lib$libname.la";
886            }
887
888        }
889        elsif (/^optinstalldirs_([\w-]*)\s*=\s*(.*)\s*$/) {
890            # This is for files that will be installed only if present
891            $optinstall_dirs{$1} .= "$2 ";
892        }
893        elsif (/^SUBDIRS\s*=\s*(.*)\s*\r?$/) {
894            # The \r is used to remove any \r in DOS-style files
895            @subdirs = split(/\s+/,$1);
896            $subdirs_has_autoconf = 0;
897            $smmakevars{'SUBDIRS'} = $1;
898        }
899        elsif (/^SUBDIRS_(\w+)\s*=\s*(.*)\s*/) {
900            # use SUBDIRS_acname = realname to say that the
901            # autoconf variable acname, used in SUBDIRS, can
902            # have any of the values realname
903            $subdir_autoconf_vars{$1} = $2;
904            $subdir_optionals .= " $2";
905            # Also add as a make variable because other
906            # parts of the code will look for it as a raw variable.
907            $makevars{"SUBDIRS_$1"} = $2;
908        }
909        elsif (/^DOC_SUBDIRS\s*=\s*(.*)\s*\r?$/) {
910            # The \r is used to remove any \r in DOS-style files
911            @doc_subdirs = split(/\s+/,$1);
912            $smmakevars{'DOC_SUBDIRS'} = $1;
913        }
914        elsif (/^DOCDESTDIRS\s*=\s*(.*)\s*\r?$/) {
915        # kind:dir [, kind:dir ]*
916            $smmakevars{'DOCDESTDIRS'} = $1;
917            for $pair (split(/,\s*/,$1)) {
918                $pair =~ /(.*):(.*)/;
919                $docthiskinddir{$1} = $2;
920            }
921        }
922        elsif (/^INSTALL_SUBDIRS\s*=\s*(.*)\s*\r?$/) {
923            @install_subdirs = split(/\s+/,$1);
924            $smmakevars{'INSTALL_SUBDIRS'} = $1;
925        }
926        elsif (/^NOTSIMPLEMAKE_SUBDIRS\s*=\s*(.*)\s*\r?$/) {
927            foreach my $dir (split(/\s+/,$1)) {
928                $notSimplemakeDirs{$dir} = 1;
929            }
930        }
931        elsif (/^EXTRA_PROGRAMS\s*=\s*(.*)\s*$/) {
932            foreach $program (split(/\s+/,$1)) {
933                $extra_programs{$program} = 1;
934            }
935            $smmakevars{'EXTRA_PROGRAMS'} = $1;
936        }
937        elsif (/^EXTRA_LIBS\s*=\s*(.*)\s*$/) {
938            foreach $lib (split(/\s+/,$1)) {
939                $extra_libs{$lib} = 1;
940            }
941            $smmakevars{'EXTRA_LIBS'} = $1;
942        }
943        elsif (/^TAGS_DIRS\s*=\s*(.*)\s*$/) {
944            # Keep track of tags dirs
945            @tags_dirs = split( /\s+/,$1);
946            $smmakevars{'TAGS_DIRS'} = $1;
947        }
948        elsif (/^EXTRA_DIRS\s*=\s*(.*)\s*$/) {
949            @extra_dirs = split( /\s+/,$1);
950            $smmakevars{'EXTRA_DIRS'} = $1;
951        }
952        elsif (/^OTHER_DIRS\s*=\s*(.*)\s*$/) {
953            @other_dirs = split( /\s+/,$1);
954            $smmakevars{'OTHER_DIRS'} = $1;
955        }
956        elsif (/^EXTERNAL_LIBS\s*=\s*(.*)\s*$/) {
957            foreach $lib (split(/\s+/,$1)) {
958                $external_libraries{$lib} = 1;
959            }
960            $smmakevars{'EXTERNAL_LIBS'} = $1;
961        }
962        elsif (/^(\w+)\s*\+=\s*(.*)\s*$/){
963            # Use this form to prepend values to some of the
964            # autoconf generated names, e.g., to change
965            # LIBS = \@LIBS\@
966            # to
967            # LIBS = \@EXAMPLE_LIBS\@ \@LIBS\@
968            # use
969            # LIBS += \@EXAMPLE_LIBS\@
970            $varname = $1;
971            $varvalue = $2;
972            $PrependVar{$1} = $2;
973        }
974        elsif (/^(\w*)_ADD\s*=\s*(.*)\s*$/) {
975            # This lets us define "nameAdd = value" by
976            # adding "name_ADD = value" to the makefile.sm
977            # We Could use the smvar form or the prepend form, but
978            # this gives us a slightly cleaner and more controled
979            # way (used for now only with docargs_ADD)
980            $varname = $1 . "Add";
981            $varvalue = $2;
982            $${varname} = $varvalue;
983        }
984        elsif ($nocomments && /^\s*#/) {
985               ;
986           }
987        elsif (/^smvar_(\w+)\s*=\s*(.*)/) {
988            # Allow the user to override any simplemake variable
989            # E.g.,
990            # smvar_autoconf = /foo/bar/fixedac
991            # causes simplemake to replace "autoconf" with "/foo/bar/fixedac"
992            $varname = $1;
993            $value   = $2;
994            # Save old values
995            $simplemake_vars{$varname} = $$varname;
996            $$varname = $value;
997            print STDERR "setting $varname to $value\n" if $debug;
998        }
999        elsif (/^smvarSubdir_(\w+)\s*=\s*(.*)/) {
1000            my $varname = $1;
1001            my $varvalue = $2;
1002            if ($varname =~ /;/ || $varvalue =~ /;/) {
1003                print STDERR "smvarSubdir_$varname=$varvalue must not contain a semicolon\n";
1004                print STDERR "This command will be ignored\n";
1005            }
1006            else {
1007                # Save the name with the CURRENT value, then update the
1008                # value
1009                my $oldvalue = "";
1010                if (defined($$varname)) {
1011                    $oldvalue = $$varname;
1012                }
1013                if ($oldvalue =~ /;/) {
1014                    print STDERR "Cannot use smvarSubdir_$varname to replace a value that includes a semicolon (current value is $oldvalue)\n";
1015                }
1016                else {
1017                    $gSubdirSMVarsSeen .= "$varname=$oldvalue;";
1018                    $$varname = $varvalue;
1019                }
1020            }
1021        }           
1022        elsif (/^noinst/) {
1023            # Automake target to identify some programs/libraries as
1024            # not to be installed.
1025            # Skip for now
1026            ;
1027        }
1028        elsif (/^([\w-]*)_SOURCES\s*=\s*(.*)\s*$/) {
1029            # programs
1030            $pgm = $1;
1031            $pgmsrc = $2;
1032            $programs{$pgm} = $pgmsrc;
1033            #---------------------Kumud_parallel_fix------------------------------
1034            # Add to targets
1035            # $alltargets[$#alltargets+1] = $pgm;
1036            # Keep track of source types
1037            &FindSrcTypes( $pgmsrc );
1038            # Keep track of source files
1039            &SaveSrcNames( $pgmsrc );
1040            # Find program source type
1041            $pgmsrctype{$pgm} = &FindPgmSrcType( $pgm, $pgmsrc );
1042        }
1043        elsif (/^([\w-]*)_LDADD\s*=\s*(.*)\s*$/) {
1044            $pgm_ldadd{$1} = $2;
1045        }
1046        elsif (/^LDADD\s*=\s*(.*)\s*$/) {
1047            $ldadd_all = $1;
1048        }
1049        elsif (/^([\w-]*)_DEPADD\s*=\s*(.*)\s*$/) {
1050            $pgm_depadd{$1} = $2;
1051        }
1052        elsif (/^DEPADD\s*=\s*(.*)\s*$/) {
1053            $depadd_all = $1;
1054        }
1055        elsif (/^([\w-]+)\s*=\s*(.*)\s*$/) {
1056            $other_vars .= "$origline";
1057            # Save all variable names
1058            $makevars{$1} = $2;
1059            # Look for special autoconf directory names
1060            &LookForAutoconfDirs( $_ );
1061        }
1062        elsif (/^([^:\s]*)\s*:(.*)$/) {
1063            # Remember user-defined targets.
1064            $usertargets{$1} = $_;
1065            $other_text .= "$origline";
1066            # We could copy lines until we saw a blank line
1067            if ($1 eq ".SUFFIXES") { $ExplicitSuffixes .= $2; }
1068            # Look for special autoconf directory names
1069            &LookForAutoconfDirs( $_ );
1070            &LookForSuffixes( $_ );
1071            &LookForVariables( $_ );
1072        }
1073        else {
1074            $other_text .= "$origline";
1075            # Look for special autoconf directory names
1076            if (!/^\s*#/) {
1077                &LookForAutoconfDirs( $_ );
1078            }
1079            &LookForVariables( $_ );
1080        }
1081    $origline = "";
1082    }
1083
1084    # For the simplemake maint target, see if smdir references
1085    # any of the autoconf directories (so that we'll include the
1086    # appropriate lines in the Makefile.in header)
1087    if ($maint_targets && $smdir && $smdir ne "") {
1088        &LookForAutoconfDirs( $smdir );
1089    }
1090
1091}
1092
1093sub WriteMfile {
1094    $maxline = 80;
1095    $output_filename = $_[0];
1096    # Write out the generated Makefile
1097    unlink $output_filename . ".new";
1098    open( FD, ">$output_filename.new" ) || die "Could not open $output_filename\n.new";
1099
1100    print FD "# This $output_filename created by simplemake.  Do not edit$newline$newline";
1101    if ($output_filename =~ /Makefile\.in/) {
1102        print FD "# \@configure_input\@$newline";
1103    }
1104    # Ensure that the default target takes us to "all"
1105    print FD "$newline$makeBlockSep";
1106    print FD "all: all-redirect$newline$newline";
1107    # Autoconf sets a number of directories that some tools (such as libtool)
1108    # may rely on. 
1109    if ($useinclude) {
1110        printMakeVariable( FD, "SHELL", "\@SHELL\@" );
1111        print FD "include $includedir/$makefilebase$newline";
1112        # Print out variables before generated targets
1113        print FD $other_vars;
1114        print FD "$newline";
1115    }
1116    else {
1117        # We may want to break DefaultRules into a pre and post version
1118        &DefaultVariables;
1119
1120        # Other variables
1121       
1122        # Print out variables before generated targets
1123        print FD $other_vars;
1124        print FD "$newline";
1125
1126        # If there were any uses of the smmakevars, add them to the
1127        # output here
1128        my $sawvar = 0;
1129        foreach my $var (keys(%vars_seen)) {
1130            if (defined($smmakevars{$var})) {
1131                print FD "$var = ";
1132                my $contline = "";
1133                foreach my $varline (split(/\n/,$smmakevars{$var})) {
1134                    print FD "$contline$varline";
1135                    $contline = "\\$newline\t";
1136                }
1137                print FD $newline;
1138                $sawvar = 1;
1139            }
1140        }
1141        if ($sawvar) { print FD $newline; }
1142
1143        &DefaultRules;
1144    }
1145
1146    &SMInvokeAction( "OutputHeader" );
1147
1148    # Generate the all-redirect: target (libraries, programs, and
1149    # anything specified by all-local)
1150    &TargetAll;
1151
1152    # Output the generated targets.  First, the libraries and the shared
1153    # libraries
1154    &TargetLibraries;
1155    if ($do_sharedlibs) {
1156        &TargetSharedLibraries( \%libraries );
1157        if (defined($optinstall_files{'SHLIB'})) {
1158            &CreateOptInstallSHLibs( 'SHLIB' );
1159        }
1160        if (defined($optinstall_files{'DLLLIB'})) {
1161            print STDOUT "DLLLIB target in $curdir\n" if $debug;
1162            &CreateOptInstallSHLibs( 'DLLLIB' );
1163        }
1164    }
1165
1166    # Handle any specifically requested shared libraries (ones that
1167    # have no static counterpart)
1168    if (%shared_libraries) {
1169        # If any shared libraries were requested...
1170        &TargetSharedLibraries( \%shared_libraries );
1171        foreach $libname (keys(%shared_libraries)) {
1172            &TargetSharedLibraryFinal( "lib$libname.la", "lib$libname.\@SHLIB_EXT\@", "." );
1173        }
1174    }
1175
1176    if ($do_profilelibs && $found_profilelib) {
1177        &print_make_endline( FD );
1178        print FD $makeBlockSep;
1179        &TargetProfileLibraries;
1180        print FD $makeBlockSep;
1181    }
1182
1183    # Coverage analysis
1184    &TargetGcov;
1185   
1186    #------------kumud_parallel_fix---------------------------------------
1187    &TargetExecutables;
1188
1189    #------------------kumud_parallel_fix-------------------------------------------
1190    #each executable to be built is listed as prerequisite for all-executable-local
1191    &TargetProgramsLocal;
1192
1193    # Next, the programs
1194    &TargetPrograms;
1195
1196    # Documentation
1197    &TargetDocs;
1198
1199    print FD $makeBlockSep;
1200    &TargetInstall;
1201    print FD $makeBlockSep;
1202   
1203
1204    # This is ugly, but we need to tell the install target when we're at
1205    # the top for the documentation.  This should be promoted to
1206    # a more general sense of "at the top" for all areas.
1207    $doc_attop = 0;
1208
1209    if ($do_dependencies ne "no") {
1210        if ($do_dependencies eq "static") {
1211            &TargetDependenciesStatic;
1212        }
1213        elsif ($do_dependencies eq "ignore") {
1214            # Add a null target so that recursive targets work
1215            print FD "dependencies:$newline";
1216        }
1217        else {
1218            &TargetDependenciesDynamic;
1219        }
1220    }
1221    elsif ($dependenciesDummy eq "yes") {
1222        print FD "# Dummy target$newline";
1223        print FD "dependencies:$newline$newline";
1224    }
1225
1226
1227    # Tags
1228    print FD $makeBlockSep;
1229    &TargetTags;
1230    print FD $makeBlockSep;
1231
1232    # Unrecognized lines go here
1233    print FD $other_text;
1234
1235    # Add a final target, used by gnumake
1236    print FD "${newline}FORCE_TARGET:${newline}${newline}";
1237
1238    close FD;
1239
1240    &ReplaceIfDifferent( $output_filename, $output_filename . ".new" );
1241
1242    # FIXME: Make the file read only
1243    # ($dev,$ino,$mode) = stat $output_filename
1244    # Modifiy $mode to remove write permissions
1245    # use chmod $mode $output_filename
1246    # to change permissions
1247
1248    # If the user overrode any variables, restore them here
1249    foreach $varname (keys(%simplemake_vars)) {
1250        print STDERR "Restoring $varname to $simplemake_vars{$varname}\n" if $debug;
1251        $$varname = $simplemake_vars{$varname}
1252    }
1253}
1254
1255#
1256# ===========================================================================
1257# Output files may contain either a set of default rules, written by this
1258# routine, or an include of a set of base rules.
1259#
1260sub DefaultVariables {
1261    # SHELL must be in uppercase for Make to use it as the shell to
1262    # execute commands with.
1263    printMakeVariable( FD, "SHELL", "\@SHELL\@" );
1264    printMakeVariable( FD, "LIB_SUBSYSTEM", "\@LIB_SUBSYSTEM\@" );
1265    # Library definitions
1266    #if (scalar(%libraries)) {
1267        # Add ar, ranlib definitions if there are any library targets.
1268        printMakeVariable( FD, "AR", "\@AR\@" );
1269        printMakeVariable( FD, "RANLIB", "\@RANLIB\@" );
1270    #}
1271    if ($do_sharedlibs) {
1272        if (defined($optinstall_files{'SHLIB'}) ||
1273            defined($optinstall_files{'DLLLIB'})) {
1274            # Add the definition of libtool in case we're using
1275            # libtool to provide the shared library.
1276            printMakeVariable( FD, "LIBTOOL", "\@LIBTOOL\@" );
1277            printMakeVariable( FD, "CREATESHLIB", "\@CREATESHLIB\@" );
1278            print FD "$shlibdefs{'c'}$newline";
1279        }
1280        elsif ($found_sharedlib) {
1281            # No install target, but a shared library is begin built
1282            # Add the definition of libtool incase we're using
1283            # libtool to provide the shared library.
1284            printMakeVariable( FD, "LIBTOOL", "\@LIBTOOL\@" );
1285            printMakeVariable( FD, "CREATESHLIB", "\@CREATESHLIB\@" );
1286            print FD "$shlibdefs{'c'}$newline";
1287            printMakeVariable( FD, "MKDIR_P", "\@MKDIR_P\@" );
1288        }
1289    }
1290
1291    if (scalar(%install_files) || scalar(%optinstall_files)) {
1292        print FD "INSTALL         = \@INSTALL\@$newline";
1293        print FD "INSTALL_PROGRAM = \@INSTALL_PROGRAM\@$newline";
1294        print FD "INSTALL_SCRIPT  = \@INSTALL_SCRIPT\@$newline";
1295        print FD "INSTALL_DATA    = \@INSTALL_DATA\@$newline";
1296        printMakeVariable( FD, "MKDIR_P", "\@MKDIR_P\@" );
1297    }
1298
1299    # Directory definitions
1300    %dir_added = ();
1301    foreach $dir (keys(%dirs_seen)) {
1302        if (!defined($dir_added{$dir})) {
1303            print FD "$dirdefs{$dir}$newline";
1304            $dir_added{$dir} = 1;
1305            if (defined($required_dirs{$dir})) {
1306                foreach $rdir (split(/\s+/,$required_dirs{$dir})) {
1307                    if (!defined($dir_added{$rdir})) {
1308                        print FD "$dirdefs{$rdir}$newline";
1309                        $dir_added{$rdir} = 1;
1310                    }
1311                }
1312            }
1313        }
1314    }
1315    if (scalar(%install_files) || scalar(%optinstall_files)) {
1316        if (!defined($dir_added{'prefix'})) {
1317            $dir_added{'prefix'} = 1;
1318            print FD "$dirdefs{'prefix'}$newline";
1319        }
1320    }
1321    foreach $dir (keys(%install_files),keys(%optinstall_files)) {
1322        # Handle the derived dirs for the install directories
1323        $dir = $InstallDirFromKind{$dir};
1324        if (!defined($required_dirs{$dir})) {
1325            print STDERR "Warning: No entry $dir in required_dirs\n";
1326        }
1327        foreach $rdir (split(/\s+/,$required_dirs{$dir})) {
1328            if (!defined($dir_added{$rdir})) {
1329                print FD "$dirdefs{$rdir}$newline";
1330                $dir_added{$rdir} = 1;
1331            }
1332        }
1333    }
1334    foreach $dir (keys(%install_files),keys(%optinstall_files)) {
1335        $dir = $InstallDirFromKind{$dir};
1336        if (!defined($dir_added{$dir})) {
1337            #$resultdir = $dirdefs{$dir};
1338            if (!defined($dirdefs{$dir})) {
1339                print STDERR "Warning: no entry $dir in dirdefs\n";
1340            }
1341            print FD "$dirdefs{$dir}$newline";
1342            $dir_added{$dir} = 1;
1343        }
1344    }
1345
1346    &InstallDocDirs;
1347
1348    # Miscellaneous.  This needs to be improved.  This is really needed
1349    # only for some targets
1350    # The definition of DEFS is the same as for Automake
1351    if (defined($ext_seen{"c"}) || defined($ext_seen{"cxx"}) ||
1352        defined($ext_seen{"cpp"})) {
1353        if (!defined($makevars{'DEFS'})) {
1354            printMakeVariable( FD, "DEFS", "\@DEFS\@ -I. -I\${srcdir}" );
1355        }
1356        # What to do about includes?  If they were set explicitly,
1357        # don't use the default.
1358        if (!defined($makevars{"INCLUDES"})) {
1359            printMakeVariable( FD, "INCLUDES", $include_list );
1360        }
1361        if (!defined($makevars{"CPPFLAGS"})) {
1362            printMakeVariable( FD, "CPPFLAGS", "\@CPPFLAGS\@" );
1363        }
1364    }
1365    # Add the LIBS if there are any programs to build
1366    if (scalar(%pgmlinktypes)) {
1367        if (!defined($makevars{"LIBS"})) {
1368            printMakeVariable( FD, "LIBS", "\@LIBS\@" );
1369        }
1370    }
1371
1372    # If there are subdirs, we need make.  Also needed by
1373    #    shared library support
1374    #    profile library support
1375    #    postambles
1376    #    local targets
1377    #    install (but a subset of subdir)
1378    # so we always add MAKE (originally checked for $#subdirs >= 0
1379    # and $#doc_subdirs >= 0)
1380    if (! defined($makevars{"MAKE"}) ) {
1381        printMakeVariable( FD, "MAKE", "\@MAKE\@" );
1382    }
1383
1384    # Add any standard definitions
1385    if ($commonmake ne "") {
1386        print FD "$commonmake$newline";
1387    }
1388
1389    # Definitions for each possible program type seen
1390    $any_prog_def = 0;
1391    foreach $ext (keys(%ext_seen)) {
1392        print "ext seen is :$ext:\n" if $debug;
1393        $extkey = "$ext:o";
1394        if (defined($extdef{$extkey})) {
1395            foreach $line (split(/\n/,$extdef{$extkey})) {
1396                # Check for an override
1397                if ($line =~ /^(\w+)(\s*)=(.*)/) {
1398                    my $var = $1;
1399                    my $spacing = $2;
1400                    my $value = $3;
1401                    if (defined($makevars{$var})) {
1402                        print "Using override definition of $var\n" if $debug;
1403                        next;
1404                    }
1405                    if (defined($PrependVar{$var})) {
1406                        $line = "$var$spacing= " . $PrependVar{$var} . " $value";
1407                    }
1408                }
1409                print FD "$line$newline";
1410            }
1411        }
1412        if (defined($pgmlinktypes{$ext})) {
1413            # Allow the user to override the definition
1414            my $def = $progdefs{$ext};
1415            if ($def =~ /(\S+)\s*=.*/) {
1416                $def = $1;
1417            }
1418            if (!defined($makevars{$def})) {
1419                print FD "$progdefs{$ext}$newline";
1420            }
1421            $any_prog_def = 1;
1422        }
1423        if ($do_sharedlibs || $found_sharedlib) {
1424            if ($#allshlibtargets >= 0) {
1425                # Only add the libtool definition if there are targets that
1426                # may need it.
1427                printMakeVariable( FD, "LIBTOOL", "\@LIBTOOL\@" );
1428                # We only need CREATESHLIB to finish off the library
1429                if (%shared_libraries) {
1430                    printMakeVariable( FD, "CREATESHLIB", "\@CREATESHLIB\@" );
1431                }
1432            }
1433            $extkey = "$ext:lo";
1434            if (defined($extdef{$extkey})) {
1435                print FD "$extdef{$extkey}$newline";
1436            }
1437            else {
1438                print FD $newline;
1439            }
1440               
1441        }
1442    }
1443    if ($any_prog_def) {
1444        # These are special definitions that are shared by all
1445        # pgmlink types
1446        if (!defined($makevars{"LDFLAGS"})) {
1447            my $otherflags = "";
1448            if (defined($PrependVar{'LDFLAGS'})) {
1449                $otherflags = $PrependVar{'LDFLAGS'};
1450            }
1451            print FD "LDFLAGS     = $otherflags \@LDFLAGS\@ $ldadd_all$newline";
1452        }
1453    }
1454    print FD "$newline";
1455#    foreach $ext (keys(%pgmlinktypes)) {
1456#    }
1457
1458    if ($vpath_config) {
1459        print FD '@VPATH@'; print FD "$newline";
1460    }
1461    else {
1462        # Some make programs require a specific directory, not a make
1463        # variable, in the VPATH specification
1464        print FD "VPATH = .:\@srcdir\@$newline";
1465    }
1466
1467    &VariableDocs;
1468}
1469
1470sub DefaultRules {
1471
1472    # Add the compilation rules.  Include only those needed for the
1473    # given files.  Remove all default suffix rules
1474    if (scalar(%ext_seen)) {
1475        $suffixes = ".o";
1476        if ($maint_perf_targets && !($suffixes =~ /\.s/)) {
1477            $suffixes .= " .s";
1478        }
1479        if ($do_sharedlibs || $found_sharedlib) {
1480            $suffixes .= " .lo";
1481        }
1482    }
1483    foreach $ext (keys(%ext_seen)) {
1484        $suffixes .= " .$ext";
1485    }
1486   
1487    # Finally, update suffixes from any other source.  Currently, this
1488    # handles the suffixes for document generation.
1489    &SuffixDocs;
1490
1491    print FD ".SUFFIXES:$newline";
1492    # Grrr.
1493    # OSF1 make complains if there are no suffix items.  To make it happy,
1494    # *always* add .o .c
1495    if ("$suffixes $ExplicitSuffixes" ne " ") {
1496        print FD ".SUFFIXES: $suffixes $ExplicitSuffixes$newline";
1497    }
1498    else {
1499        print FD "# Some make programs complain if no suffixes are set$newline";
1500        print FD ".SUFFIXES: .c .o$newline";
1501    }
1502
1503    # To make it easier to build programs, conditionally add a
1504    # default "build program" rule from the seen sourcecode extensions
1505    foreach $ext (keys(%ext_seen)) {
1506        # Skip any rules for .o files that we've seen
1507        if ($ext eq "o") { next; }
1508        # If we overrode the default rule for this key, then skip that
1509        # as well
1510        if (defined($usertargets{".$ext.o"})) { next; }
1511        print FD ".$ext.o:$newline";
1512        if ($found_profilelib) {
1513            # Use a special rule when building the non-profile-lib version
1514            $extkey = "$ext:o";
1515            # COMMAND PRINTING
1516            if (defined($extstring{$extkey})) {
1517                &PrintVerboseOptionCommand( "$extrules_with_profile{$extkey}",
1518                                            "-", "$extstring{$extkey}" );
1519            }
1520            else {
1521                print FD "\t$extrules_with_profile{$extkey}$newline";
1522            }       
1523        }
1524        else {
1525            $extkey = "$ext:o";
1526            if (defined($extrules{$extkey})) {
1527                # COMMAND PRINTING
1528                if (defined($extstring{$extkey})) {
1529                    &PrintVerboseOptionCommand( "$extrules{$extkey}", "-",
1530                                                "$extstring{$extkey}" );
1531                }
1532                else {
1533                    print FD "\t$extrules{$extkey}$newline";
1534                }
1535            }
1536            else {
1537                print FD $newline;
1538            }
1539        }
1540        if ($do_sharedlibs || $found_sharedlib) {
1541            $extkey = "$ext:lo";
1542            print FD ".$ext.lo:$newline";
1543            if (defined($extrules{$extkey})) {
1544                # COMMAND PRINTING
1545                if (defined($extstring{$extkey})) {
1546                    # the lo rules have newlines in them, so we need to escape them,
1547                    # as well as remove any @ prefixes
1548                    my $escaped_rule = $extrules{$extkey};
1549                    $escaped_rule =~ s/$newline(\t+)\@*/ ; \\$newline$1echo /g;
1550                    &PrintVerboseOptionCommand( "$extrules{$extkey}", "-",
1551                                                "$extstring{$extkey}" );
1552                }
1553                else {
1554                    print FD "\t$extrules{$extkey}$newline";
1555                }
1556            }
1557        }
1558        # For maintainers, make it easy to create the asm versions
1559        if ($maint_perf_targets) {
1560            $extkey = "$ext:s";
1561            if (defined($extrules{$extkey})) {
1562                print FD ".$ext.s:$newline";
1563                print FD "\t$extrules{$extkey}$newline";
1564            }
1565        }
1566        if ($maint_targets) {
1567            # Add the target that applies the preprocessor to the source file
1568            $extkey = "$ext:txt";
1569            if (defined($extrules{$extkey})) {
1570                print FD ".$ext.txt:$newline";
1571                print FD "\t$extrules{$extkey}$newline";
1572            }
1573        }
1574
1575        $extkey = "$ext:";
1576        # We may want to make this conditional, only generating it
1577        # when desired.
1578        if (defined($extrules{$extkey})) {
1579            print FD ".$extkey$newline";
1580            # COMMAND PRINTING
1581            if (defined($extstring{$extkey})) {
1582                &PrintVerboseOptionCommand( "$extrules{$extkey}", "-",
1583                                            "$extstring{$extkey}" );
1584            }
1585            else {
1586                print FD "\t$extrules{$extkey}$newline";
1587            }
1588        }
1589    }
1590   
1591    # Other generic rules.  Currently, only for documents
1592    &RuleDocs;
1593
1594    # Configure update targets
1595    if ( -s "configure.in" && $maint_targets ) {
1596        # Convert ROOTDIR as necessary
1597        $aargs = $autoconf_args;
1598        if (!$rootdirpath || $rootdirpath eq "") {
1599            $aargs =~ s/ROOTDIR/\./;
1600        }
1601        else {
1602            #chomp( $rootdir =  $rootdirpath );
1603            ( $rootdir =  $rootdirpath ) =~ s/[\r\n]*$//; # David added
1604                #strip( $rootdir = $rootdirpath );
1605            $aargs =~ s/ROOTDIR/$rootdir/;
1606        }
1607        $aargs =~ s/\/\//\//;
1608        $autoconf_deps="";
1609        print "macro loc arg is $aargs\n" if $debug_confdir;
1610        # If there is a -l dir in the autoconf_args, then add that to the
1611        # dependencies (We use $acincdir_arg incase autoconf 2.57 is used,
1612        # in which case the argument is -I or -B, or in case autoconf 2.58
1613        # or later is used, in which case the argument may be changed again.
1614        # Argh.  In autoconf 2.59, -B doesn't work
1615        if ($aargs =~ /$acincdir_arg\s*([\.\/\w]*)/) {
1616            $macroloc = $1;
1617            # HACK.  If we've messed up the location, don't include it
1618            if (-s "$macroloc/aclocal.m4") {
1619                $autoconf_deps .= "$macroloc/aclocal.m4";
1620                # Extract includes from aclocal.m4
1621                open (AFD, "<$macroloc/aclocal.m4" );
1622                while (<AFD>) {
1623                    if (/^\s*builtin\(include,([\w-]*\.m4)\)\s*$/) {
1624                        $filename = "$macroloc/$1";
1625                        $autoconf_deps .= " $filename";
1626                    }
1627                }
1628                close (AFD);
1629            }
1630        }
1631        # Extract includes from configure.in
1632        open (AFD, "<configure.in" );
1633        while (<AFD>) {
1634            if (/^\s*builtin\(include,([\w\-\/\.]*\.m4)\)\s*$/)
1635            {
1636                $filename = $1;
1637                if (-s "$filename")
1638                {
1639                    $autoconf_deps .= " $filename";
1640                }
1641                elsif (($filename =~ /[^\.\/]+/) && defined($macroloc) && -s "$macroloc/$filename")
1642                {
1643                    $autoconf_deps .= " $macroloc/$filename";
1644                }
1645            }
1646        }
1647        close (AFD);
1648        #
1649        print FD "$newline";
1650        $header_depend="";
1651        if ($configure_has_config_headers ne "no") {
1652            $header_depend="\${srcdir}/$configure_has_config_headers ";
1653            if ($debugConfigHeaderDepend) {
1654                print "Adding $header_depend to configure target\n";
1655            }
1656        }
1657        &print_make_longline( FD,  "$header_depend \${srcdir}/configure: \${srcdir}/configure.in $autoconf_deps" );
1658        &print_make_setpos( 8 );
1659        &FindWorkingAutoconf ;
1660        # Use autoheader only if AC_CONFIG_HEADER is in the configure file
1661        #
1662        # With Autoconf 2.57, there is a "cache" that like all automake
1663        # caches, isn't reliable and must be removed
1664#       &print_make_longline( FD, "\t\@if [ -d autom4te.cache ] ; then rm -rf autom4te.cache ; fi" );
1665        # With some versions of autoconf, this cache has the version
1666        # number in it (!)
1667        &print_make_longline( FD, "\t\@rm -rf autom4te*.cache" );
1668        if ($configure_has_config_headers ne "no") {
1669            &print_make_longline( FD,  "\t(cd \${srcdir} && $autoheader_prog $aargs && \\$newline\t$autoconf $aargs )" );
1670        }
1671        else {
1672            &print_make_longline( FD,  "\t(cd \${srcdir} && $autoconf $aargs )" );
1673        }
1674        if ($fixup_autoconf_cd) {
1675            # This is needed for DOS in case the pwd contains blanks
1676            print FD "\t( cd \${srcdir} && sed -e 's/cd *\$\$ac_popdir/cd \"\$\$ac_popdir\"/g' configure > c.tmp ; mv -f c.tmp configure ; chmod a+x configure)$newline";
1677        }
1678    }
1679    if ($maint_targets && $smdir && $smdir ne "") {
1680        # FIXME: make smdir take a value from the Makefile.in (e.g,
1681        # $(top_abs_src)/maint instead of the location where it
1682        # was originally run.
1683        print FD "$newline";
1684        print FD $makeBlockSep;
1685        print FD "\${srcdir}/Makefile.in: \${srcdir}/Makefile.sm$newline";
1686        print FD "\t( cd \${srcdir} && $smdir/simplemake \\$newline";
1687        if ($rootdir) {
1688            print FD "\t-rootdir=$rootdir \\$newline";
1689        }
1690        print STDOUT "last_config_dir is $last_config_dir in $curdir\n" if $debug_confdir;
1691        if (defined($last_config_dir) && $last_config_dir ne "") {
1692            print FD "\t-configdir=$last_config_dir \\$newline";
1693        }
1694        foreach $curarg (@keepargs) {
1695            # Skip some special cases
1696            if ($curarg =~ /^-smvar_doc_attop=0/) { next; }
1697            # Must handle $ specially
1698            $tmparg = $curarg;
1699#           # FIXME: Should this be s/../g (change all instances)?
1700#           $tmparg =~ s/\$/\\\$\$/;
1701            if ($tmparg =~ /\s/) {
1702                print FD "\t\"$tmparg\" \\$newline";
1703            }
1704            else {
1705                print FD "\t$tmparg \\$newline";
1706            }
1707        }
1708        if ($lcurdir && defined($autoconf_files_by_dir{$lcurdir})) {
1709            print FD "\t-distcleanfiles=\"$autoconf_files_by_dir{$lcurdir}\" \\$newline";
1710        }
1711        print FD "\t-smvar_doc_attop=0 \\$newline";
1712        print FD "\t\tMakefile.sm )$newline";
1713        print FD "Makefile: \${srcdir}/Makefile.in$newline";
1714
1715        # The following does not always work correctly.  There may be
1716        # problem in handling jumps between directories
1717        my $real_last_config_dir = $last_config_dir;
1718        if (defined($makefile_configdir)) {
1719            $real_last_config_dir = $makefile_configdir;
1720            print "Replacing last config dir with $real_last_config_dir\n";
1721        }
1722       
1723        my $topdir = &GetPathToParent( $curdir, $real_last_config_dir );
1724        print "last config dir = $real_last_config_dir, topdir = $topdir\n" if $debug_confdir;
1725        if ($topdir eq "") {   
1726            $topdir = ".";
1727        }
1728
1729        # We need to use the enclosing configure, not always the top-level
1730        # configure.  Thus, we need to keep track of the directory of the
1731        # current configure, and the path to get to that configure.
1732        # We also allow this step to fail; for example, the
1733        # config.status may already have been removed.
1734        # Further, to make the clean step cleaner, we test for the
1735        # config.status file before trying to run it (using a simple
1736        # test -x config.status && ... works, but still generates noise
1737        # about ignoring a failing step.
1738
1739        $ignore_step = "-";
1740
1741        if ($topdir ne ".") {
1742            print FD "\t-cd $topdir && \\$newline";
1743            $ignore_step = "";
1744        }
1745        $relcurdir = $curdir;
1746        if ($real_last_config_dir) {
1747            my $quoted_dir = quotemeta $real_last_config_dir;
1748            $relcurdir =~ s/^$quoted_dir//;
1749        }
1750        print STDOUT "curdir is $curdir and relcurdir is $relcurdir\n" if $debug_confdir;
1751
1752        print FD "\t${ignore_step}if [ -x config.status ] ; then CONFIG_FILES=${relcurdir}Makefile CONFIG_HEADERS= \${SHELL} ./config.status ; fi$newline";
1753        print FD $makeBlockSep;
1754    }
1755    # The following are general targets that can be used to run a program
1756    # specified on the make command line
1757    &TargetInit( "apply" );
1758    print FD "\n";
1759    print FD "\t\$(ACTION) \$(ACTION_INPUT)$newline";
1760    # ToDo: we could control the subdirectories over which the recursion
1761    # is applied.
1762    &RecursiveOp( "apply" );
1763    &TargetPostamble( "apply" );
1764   
1765    # Clean targets
1766    &TargetClean;
1767}
1768
1769#
1770# ===========================================================================
1771#
1772# Look at a list of source files and determine the source types
1773#
1774# Eventually, make this $ext_seen{$extension} = 1,
1775# then generate code by using keys(%ext_seen).  Allows general
1776# extensions and simpler handling of rules (like adding .F and .f90 )
1777sub FindSrcTypes {
1778    my $source = $_[0];
1779    my $files = "";
1780    foreach my $sym (split(/\s+/,$source)) {
1781        print STDERR "Is $sym a make variable?\n" if $debug;
1782        $vsym = $sym;
1783        if ($vsym =~ /\$[\{\(]?(\w*)[\}\)]?/) {
1784            $vsym = $1;
1785        }
1786        if (defined($makevars{$vsym})) {
1787            print STDERR "yes, value is $makevars{$vsym}\n" if $debug;
1788            $files .= " $makevars{$vsym}";
1789        }
1790        else {
1791            $files .= " $sym";
1792        }
1793    }
1794    foreach my $file (split(/\s+/,$files)) {
1795        ($name,$ext) = split('\.',$file);
1796        if (defined($ext) && $ext ne "") {
1797            $ext_seen{$ext} = 1;
1798        }
1799    }
1800}
1801
1802# Save all conventional sources
1803# This is only approximate.
1804# We want to allow source files to be specified through other
1805# variables (e.g., ${Foo_sources}).
1806# Globals: regular_sources, regular_headers
1807sub SaveSrcNames {
1808    my $source = $_[0];
1809    my @files;
1810    my $file;
1811    # First, expand the source variable
1812    #print STDERR "Got $source ...\n";
1813    foreach $file (split(/\s+/,$source)) {
1814        #print STDERR "Checking $file ...\n";
1815        # Substitute for any make variables (1 level of substitution)
1816        $file = &ExpandMakeVars( $file );
1817        foreach $name (split(/\s+/,$file)) {
1818            $files[$#files+1] = $name;
1819        }
1820    }
1821   
1822    foreach $file (@files) {
1823        ($name,$ext) = split( '\.',$file);
1824        if (defined($ext)) {
1825            if (defined($extrules{"$ext:o"})) {
1826                $regular_sources .= " $file";
1827                $sources{$file} = 1;
1828            }
1829            elsif ($ext eq "h") {
1830                # FIXME: need to handle other header extensions;
1831                # e.g., MPICH2 uses .i as well
1832                $regular_headers .= " $file";
1833                $headers{$file} = 1;
1834            }
1835        }
1836    }
1837}
1838
1839#
1840# Find the name of the source file that matches the program.
1841# If none found, use c as the type
1842sub FindPgmSrcType {
1843    $pgm = $_[0];
1844    $pgmsrc = $_[1];
1845    # Also keep track of the types seen
1846    my %exttypes;
1847    my $firstext = "";
1848    foreach $file (split(/\s+/,$pgmsrc)) {
1849        ($name,$ext) = split('\.',$file);
1850        if ($name eq $pgm) {
1851            $pgmlinktypes{$ext} = 1;
1852            return $ext;
1853        }
1854        else {
1855            $exttypes{$ext} = 1;
1856            if ($firstext eq "") { $firstext = $ext; }
1857        }
1858    }
1859    if (defined($exttypes{"c"})) {
1860        $pgmlinktypes{"c"} = 1;
1861        return "c";
1862    }
1863    elsif (defined($exttypes{"cxx"})) {
1864        $pgmlinktypes{"cxx"} = 1;
1865        return "cxx";
1866    }
1867    elsif (defined($exttypes{"f90"})) {
1868        $pgmlinktypes{"f90"} = 1;
1869        return "f90";
1870    }
1871    else {
1872        $pgmlinktypes{$firstext} = 1;
1873        return $firstext;
1874    }
1875}
1876
1877sub ClearVars {
1878    # Extensions seen is a property of the makefile
1879    %ext_seen = ();
1880    # We include abs_srcdir because it is useful to know and some
1881    # steps may conditionally need it (so we may not know that we also
1882    # need abs_srcdir until it is too late to add it)
1883    # We include abs_builddir because it is useful to have the
1884    # build directory around (particularly for the TAGS step)
1885    %dirs_seen = ( "srcdir" => 1, "abs_srcdir" => 1, "abs_builddir" => 1 );
1886    $other_vars = "";
1887    $other_text = "";
1888    $regular_sources = "";
1889    #$header_sources = "";
1890    $regular_headers = "";
1891    %sources = ();
1892    %headers = ();
1893
1894    # Targets
1895    @alltargets = ();   # implicit targets
1896    @allshlibtargets = (); # implicit shared library targets
1897    @alldlllibtargets = (); # implicit dynamically loaded library targets
1898    %altalltargets = ();   # related targets to items in alltargets
1899    %usertargets = ();  # explicit, user-defined targets
1900    %extra_programs = ();
1901    %extra_libs     = ();
1902    %libraries = ();
1903    $libcount = 0;
1904    %libnum    = ();    # Gives number associated with library
1905    %shared_libraries = ();
1906    %shared_libraries_exports = ();
1907    %shared_libraries_libs = ();
1908    %profile_libraries = ();
1909    %profile_libraries_basename = (); # inverse of profile_libraries
1910    %profile_library_sources = ();
1911    %install_files = ();
1912    @install_subdirs = ();
1913    %install_dirs = ();
1914    %optinstall_files = ();
1915    $install_local_dirs = "";
1916    $gIssuedInstallLocal = 0;
1917    %libNotShared = ();
1918    %external_libraries = ();
1919    $found_profilelib = 0;
1920    $found_sharedlib  = 0;
1921    $InitSharedLibraryFinal = 0;
1922    %programs = ();
1923    %pgm_ldadd = ();
1924    $ldadd_all = "";
1925    %pgm_depadd = ();
1926    $depadd_all = "";
1927
1928    $gSubdirSMVarsSeen = "";
1929
1930    # Variables
1931    # makevars are variables seen in the Makefile.sm
1932    # addedMakeVars are variables that have been added to the output
1933    # Makefile.in
1934    %PrependVar = ();
1935    %makevars = ();
1936    %addedMakeVars = ();
1937    # smmakevars are variables that have been defined as SM variables.
1938    %smmakevars = ();
1939    # vars_seen is a hash of the variables used in the makefile
1940    %vars_seen = ();
1941    # Information about program targets
1942    %pgmlinktypes = ();
1943    # Other directories
1944    @subdirs = ();
1945    %notSimplemakeDirs = ();
1946    %subdir_autoconf_vars = ();
1947    $subdir_optionals = "";
1948    @doc_subdirs = ();
1949    $docargsAdd = "";
1950    %docthiskinddir = ();
1951    @extra_dirs = ();
1952    @tags_dirs  = ();
1953    @other_dirs = ();
1954    $subdirs_has_autoconf = 0;
1955    # Suffix definitions
1956    $ExplicitSuffixes = "";
1957    $suffixes = "";
1958
1959    # Document sources and directories
1960    %docdir = ();
1961    %docsrc = ();
1962    # These may be overriden on a file by file basis
1963    $autoconf = $autoconf_prog; # Name of autoconf program to use
1964    $autoconf_version = ""; # Any version is allowed
1965    # We cannot clear config_headers here because we may still
1966    # need to know that the configure in the current directory
1967    # has a header file, and this routine to clear vars is called for
1968    # every file.
1969    #$configure_has_config_headers = "no";
1970    %simplemake_vars = ();
1971
1972    # For any extensions, clear their global variables.
1973    &SMInvokeAction( "Clear" );
1974
1975}       
1976
1977#
1978# Expand all of the make variables in an expression.  This
1979# lets users use targets like
1980# libmpich_SOURCE_a = ${MPI_SOURCES}
1981sub ExpandMakeVars {
1982    # look for ${\w*} and replace with the value of $makevars{$1}
1983    my $line = $_[0];
1984    print "Looking at $line\n" if $debug;
1985
1986    if (!defined($line)) { return ""; }
1987
1988    my $after = "";
1989    my $processed = "";
1990    while ($line =~ /([^\$]*)\$([{\(])(\w+)([}\)])(.*)/) {
1991        my $before = $1;
1992        my $lb   = $2;
1993        my $mvar = $3;
1994        my $rb   = $4;
1995        $after   = $5;
1996        print "replacing \$$lb$mvar$rb\n" if $debug;
1997        # Rescan the replacement in case it contains a variable.
1998        # Undefined variables are left in place
1999        if (defined($makevars{$mvar})) {
2000            $processed .= $before;
2001            $line = $makevars{$mvar} . $after;
2002        }
2003#       elsif (defined($dirdefs{$mvar})) {
2004#           $processed .= $before;
2005#           $line = $dirdefs{$mvar} . $after;
2006#       }
2007        else {
2008            $processed .= $before . "\$$lb$mvar$rb";
2009            $line      = $after;
2010        }
2011    }
2012    $processed .= $line;
2013    print "expanded to $processed\n" if $debug;
2014    return $processed;
2015}
2016
2017#
2018# ===========================================================================
2019@config_dir = ();    # Stack of the location of the most recently seen
2020                     # configure script.  Used to create targets that
2021                     # need to run config.status from that directory.
2022
2023$last_config_dir = "";
2024
2025#
2026# ===========================================================================
2027
2028# These next two routines let us print out the file being processed only
2029# when we need to (e.g., before an error message).
2030$curFilename = "";
2031$curFilenamePrinted = 0;
2032sub ResetFileName {
2033    $curFilename = $_[0];
2034    $curFilenamePrinted = 0;
2035}
2036sub ShowFileName {
2037    if ($curFilenamePrinted) { return; }
2038    print "Processing $curdir$file\n" if (!$quiet && $debug_dirs);
2039    $curFilenamePrinted = 1;
2040}
2041
2042sub ProcessFile {
2043    $file = $_[0];
2044
2045    $gSubdirSMVarsSeen = "";
2046
2047    # FIXME: curdir?
2048    if (!$curdir) { $curdir = ""; }
2049    &ResetFileName( "$curdir$file" );
2050    print "Processing $curdir$file\n" if (!$quiet && $debug_dirs);
2051    $configure_has_config_headers = "no";
2052    if (-s "configure.in") {
2053        &ReadAutoconf;
2054        print "Found configure.in in $curdir, set last_config_dir to $curdir\n" if $debug_confdir;
2055        if ($curdir eq "") { $last_config_dir = "."; }
2056        else {  $last_config_dir = $curdir; }
2057    }
2058    &ReadMfile( $file );
2059    $output_name = $file;
2060    if ($create_configure_input) {
2061        $output_name =~ s/\.sm$/.in/;
2062    }
2063    &WriteMfile( $output_name );
2064   
2065    if ($gCheckForTargets) {
2066        &checkForTargets();
2067    }
2068
2069    # Process any subdirectories
2070    # The list of directories to process comes from the variables
2071    # defined in the Makefile.sm.  The following is the list
2072    my @dirs = (@subdirs,@other_dirs,@doc_subdirs,@tags_dirs);
2073    # Get a local copy of the "notsimplemake" hash
2074    my %notSimplemake = %notSimplemakeDirs;
2075    # First, check for names that are replaced by autoconf (e.g., @name@)
2076    # in the names of the directories.  For those variables, there should
2077    # be a corresponding SUBDIRS_name variable in the makefile that lists
2078    # *all* directories to which @name@ may be expanded by configure.
2079    my @actdirs = ();
2080    foreach my $dir (@dirs) {
2081        $sdir = $dir;
2082        print "Checking $sdir\n" if ($debug_dirs);
2083        if ($sdir =~ /@([^@]*)@/) {
2084            $subst_name = $1;
2085            $subdirs_has_autoconf = 1;
2086            #print "Found $subst_name\n";
2087            # Look up the special name
2088            $var_name = "SUBDIRS_$subst_name";
2089            #print "varname is $var_name\n";
2090            if (defined( $makevars{$var_name} )) {
2091                # Concatenate the value of the variable name to the list
2092                # of directories
2093                @actdirs = ( @actdirs, split( /\s+/, $makevars{$var_name} ) );
2094            }
2095        }
2096        else {
2097            $actdirs[$#actdirs+1] = $dir;
2098        }
2099    }
2100
2101    # Push the saved subdir vars onto a stack, to be popped at the end.
2102    print "Saving $gSubdirSMVarsSeen\n" if $gDebugSubdirVar && ($gSubdirSMVarsSeen ne "");
2103    $subdirsSMVars[$#subdirsSMVars+1] = $gSubdirSMVarsSeen;
2104   
2105    # For each of the directories, process it.
2106    M: foreach my $dir (@actdirs) {
2107        if ($dir eq ".") { next M; }
2108        if ($dir =~ /\.\./ || $dir =~ /.\/./) {
2109            # Skip directory changes that aren't simple
2110            &ShowFileName;
2111            print "$dir has .. in it (skipping)\n";
2112            print "Current dir is $curdir\n" if $debug;
2113            next M;
2114            #exit(1);
2115        }
2116        if (! -d $dir) {
2117            my $ldir = `pwd`;
2118            if (!defined($notSimplemake{$dir})) {
2119                &ShowFileName;
2120                print "Directory $curdir$dir does not exist\n";
2121                print "(Current location is $ldir)\n";
2122            }
2123            next M; }
2124        if (! -s "$dir/$file") {
2125            if (!defined($notSimplemake{$dir})) {
2126                print "File $curdir$dir/$file does not exist\n";
2127            }
2128            next M; }
2129        chdir $dir || die "Cannot change to directory $dir\n";
2130        $curdir .= "$dir/";
2131        $curdir = &CleanCurDir( $curdir );
2132        if ($dir =~ /\.\./) {
2133            &ShowFileName;
2134            print "changed to a non-obvious dir = $dir\n";
2135            my $ldir = $dir;
2136            while ($ldir =~ /^\.\.\//) {
2137                $rootdirpath =~ s/\.\.\/$//;
2138                $ldir =~ s/^\.\.\///;
2139            }
2140            while ($ldir =~ /^[^\/]+\//) {
2141                $rootdirpath .= "../";
2142                $ldir =~ s/^[^\/]+\///;
2143            }
2144            if ($ldir =~ /\S+/) {
2145                $rootdirpath .= "../";
2146            }           
2147        }
2148        else {
2149            $rootdirpath .= "../";
2150        }
2151        print "rootdir = $rootdirpath\n" if $debug_confdir;
2152        print "curdir = $curdir\n" if $debug_confdir;
2153        # Remember the last place that we saw a configure; push and
2154        # pop for each file that we process.
2155        $config_dir[$#config_dir+1] = $last_config_dir;
2156        print "config stack has depth $#config_dir\n" if $debug_confdir;
2157        print "relative path to configure dir is " . &GetPathToParent( $curdir, $last_config_dir ) . "\n" if $debug_confdir;
2158        &ProcessFile( $file );
2159        $last_config_dir = $config_dir[$#config_dir]; $#config_dir--;
2160        print "after processing, last_config_dir = $last_config_dir\n" if $debug_confdir;
2161        print "config stack has depth $#config_dir\n" if $debug_confdir;
2162        $rootdirpath =~ s/\.\.\/$//;
2163        chdir "..";
2164        $curdir =~ s/[^\/]*\/$//;
2165        $curdir = &CleanCurDir( $curdir );
2166    }
2167    # End of processing directories
2168
2169    # Restore any variables that were changed for the scope of this directory
2170    # subtree (emulate a stack; don't trust perls dynamic scoped local)
2171    my $subdirvars = $subdirsSMVars[$#subdirsSMVars]; $#subdirsSMVars--;
2172    if (!defined($subdirvars)) {
2173        print STDERR "subdirsSMVars stack count = $#subdirsSMVars in $curdir\n";
2174        print STDERR "previous value is $subdirsSMVars[$#subdirsSMVars]\n";
2175    }
2176    foreach my $varstring (split(/;/,$subdirvars)) {
2177        if ($varstring =~ /(\w+)=(.*)/s) {
2178            my $varname = $1;
2179            my $varvalue = $2;
2180            print "Restoring $$varname to $varvalue in $curdir\n" if $gDebugSubdirVar;
2181            $$varname = $varvalue;
2182        }
2183        elsif ($varstring ne "") {
2184            print STDERR "Internal Error: varstring = $varstring\n";
2185        }
2186    }                         
2187}
2188
2189sub ListTargets {
2190  foreach $target (@alltargets) {
2191      # Skip the extra programs
2192      if (defined($extra_programs{$target})) { next; }
2193      if (defined($extra_libs{$target})) { next; }
2194      # Add any alternate target (used for targets in other directories
2195      # to work around timestamp problems).
2196      if (defined($altalltargets{$target})) {
2197          print_make_line( FD, " " . $altalltargets{$target} );
2198      }
2199      print_make_line( FD,  " $target" );
2200  }
2201}
2202
2203
2204#
2205# Add to a target the designate operation in all subdirs (except for .)
2206#     &RecursiveOp( "target" [, optional array of directories, [checkMakefile] ] );
2207# If the array of directories is not included, (@extra_dirs,@subdirs)
2208# is used.  These are the arrays maintined by simplemake of the
2209# directories set by EXTRA_DIRS and SUB_DIRS.  The "optional array"
2210# is passed by name (i.e., the name of the array is passed, not the array
2211# itself).
2212#
2213# The third argument allows you to only execute the test if the
2214# Makefile is present.  This is used in the distclean targets and
2215# may be useful elsewhere.
2216#
2217# Special notes:
2218#    For a small number of directories, use a simpler (non loop) approach
2219#   
2220sub RecursiveOp {
2221    my $target = $_[0];
2222    my $subdirname = $_[1];
2223    my $checkForMakefile = $_[2];
2224    my $forThreashold = 3;
2225
2226    if (!defined($checkForMakefile) || $checkForMakefile eq "") {
2227        $checkForMakefile = 0;
2228    }
2229    # Get the optional arrays
2230    if (defined($subdirname) && $subdirname ne "") {
2231        @dirs = @$subdirname;
2232    }
2233    else {
2234        @dirs = (@extra_dirs, @subdirs);
2235    }
2236
2237    # Entries that are shell or autoconf variables have unknown count.
2238    #
2239    my $dirlistHasVariable = 0;
2240    foreach $dir (@dirs) {
2241        if ($dir =~ /@[^@]*@/) {
2242            $dirlistHasVariable = 1;
2243        }
2244        elsif ($dir =~ /\$/) {
2245            $dirlistHasVariable = 1;
2246        }
2247    }
2248
2249    print "n dirs = $#dirs\n" if $debug;
2250    if ($#dirs == 0 && $dirs[0] eq ".") { return; }
2251    if ($#dirs >= $forThreashold || $subdirs_has_autoconf ||
2252        $dirlistHasVariable) {
2253        print FD "\tfor dir in";
2254        foreach $dir (@dirs) {
2255            if ($dir ne ".") { print FD " $dir"; }
2256            if ($dir =~ /@[^@]*@/) {
2257                $subdirs_has_autoconf = 1;
2258            }       
2259        }
2260        # We may also want to check if subdirs is *only* autoconf;
2261        # if not, we don't need the -
2262        if ($subdirs_has_autoconf) {
2263            # Add a - incase there is a problem
2264          print FD " - ; do \\$newline";
2265          print FD "\t\tif [ \"\$\$dir\" = \"-\" ] ; then break ; fi ; \\$newline";
2266          if ($checkForMakefile) {
2267              print FD "\t\tif [ ! -s \$\$dir/Makefile ] ; then continue ; fi ;\\$newline";
2268          }
2269          print FD "\t\t(cd \$\$dir && \${MAKE} $target ; ) ; done$newline";
2270        }       
2271        else {
2272          print FD " ; do \\$newline";
2273          if ($checkForMakefile) {
2274              print FD "\t\tif [ ! -s \$\$dir/Makefile ] ; then continue ; fi ;\\$newline";
2275          }
2276          print FD "\t\t(cd \$\$dir && \${MAKE} $target ; ) ; " .
2277            "done$newline";
2278        }
2279    }
2280    elsif ($#dirs >= 0) {
2281        foreach $dir (@dirs) {
2282            # Skip . and any empty names
2283            if ($dir ne "." && $dir =~ /\S/) {
2284                if ($checkForMakefile) {
2285                    print FD "\tif [ -s $dir/Makefile ] ; then (cd $dir && \$(MAKE) $target ) ; fi$newline";
2286                }
2287                else {
2288                    print FD "\t(cd $dir && \$(MAKE) $target )$newline";
2289                }
2290            }
2291        }
2292    }
2293}
2294
2295# A version of RecuriveOps for optional directories; this is careful
2296# to check for existence of both the directory and the Makefile
2297# RecursiveOpForOptionalDirs( dirs, target, checkmake )
2298sub RecursiveOpForOptionalDirs {
2299    my $subdirs = $_[0];
2300    my $target = $_[1];
2301    my $checkForMakefile = $_[2];
2302
2303    my $forThreshold = 3;
2304
2305    if ($subdirs ne "") {
2306        # Count the number of directories
2307        my @sdirs = split(/\s+/,$subdirs);
2308        if ($#sdirs >= $forThreshold) {
2309            print FD "\t-\@for dir in $subdirs ; do \\$newline";
2310            print FD "\t    if [ -s \$\$dir/Makefile ] ; then \\$newline";
2311            print FD "\t      (cd \$\$dir && \${MAKE} $target ;) ; fi ; \\$newline";
2312            print FD "\tdone$newline";
2313        }
2314        else {
2315            foreach my $dir (@sdirs) {
2316                if ($dir ne "." && $dir =~ /\S/) {
2317                    if ($checkForMakefile) {
2318                        print FD "\tif [ -s $dir/Makefile ] ; then (cd $dir && \$(MAKE) $target ) ; fi$newline";
2319                    }
2320                    else {
2321                        print FD "\t(cd $dir && \$(MAKE) $target )$newline";
2322                    }
2323                }
2324            }
2325        }
2326    }
2327}
2328
2329#
2330# Return the directory in which the named library should be in
2331sub GetLibLoc {
2332    my $libname = $_[0];
2333   
2334    my $libloc = "";
2335    if (defined($libdir{$libname})) {
2336        $libloc = $libdir{$libname};
2337        my $rootdir;
2338        if (!defined($rootdirpath)) {
2339            $rootdir = "."
2340            }
2341        else {
2342            $rootdir = $rootdirpath;
2343            $rootdir =~ s/\r?\n?$//; # strip off any newlines
2344        }
2345        $libloc =~ s/ROOTDIR/$rootdir/;
2346        # Remove duplicated //
2347        $libloc =~ s/\/\//\//;
2348    }
2349
2350    return $libloc;
2351}
2352
2353
2354#
2355# Look for autoconf directory variables that are used
2356sub LookForAutoconfDirs {
2357    $line = $_[0];
2358    print "Looking at $line\n" if $debug;
2359    # Look for \$\{\w*\} and \$\(\w*\)
2360    while ($line =~ /^[^\$]*\$(.*)/) {
2361        $line = $1;
2362        if ($line =~ /^\$\w+(.*)/) {
2363            # This is a shell variable; skip it
2364            $line = $1;
2365        }
2366        elsif ($line =~ /^[\{\(](\w+)[\}\)](.*)/) {
2367            $varname = $1;
2368            $line    = $2;
2369            print "Found $varname in line\n" if $debug;
2370            # Look for varname in the known names; add to dirs_seen
2371            if (defined($dirdefs{$varname})) {
2372                print "Adding $varname to dirs_seen\n" if $debug;
2373                $dirs_seen{$varname} = $varname;
2374            }
2375        }
2376        else {
2377            last;
2378        }
2379    }
2380}
2381
2382#
2383# Look for make variables that are used
2384sub LookForVariables {
2385    $line = $_[0];
2386    print "Looking at $line\n" if $debug;
2387    # Look for \$\{\w*\} and \$\(\w*\)
2388    while ($line =~ /^[^\$]*\$(.*)/) {
2389        $line = $1;
2390        if ($line =~ /^\$\w+(.*)/) {
2391            # This is a shell variable; skip it
2392            $line = $1;
2393        }
2394        elsif ($line =~ /^[\{\(](\w+)[\}\)](.*)/) {
2395            $varname = $1;
2396            $line    = $2;
2397            print "Found $varname in line\n" if $debug;
2398            $vars_seen{$varname} = 1;
2399        }
2400        else {
2401            last;
2402        }
2403    }
2404}
2405
2406sub LookForSuffixes {
2407    $line = $_[0];
2408    while ($line =~ /^[^\.]*\.(\w*)\s*(.*)$/) {
2409        $suffix = $1;
2410        $line   = $2;
2411        # For now, only check for suffixes that lead to .o files.
2412        # Later we can check the keys of extdef to see if they
2413        # match /$ext:.*/
2414        if (defined($extdef{"$suffix:o"})) { 
2415            $ext_seen{$suffix} = 1;
2416        }
2417    }
2418}
2419
2420#
2421# ===========================================================================
2422# The "all" target.
2423#
2424# Output the target list.  If there are extra_programs or
2425# extra_libs, note that.
2426# FIXME: there needs to be way to specify other local targets
2427# beyond the implicitly determined ones.  This needs to allow
2428# for both pre and post implicit target values
2429#
2430sub TargetAll {
2431    print_make_line( FD,  "all-redirect:" );
2432    if ($#subdirs > -1) {
2433        # If there are subdirectories, we must descend into them.
2434        # This branch does that, after adding the dependencies for the
2435        # target (if any).
2436        &TargetPreamble( "all" );
2437        print_make_endline( FD );
2438        # Now add the steps for the subdirectories
2439        $has_dot = 0;
2440        foreach $dir (@extra_dirs, @subdirs) {
2441            if ($dir eq ".") {
2442                if (scalar(@alltargets) ||
2443                    defined($usertargets{"all-local"})) {
2444                    $has_dot = 1;
2445                    print FD "\t\${MAKE} all-local$newline";
2446                    #----------------  Kumud check ----------------------------
2447                    #my $kumud_libloc= &GetLibLoc ( '${MPILIBNAME}');
2448                    #print FD "\tI am alive and the library location is $kumud_libloc";
2449                }
2450            }
2451            elsif ($dir =~ /@([^@]*)@/) {
2452                # May be a replaced variable
2453                print FD "\t${quietmake}for dir in $dir - ; do \\$newline";
2454                print FD "\t\tif [ \"\$\$dir\" = \"-\" ] ; then break ; fi ; \\$newline";
2455                print FD "\t\tif ( cd \$\$dir && \${MAKE} all ) ; then : ; else exit 1; fi \\$newline";
2456                print FD "\tdone$newline";
2457            }
2458            else {
2459                print FD "\t${quietmake}(cd $dir && \${MAKE} all )$newline";
2460            }
2461        }
2462        # If subdirs has no dot but there are local targets, add an
2463        # implicit dot to the end.
2464        if (!$has_dot && $#alltargets > -1) {
2465            $has_dot = 1;
2466            print FD "\t\${MAKE} all-local$newline";
2467        }
2468
2469                   
2470        if ($has_dot && !defined($usertargets{"all-local"})) {
2471            # Add the default definition of all-local for the case where
2472            # a . is in the SUBDIR line
2473            print_make_line( FD, "all-local:" );
2474            &ListTargets;
2475            # ListTargets does *not* end the line
2476            print_make_endline( FD );
2477            # Add generation of shared libraries if necessary
2478            &TargetAllCommandsForSharedLibs;
2479            &TargetAllCommandsForDLLLibs;
2480        }
2481       
2482        #  Create the final shared library (typically .so) from the .la file
2483        if (defined($optinstall_files{'SHLIB'})) {
2484            # Conditionally create the shared libraries.
2485            print FD "\t\@if [ \"\@ENABLE_SHLIB\@\" != \"none\" ] ; then \\\n";
2486            foreach $libspec (split(/\s+/,$optinstall_files{'SHLIB'})) {
2487                if (defined($extra_libs{$libspec})) { next; }
2488                # Be careful of library names that are related to
2489                # the profile library (those libraries are built
2490                # as part of the "master" library name build)
2491                my $baselibname = $libspec;
2492                $baselibname =~ s/^.*\///g;
2493                $baselibname =~ s/^lib//;
2494                $baselibname =~ s/\..*//;
2495                # We need to be careful about the optional files, since
2496                # the prerequisites may not exist
2497                # We could either test on the conditions under which
2498                # the optional files should exist (this is probably the
2499                # best option), or we can coordinate with the
2500                # target that we invoke for each case.  We'll do the
2501                # latter for now and consider adding an optional predicate
2502                # that can be supplied for each OPTINSTALL item.
2503                if (!defined($profile_libraries_basename{$baselibname})) {
2504                    print "Building sharedlib library $baselibname (from $libspec) as part of all-redirect\n" if $gDebugWhy;
2505                    # Get the condition
2506                    my $prereq = $libspec;
2507                    $prereq =~ s/\.\@SHLIB_EXT\@/.la/;
2508                    print FD "\t    if [ -s $prereq ] ; then \\\n";
2509                    print FD "\t        echo \"make $libspec\" ;\\\n";
2510                    print FD "\t        \${MAKE} $libspec ; \\\n";
2511                    print FD "\t    fi ; \\\n";
2512                }
2513            }
2514            print FD "\tfi\n";
2515        }
2516        if (defined($optinstall_files{'DLLLIB'})) {
2517            #print STDOUT "in optinstall_files dlllib\n";
2518            # Conditionally create the dynamically loadable shared libraries.
2519            print FD "\t\@if [ \"\@BUILD_DLLS\@\" = \"yes\" ] ; then \\\n";
2520            foreach $libspec (split(/\s+/,$optinstall_files{'DLLLIB'})) {
2521                # Be careful of library names that are related to
2522                # the profile library (those libraries are built
2523                # as part of the "master" library name build)
2524                my $baselibname = $libspec;
2525                $baselibname =~ s/^.*\///g;
2526                $baselibname =~ s/^lib//;
2527                $baselibname =~ s/\..*//;
2528                # We need to be careful about the optional files, since
2529                # the prerequisites may not exist
2530                # We could either test on the conditions under which
2531                # the optional files should exist (this is probably the
2532                # best option), or we can coordinate with the
2533                # target that we invoke for each case.  We'll do the
2534                # latter for now and consider adding an optional predicate
2535                # that can be supplied for each OPTINSTALL item.
2536                if (!defined($profile_libraries_basename{$baselibname})) {
2537                    print "Building sharedlib library $baselibname (from $libspec) as part of all-redirect\n" if $gDebugWhy;
2538                    # Get the condition
2539                    my $prereq = $libspec;
2540                    $prereq =~ s/\.\@SHLIB_EXT\@/.la/;
2541                    print FD "\t    if [ -s $prereq ] ; then \\\n";
2542                    print FD "\t        echo \"make $libspec\" ;\\\n";
2543                    print FD "\t        \${MAKE} $libspec ; \\\n";
2544                    print FD "\t    fi ; \\\n";
2545                }
2546            }
2547            print FD "\tfi\n";
2548        }
2549        &TargetPostamble( "all" );
2550    }
2551    else {
2552        # This is a leaf, so we can list the dependencies. 
2553        &TargetPreamble( "all" );
2554        if (defined($usertargets{"all-local"})) {
2555            # Add all-local as a target
2556            print_make_line( FD, " all-local " );
2557        }
2558        &ListTargets;
2559        if ($found_profilelib) {
2560            print_make_endline( FD );
2561            # Add a conditional step
2562            print FD "\t\@if [ -n \"\@NO_WEAK_SYM\@\" ] ; then \\\n";
2563            foreach my $lib (keys(%profile_libraries)) {
2564                my $proflib = $profile_libraries{$lib};
2565                my $libstamp = ".libstamp" . $libnum{$proflib};
2566#               my $libloc = &GetLibLoc( $lib );
2567#               my $fullname = "${libloc}lib$proflib.a";
2568#               print FD "\t    \${MAKE} $fullname ; \\\n";
2569                print FD "\t    \${MAKE} $libstamp || exit 1; \\\n";
2570            }
2571            print FD "\tfi";
2572        }
2573        print_make_endline( FD );
2574        &TargetAllCommandsForSharedLibs;
2575        &TargetAllCommandsForDLLLibs;
2576        &TargetPostamble( "all" );
2577    }
2578    print_make_endline( FD );
2579} # TargetAll
2580# ---------------------------------------------------------------------------
2581# Routines to provide standard extensions through -preamble, -postamble,
2582# and -local
2583# -preamble allows you to *ADD* a step to be performed before the other
2584# dependencies, -postamble adds a step after the target is formed
2585#
2586# To ensure uniform handling of -preamble, the routine TargetInit( name )
2587# outputs the target and the preamble.
2588sub TargetInit {
2589    my $name = $_[0];
2590    print FD "$name: ";
2591    &TargetPreamble( $name );
2592}
2593sub TargetPreamble {
2594    my $name = $_[0];
2595    $name .= "-preamble";
2596    if (defined($usertargets{$name})) {
2597        print FD " $name";
2598    }
2599}
2600sub TargetPostamble {
2601    my $name = $_[0];
2602    $name .= "-postamble";
2603    if (defined($usertargets{$name})) {
2604        print FD "\t\${MAKE} $name$newline";
2605    }
2606}
2607# --------------------------------------------------------------------------
2608# Helper routines for the implementation of the "all" target.  Two
2609# complications here are that the handling of leaf Makefile.sm (those with
2610# no SUBDIRS) and non-leaf Makefile.sm are different for the "all" target.
2611# (a better long-term solution may be to redesign the handling of the all
2612# target).
2613# --------------------------------------------------------------------------
2614
2615# Add the commands to build shared libraries if any are defined
2616# (either explicitly or because we generate shared libraries for all
2617# libraries).
2618sub TargetAllCommandsForSharedLibs {
2619    if ($do_sharedlibs && $#allshlibtargets >= 0) {
2620        # Add a conditional step
2621        print FD "\t\@if [ \"\@ENABLE_SHLIB\@\" != \"none\" ] ; then \\\n";
2622        foreach $shlib (@allshlibtargets) {
2623            if (defined($extra_libs{$shlib})) { next; }
2624            # Get the library stamp name from the lib name
2625            my $libbase = $shlib;
2626            if ($shlib =~ /.*\/lib([^\/]*)/) {
2627                $libbase = $1;
2628            }
2629            my $libstamp = $shlib;
2630            if (defined($libnum{$libbase})) {
2631                $libstamp = ".libstamp" . $libnum{$libbase};
2632            }
2633            print FD "\t    \${MAKE} $libstamp || exit 1; \\\n";
2634        }
2635        if ($found_profilelib) {
2636            print FD "\t    if [ -n \"\@NO_WEAK_SYM\@\" ] ; then \\\n";
2637            foreach my $lib (keys(%profile_libraries)) {
2638                my $proflib = $profile_libraries{$lib};
2639                my $libloc = &GetLibLoc( $lib );
2640                my $fullname = "${libloc}lib$proflib.la";
2641                my $libstamp = ".libstamp" . $libnum{$proflib.".la"};
2642                print FD "\t        \${MAKE} $libstamp || exit 1; \\\n";
2643#               print FD "\t        \${MAKE} $fullname ; \\\n";
2644            }
2645            print FD "\t    fi ; \\\n";
2646        }
2647        print FD "\tfi\n";
2648    }
2649}
2650
2651sub TargetAllCommandsForDLLLibs {
2652    if ($do_sharedlibs && $#alldlllibtargets >= 0) {
2653        # Add a conditional step
2654        print FD "\t\@if [ \"\@BUILD_DLLS\@\" = \"yes\" ] ; then \\\n";
2655        foreach $shlib (@alldlllibtargets) {
2656            # Get the library stamp name from the lib name
2657            my $libbase = $shlib;
2658            if ($shlib =~ /.*\/lib([^\/]*)/) {
2659                $libbase = $1;
2660            }
2661            my $libstamp = $shlib;
2662            if (defined($libnum{$libbase})) {
2663                $libstamp = ".libstamp" . $libnum{$libbase};
2664            }
2665            print FD "\t    \${MAKE} $libstamp || exit 1; \\\n";
2666        }
2667        print FD "\tfi\n";
2668    }
2669}
2670
2671# --------------------------------------------------------------------------
2672#
2673# ===========================================================================
2674# The "clean" target
2675#
2676# Produces clean:, distclean:, and maintainerclean:
2677# If clean-local, distclean-local, or maintainer-clean-local were defined,
2678# they are included in the dependency lists
2679#
2680# The default for quietLine makes the clean lines quiet (no echo of the
2681# command).
2682#
2683# Notes:
2684# The clean target is relatively easy, because it involves only files
2685# created *after* the configure step. 
2686# The distclean and maintainer-clean steps are more complicated, because
2687# there is some interaction with the generated steps.  In particular,
2688# distclean must remove Makefile, but once the makefiles are gone,
2689# you can't execute another make step.  If you run maintainer-clean first,
2690# the the dependencies on Makefile:Makefile.in:Makefile.sm will force
2691# a reconstruction of some of the files that were just removed.
2692# Thus, we need to separate from the distclean and maintainer-clean targets
2693# the steps that remove the makefiles.  Thus, we have the
2694# following intermediate targets:
2695#    remove-makefile
2696#    remove-genmakefiles
2697# To simplify the construction of the targets, we use internal targets.
2698# Thus, distclean becomes:
2699# distclean: clean distclean-local distclean-xxx remove-makefile
2700#
2701# and maintainer-clean becomes
2702# maintainer-clean: clean maintainer-clean-local distclean-local \
2703#     distclean-xxx maintainer-clean-xxx remove-genmakefiles
2704#
2705#
2706#
2707sub TargetClean {
2708    my $otherMakefiles = "";
2709
2710    $programnames = join( ' ', keys(%programs));
2711    &TargetInit( "clean" );
2712    if (defined($usertargets{"clean-local"})) { print FD " clean-local"; }
2713    print FD "$newline";
2714    print FD "\t-${quietLine}rm -f *.o \${srcdir}/*.o $programnames$newline";
2715    &LibraryTimestampClean;
2716    # Add Windows names of executables
2717    if ($programnames ne "") {
2718        print FD "\t-${quietLine}rm -f";
2719        foreach $name (split(/\s+/,$programnames)) {
2720            print FD " $name.exe";
2721        }
2722        print FD "$newline";
2723        # Remove core files, including core files with process numbers
2724        # (produced by some versions of Linux)
2725        print FD "\t-${quietLine}rm -f core core.[0-9]*$newline";
2726    }
2727
2728    # Output this in all cases to clear any old files. 
2729    # (Don't make this conditional because it is important to remove
2730    # these files even if we're not building for enabling shared libraries
2731    # this time around.
2732    print FD "\t-${quietLine}rm -f *.lo \${srcdir}/*.lo$newline";
2733
2734    # Clean coverage analysis files
2735    &GcovClean;
2736
2737    # We can put a hook here to add additional clean targets.  For
2738    # the moment, we'll add an MPICH-2 specific target for this
2739    if ($programnames ne "") {
2740        # Testing of parallel program may produce log files.  This will remove
2741        # any existing irlog files
2742        print FD "\t-${quietLine}rm -f *.irlog*$newline";
2743    }
2744
2745    if ($maint_perf_targets) {
2746        # In this case, we want to remove any generated asm files,
2747        # to prevent them from being used in preference to the
2748        # original (e.g., C) source file
2749        my $input_sources;
2750        if ($regular_sources =~ /\S/) {
2751            $input_sources = $regular_sources;
2752        }
2753        elsif (defined($makevars{'SOURCES'})) {
2754            $input_sources = $makevars{'SOURCES'};
2755        }
2756        if (defined($input_sources)) {
2757            my $clean_files = "";
2758            foreach my $file (split(/\s+/,$input_sources)) {
2759                if ($file =~ /(.*)\.([^\.]+)/) {
2760                    my $base = $1;
2761                    my $ext  = $2;
2762                    if ($ext ne "s") {
2763                        $clean_files .= " $base.s";
2764                    }
2765                }
2766            }
2767            if ($clean_files ne "") {
2768                print FD "\t-${quietLine}rm -f $clean_files$newline";
2769            }
2770        }
2771    }
2772
2773    # For any extensions, handle the clean actions
2774    &SMInvokeAction( "OutputClean", FD );
2775
2776    # Finally, execute make clean in any subdirs
2777    &RecursiveOp( "clean" );
2778    &TargetPostamble( "clean" );
2779
2780    # --------------------------------------------
2781    # distclean target
2782    &TargetInit( "distclean" );
2783    print FD " clean";
2784    if (defined($usertargets{"distclean-local"})) {
2785        print FD " distclean-local";
2786    }
2787    print FD " distclean-xxx remove-makefile";
2788    &TargetPostamble( "distclean" );
2789
2790    print FD "$newline";
2791   
2792    print FD "distclean-xxx:$newline";
2793    # RecursiveOp uses extra_dirs,subdirs; the "1" forces it to check
2794    # for the existence of the Makefile
2795    &RecursiveOp( "distclean", "", 1 );
2796
2797    # Add clean of local libraries
2798    foreach $lib (keys(%extra_libs)) {
2799        print FD "\t-${quietLine}rm -f $lib$newline";
2800    }
2801
2802    # Remove any local files last (in case this file is one of them)
2803    $rmfile = "";
2804    if (!$curdir) { $curdir = ""; }
2805    $lcurdir = $curdir;
2806    $lcurdir =~ s/\/$//;
2807    if (defined($autoconf_files_by_dir{$lcurdir})) {
2808        $rmfile = $autoconf_files_by_dir{$lcurdir};
2809        # Remove the Makefile.in from this list because it will
2810        # be handled separately
2811        if ($rmfile =~ /Makefile.in/) {
2812            $otherMakefiles .= "Makefile.in ";
2813            $rmfile =~ s/Makefile.in\s*//;
2814        }
2815        print FD "\t-${quietLine}rm -f $rmfile$newline";
2816        # Remove the configure cache that autoconf 2.57+ adds
2817        print FD "\t-${quietLine}rm -rf autom4te*.cache$newline";
2818    }
2819    if ($configure_has_config_headers ne "no") {
2820        # Add the AC_CONFIG_HEADER file, if any.
2821        print FD "\t-${quietLine}rm -f $configure_has_config_headers$newline";
2822    }
2823    # Handle files that aren't part of subdirs
2824    if (defined($autoconf_files_by_dir_orig{$lcurdir})) {
2825        my $otherfiles = $autoconf_files_by_dir_orig{$lcurdir};
2826        foreach $dir (@subdirs) {
2827            $otherfiles =~ s/ $dir\/\S*//g;
2828        }
2829        $otherfiles =~ s/^\s*//;
2830        # Is there anything left?
2831        if ($otherfiles =~ /\S+/) {
2832            print FD "\t-${quietLine}rm -f $otherfiles$newline";
2833        }
2834    }
2835   
2836    # For any extensions, handle the clean actions
2837    &SMInvokeAction( "OutputDistClean", FD );
2838
2839    # Another difficulty are the optional directories.  For example,
2840    # a SUBDIRS = foo \@bar\@
2841    # line (without the \, included since the simplemake.in file is
2842    # itself processed with autoconf)
2843    &RecursiveOpForOptionalDirs( $subdir_optionals, "distclean", 1 );
2844
2845    &DistCleanDependencies;
2846
2847    if ($distcleanfiles ne "") {
2848        print FD "\t-${quietLine}rm -f $distcleanfiles$newline";
2849    }
2850    print FD "\t-${quietLine}rm -f TAGS$newline";
2851
2852    # --------------------------
2853    if ($maint_targets) {
2854        # Should maintainer-clean also perform a distclean?
2855        # No, because distclean needs to remove the Makefiles, and
2856        # this target needs to remove entries that have dependencies
2857        # (e.g., the Makefile : Makefile.in : Makefile.sm dependency)
2858        &TargetInit( "maintainer-clean" );
2859        if (defined($usertargets{"maintainer-clean-local"})) {
2860            print FD " maintainer-clean-local";
2861        }
2862        print FD " distclean-xxx remove-genmakefiles";
2863        &TargetPostamble( "maintainer-clean" );
2864        print FD "$newline";
2865
2866        # For any extensions, handle the clean actions
2867        &SMInvokeAction( "OutputMaintainerClean", FD );
2868
2869        &RecursiveOp( "maintainer-clean" );
2870        # Remove the file that simplemake creates
2871        $otherMakefiles .= " $output_name";
2872        #print FD "\t-rm -f $output_name$newline";
2873        # eventually, this should also invoke distclean, but it must
2874        # do that only once (not recursively) and only after all other
2875        # uses of the Makefile, since distclean removes the Makefile
2876        # Directories containing autoconf should include an rm of configure
2877
2878        # This should also remove any files that will be created with
2879        # autoheader.  We'll need to check for files that are created
2880        # by autoheader, not just rely on the AC_CONFIG_HEADER command,
2881        # since some headers may be created by hand.  We'll ignore
2882        # this for now, since we uniformly use autoheader (and
2883        # simplemake runs autoheader if it finds AC_CONFIG_HEADER)
2884        if ($configure_has_config_headers ne "no") {
2885            print FD "\t-rm -f ";
2886            foreach $file (split(/\s+/,$configure_has_config_headers)) {
2887                print FD "$file.in ";
2888            }
2889            print FD "$newline";
2890        }
2891        # We also need to remove configure and autom4ate/ if present
2892    }
2893    &TargetRmMakefiles( $otherMakefiles );
2894
2895}
2896
2897#
2898# Generate the makefile removal targets
2899# TargetRmMakfiles( otherMakefiles )
2900#
2901# These are *NOT* recursive targets because they are local to the
2902# particular directory.
2903sub TargetRmMakefiles {
2904    my $otherMakefiles = $_[0];
2905    print FD "remove-makefile:$newline";
2906    print FD "\trm -f Makefile$newline";
2907    print FD "remove-genmakefiles:$newline";
2908    print FD "\trm -f $otherMakefiles Makefile$newline";
2909}
2910#
2911# Generate the core part of the distclean target
2912sub TargetDistclean {
2913}
2914#
2915# ===========================================================================
2916# Libraries
2917#
2918# We want to generate either a generic "update library from object files"
2919# or "update library member" for makes that support that feature (this
2920# is normally used only for the maintenance target).
2921
2922#
2923# LibraryBuild ( libname, libloc, libfiles, lib extension, member extension )
2924# Not quite right.  Need to include the update command as well as ways
2925# to handle the "special extensions", both for the library (e.g., .a vs. .la)
2926# and members (e.g., .o vs .lo)
2927sub LibraryBuild {
2928    my $libname = $_[0];
2929    my $libloc  = $_[1];
2930    my $sourcefiles = $_[2];
2931    my $libext = $_[3];
2932    my $memext = $_[4];
2933    my @objects=();
2934    if (!$dolib_member) {
2935        &print_make_line( FD, "${libloc}lib$libname.$libext: " );
2936    }
2937    # Handle any variables in the lib line
2938    if (!defined($sourcefiles)) {
2939        print STDERR "Warning: no source files in library $libname in LibraryBuild\n" ; }
2940    $sourcefiles = &ExpandMakeVars($sourcefiles);
2941    foreach $sourcefile (split(/\s+/,$sourcefiles)) {
2942        $ext = "";
2943        $obj = "";
2944        if ($sourcefile =~ /(.*)\.([^\.]*)/) {
2945            $obj = "$1.$memext";
2946            $ext = $2;
2947        }
2948        else {
2949            # Don't warn about autoconf variables (see below)
2950            if (! ($sourcefile =~ /^\@/) ) {
2951                print STDERR "Sourcefile is $sourcefile\n";
2952            }
2953        }
2954        # The special case for an extension of h handles the case where the
2955        # .h files are derived, and hence have special rules for creating
2956        # them.  We also ignore autoconf variables (eventually, we might
2957        # want to insist that valid values for that autoconf variable be
2958        # available).
2959        if ( (!defined($extrules{"$ext:o"}) && ($ext ne "h") &&
2960              ! ($sourcefile =~ /^\@/))) {
2961            # Sometimes we use our own rules for building objects.
2962            # We allow the user to specify the object files rather than
2963            # the source files
2964            if ($ext ne "o") {
2965                print STDERR "Unknown extension $ext for $sourcefile for library $libname\n";
2966            }
2967        }
2968       
2969        if ($dolib_member) {
2970            &print_make_line( FD, "${libloc}lib$libname.$libext($obj): $obj" );
2971            &print_make_endline( FD );
2972            # COMMAND PRINTING
2973            # ------------------------ Kumud_Parallel_Fix ----------------------
2974            # &PrintVerboseOptionCommand( "\${AR} cr ${libloc}lib$libname.$libext \$?", "  AR" );
2975           
2976            if ($obj =~/\s*(\S+)\s*/){
2977                &PrintVerboseOptionCommand( "rm -rf lib$libname.$libext.manifest", "  rm" );
2978                &PrintVerboseOptionCommand( "echo \"\${abs_builddir}/$obj\" >> lib$libname.$libext.manifest", "  echo" );               
2979                print FD "\ttouch \${top_builddir}/lib/.lib$libname.$libext.timestamp$newline";
2980            }
2981           
2982        }
2983        else {
2984            if ($ext ne "h") {
2985                &print_make_line( FD, "$obj " );
2986                if ($obj =~/\s*(\S+)\s*/){
2987                    $objects[ $#objects+1 ]= $1;
2988                }
2989            }
2990        }
2991    }
2992    &SMInvokeAction( "OutputLibDependencies", $lib, $libloc, $memext );
2993    if (!$dolib_member) {
2994        &print_make_endline( FD );
2995        # ------------------------ Kumud_Parallel_Fix ----------------------
2996        # &PrintVerboseOptionCommand( "\${AR} cr ${libloc}lib$libname.$libext \$?",
2997        &PrintVerboseOptionCommand( "rm -rf lib$libname.$libext.manifest", "  rm" );
2998        foreach $object (@objects){
2999            &PrintVerboseOptionCommand( "echo \"\${abs_builddir}/$object\" >> lib$libname.$libext.manifest", "  echo"  );
3000        }
3001        print FD "\ttouch \${top_builddir}/lib/.lib$libname.$libext.timestamp$newline";
3002                                           
3003    }
3004}
3005
3006sub TargetLibraries {
3007    foreach $lib (keys(%libraries)) {
3008        my $libloc = &GetLibLoc( $lib );
3009        if (!defined($libraries{$lib})) { next; }
3010
3011        my $sourcefiles = &ExpandMakeVars($libraries{$lib});
3012
3013        &LibraryTimestampPrefix( $lib, $libloc );
3014        &LibraryBuild( $lib, $libloc, $sourcefiles, "a", "o" );
3015        # Add any additional actions for this library.
3016        &SMInvokeAction( "OutputLib", $lib, $libloc );
3017       
3018        # ------------------------ Kumud_Parallel_Fix ----------------------
3019        # if ($ranliblib) {
3020        #    # COMMAND PRINTING
3021        #    &PrintVerboseOptionCommand( "\${RANLIB} ${libloc}lib$lib.a", "-",
3022        #                               "  RANLIB          lib$lib.a" );
3023        #}
3024 
3025        # To handle timestamp problems with recursive makes, add a delay
3026        &LibraryTimestampFix( $lib, $libloc )
3027       
3028    }
3029}
3030
3031#
3032# Fix for problems with timestamps.  If the file is not local (not
3033# obviously in the current directory), then apply one of the fixes
3034#
3035# LibraryTimestampTarget - Save additional target name in altalltargets hash
3036#                          (used in ListTargets)
3037# LibraryTimestampPrefix - Additional target for the library
3038# LibraryTimestampFix - Fix *after* all other operations
3039# LibraryTimestampClean - Add clean commands for library timestamps
3040sub LibraryTimestampTarget {
3041    my ($fulllibname,$libstamp) = @_;
3042    my $expandedFullName = &ExpandMakeVars( $fulllibname );
3043    if ($expandedFullName =~ /^\.\./ && !$fixup_for_timestamps) {
3044        $altalltargets{$fulllibname} = $libstamp;
3045    }
3046}
3047sub LibraryTimestampPrefix {
3048    my ($lib, $libloc) = @_;
3049
3050    my $expandedlibloc = &ExpandMakeVars( $libloc );
3051
3052    if ($expandedlibloc =~ /^\.\./) {
3053        if (!$fixup_for_timestamps) {
3054            my $num = "";
3055            if (defined($libnum{$lib})) {
3056                $num = $libnum{$lib};
3057            }
3058            &print_make_line( FD, ".libstamp$num " );
3059        }
3060    }
3061}
3062sub LibraryTimestampFix {
3063    my ($lib,$libloc) = @_;
3064    my $expandedlibloc = &ExpandMakeVars( $libloc );
3065    if ($expandedlibloc =~ /^\.\./) {
3066        if ($fixup_for_timestamps) {
3067            my $SleepText = $Sleep;
3068            my $fulllibname = $libloc . "lib$lib.a";
3069            $SleepText =~ s/LIB/$fulllibname/;
3070            print FD "\t$SleepText$newline";
3071        } else {
3072            if (defined($libnum{$lib})) {
3073                my $num = "";
3074                $num = $libnum{$lib};
3075                print FD "\tdate > .libstamp$num\n";
3076            }
3077        }
3078   
3079    }
3080
3081
3082sub LibraryTimestampClean {
3083    if ($libcount > 0) {
3084        print FD "\t-${quietLine}rm -f ";
3085        for( my $i=0; $i<$libcount; $i++) {
3086            print FD ".libstamp$i ";
3087        }
3088        print FD "\n";
3089    }
3090}
3091# --------------------------------------------------------------------------
3092
3093# This code is similar to TargetLibraries.
3094sub TargetProfileLibraries {
3095    $found_source_files = 0;
3096    foreach $lib (keys(%profile_libraries)) {
3097        $proflib_name = $profile_libraries{$lib};
3098        $libloc = &GetLibLoc( $lib );
3099        # Take the sources from the base library unless
3100        # they were explicitly listed
3101        if (defined($profile_library_sources{$lib})) {
3102            $sourcefiles = $profile_library_sources{$lib};
3103        }
3104        else {
3105            $sourcefiles = $libraries{$lib};
3106        }
3107        $sourcefiles = &ExpandMakeVars( $sourcefiles );
3108        # FIXME: Use LibraryBuild here
3109        # Use the library stamp
3110        my $libstamp = ".libstamp" . $libnum{$proflib_name};
3111        print FD "$libstamp: ";
3112        #&print_make_line( FD, "${libloc}lib$proflib_name.a: " );
3113        foreach $sourcefile (split(/\s+/,$sourcefiles)) {
3114            $found_source_files = 1;
3115            $obj = $sourcefile;
3116            # Convert to object file
3117            $ext = $sourcefile;
3118            $ext =~ s/^.*\.//g;
3119            if ($ext eq "f") {
3120                # Ignore Fortran source files (setbotf.f in mpich2)
3121                next;
3122            }
3123            elsif (defined($extrules{"$ext:o"})) {
3124                $obj =~ s/\.$ext/\.o/g;
3125                $obj = "_" . $obj;
3126            }
3127            else {
3128                # Be silent on .h files
3129                if ($ext ne "h") {
3130                    print STDERR "Unknown extension $ext for $sourcefile for profile library $proflib_name\n";
3131                }
3132            }
3133            &print_make_line( FD, "$obj " );
3134        }
3135        &print_make_endline( FD );
3136        if ($found_source_files) {
3137            # Add these files as objects to the archive
3138            # COMMAND PRINTING
3139            &PrintVerboseOptionCommand( "\${AR} cr ${libloc}lib$proflib_name.a \$?",
3140                                        "  AR" );
3141            if ($ranliblib) {
3142                # COMMAND PRINTING
3143                &PrintVerboseOptionCommand( "\${RANLIB} ${libloc}lib$proflib_name.a",
3144                                            "-", "  RANLIB          lib$proflib_name.a" );
3145            }
3146            # To handle timestamp problems with recursive makes,
3147            # add a delay
3148            &LibraryTimestampFix( $proflib_name, $libloc );
3149        }
3150
3151        if ($do_sharedlibs) {
3152            my $libstamp = ".libstamp" . $libnum{$proflib_name.".la"};
3153            print FD "$libstamp: ";
3154            #&print_make_line( FD, "${libloc}lib$proflib_name.la: " );
3155            foreach $sourcefile (split(/\s+/,$sourcefiles)) {
3156                $found_source_files = 1;
3157                $obj = $sourcefile;
3158                # Convert to object file
3159                $ext = $sourcefile;
3160                $ext =~ s/^.*\.//g;
3161                if ($ext eq "f") {
3162                    # Ignore Fortran source files (setbotf.f in mpich2)
3163                    next;
3164                }
3165                elsif (defined($extrules{"$ext:o"})) {
3166                    $obj =~ s/\.$ext/\.lo/g;
3167                    $obj = "_" . $obj;
3168                }
3169                else {
3170                    # Be silent on .h files
3171                    if ($ext ne "h") {
3172                        print STDERR "Unknown extension $ext for $sourcefile for profile library $proflib_name\n";
3173                    }
3174                }
3175                &print_make_line( FD, "$obj " );
3176            }
3177            &print_make_endline( FD );
3178            if ($found_source_files) {
3179                # Add these files as objects to the archive
3180                # COMMAND PRINTING
3181                &PrintVerboseOptionCommand( "\${AR} cr ${libloc}lib$proflib_name.la \$?",
3182                                            "  AR" );
3183                # To handle timestamp problems with recursive makes,
3184                # add a delay
3185                &LibraryTimestampFix( $proflib_name.".la", $libloc );
3186            }
3187        }
3188       
3189        # The new dependencies on the object files
3190        foreach $sourcefile (split(/\s+/,$sourcefiles)) {
3191            $found_source_files = 1;
3192            $obj = $sourcefile;
3193            # Convert to object file
3194            $ext = $sourcefile;
3195            $ext =~ s/^.*\.//g;
3196            if ($ext ne "c") {
3197                print STDERR "Unknown extension $ext for $sourcefile for profile library $proflib_name\n";
3198                next;
3199            }
3200            $obj =~ s/\.$ext/.o/;
3201            $obj = "_" . $obj;
3202            # Note that many makes won't replace $< in an implicit rule,
3203            # so we explicitly list the source file
3204            print FD "$obj: $sourcefile$newline";
3205            # COMMAND PRINTING
3206            &PrintVerboseOptionCommand( "\$(C_COMPILE) -c \@PROFILE_DEF_MPI\@ \$(srcdir)/$sourcefile -o $obj", "-", "  CC             -D<profiling> \${srcdir}/$sourcefile" );
3207            if ($do_sharedlibs) {
3208                $obj =~ s/\.o/.lo/;
3209                print FD "$obj: $sourcefile$newline";
3210                &PrintVerboseOptionCommand( "\$(C_COMPILE_SHL) -c \@PROFILE_DEF_MPI\@ \$(srcdir)/$sourcefile -o $obj", "-", " CC           -D<profiling> \$(srcdir)/$sourcefile" );
3211            }
3212        }
3213    } # foreach lib
3214}
3215#
3216# ===========================================================================
3217# The following is a cache of comments on using libtool, based on the
3218# targets created by automake. 
3219# Issues include
3220#   Handling the simultaneous generation of dependency information
3221#    (automake assumes a GNU environment, including gnumake and gcc, unless
3222#    you work really, really hard)
3223#   
3224# .c.lo: (target in the automake is %.lo: %.c)  is roughly
3225# @echo '$(LTCOMPILE) -c $<'
3226# @$(LTCOMPILE) -Wp,-MD,.deps/$(*F).pp -c $<
3227# @sed -e 's/^\([^:]*\)\.o[\t ]*;/\1.lo \1.o :/' \ <.deps/$(*F).pp > \
3228#   .deps/$(*F).P; \
3229# tr ' ' '\012' < .deps/$(*F).pp \
3230#  | sed -e 's/^\\$$//' -e '/^$$/ d' -e '/:$$/ d' -e 's/$$/ :/' \
3231#  >> .deps/$(*F).P
3232# @rm -f .deps/$(*F).pp
3233#
3234# Most of this is used to handle the dependency generation, including
3235# makint the files refer to .lo and .o instead of just .o.  Also note that
3236# LTCOMPILE generates BOTH .o and .lo files.
3237# (most of this is similar to the .c.o target generated by automake
3238#
3239# Another important step is the install step, which is roughly
3240# install-libLTLIBRARIES: $(lib_LTLIBRARIES)
3241#   @$(NORMAL_INSTALL)
3242#   $(mkinstalldirs) $(DESTDIR)$(libdir)
3243#   @list='$(lib_LTLIBRARIES)'; for p in $$list ; do \
3244#     if test -f $$p; then \
3245#        echo "$(LIBTOOL) --mode=install $(INSTALL) $$p $(DESTDIR)$(libdir)/$$p" ;\
3246#        $(LIBTOOL) --mode=install $(INSTALL) $$p $(DESTDIR)$(libdir)/$$p ;\
3247#     else : ; fi ; done
3248# uninstall-libLTLIBRARIES:
3249#   @$(NORMAL_UNINSTALL)
3250#   @list='$(lib_LTLIBRARIES)'; for p in $$list ; do \
3251#        $(LIBTOOL) --mode=uninstall $(INSTALL) rm -f $(DESTDIR)$(libdir)/$$p ;\
3252#     done
3253#
3254# clean target for libtool adds .libs and _libs (may be directories)
3255#
3256# NORMAL_INSTALL and UNINSTALL seem to be hooks; the base definition is :
3257#
3258# DESTDIR is a newer automake thing to make it easier to retarget an install
3259# into a test directory.
3260#
3261# ---------------------------------------------------------------------------
3262# This routine creates the library of shared objects.  There is a separate
3263# step that builds the shared library (which is really a kind of partially
3264# linked executable).
3265# Pass in the name (by reference) of the list of libraries.  This allows
3266# us to use this routine for both the general list of libraries (for -shared,
3267# which makes both static and dynamic libraries) and for the list of libraries
3268# that are only needed as shared libraries (e.g., Totalview and Java/SLOG
3269# interface libraries).
3270sub TargetSharedLibraries {
3271    # This provides a *reference* to the hash that is passed into the routine
3272    # See the perlsub and perlref manpages for this, and the %$libraries and
3273    # $$libraries used below.
3274    my $libraries = $_[0];
3275
3276    foreach $lib (keys(%$libraries)) {
3277        # Skip the libraries that have no shared counterpart
3278        if (defined($libNotShared{$lib})) {
3279            #print "Skipping $lib\n";
3280            next;
3281        }
3282        $libloc = &GetLibLoc( $lib );
3283        $sourcefiles = &ExpandMakeVars($$libraries{$lib});
3284        &LibraryTimestampPrefix( $lib.".la", $libloc );
3285        &LibraryBuild( $lib, $libloc, $sourcefiles, "la", "lo" );
3286        # no ranlib step here because we can't "link" the shared library
3287        # until all members are added.
3288        &SMInvokeAction( "OutputShLib", $lib, $libloc );
3289        &LibraryTimestampFix( $lib.".la", $libloc )
3290    }
3291}
3292
3293#
3294# This is the routine that creates a shared library from a library of
3295# shared objects. 
3296# This must be called from the directory containing the library.
3297# Still to do: provide a separate directory for the library, so
3298# that a build library may be used instead
3299#
3300# If we can't use .lo as an object extension, then after extracting,
3301# rename everything as .o and then build.
3302# TargetSharedLibraryFinal( "libmpich.la", "libmpich.so.1", dir )
3303#
3304# Note that we need to ensure that C_LINK_SHL is defined.  In turn,
3305# C_LINK_SHL may need CC, so we add that
3306#
3307# Another special feature: For some libraries, we may need an exports
3308# definition (by default, we'll export all symbols).  This is specified
3309# by defining the exports for a given library with a simplemake command:
3310# lib(name)_so_EXPORTS = filename
3311
3312sub TargetSharedLibraryFinal {
3313    my $libname = $_[0];
3314    my $newlibname = $_[1];
3315    my $libdir = $_[2];
3316
3317    my $libbasename = $libname;
3318    $libbasename =~ s/^lib//;
3319    $libbasename =~ s/\.la$//;
3320
3321    #print "Checing $libbasename in Final\n";
3322    if (defined($libNotShared{$libbasename})) {
3323        #print "Skipping $libbasename in final\n";
3324        return;
3325    }
3326
3327    if ($libdir eq "" || $newlibname eq "" || $libname eq "") {
3328        # If we don't have these names, we cannot create a valid library
3329        print STDOUT "Unable to create shared libary target (no directory\n\
3330library, or new library name)\n" if $debug;
3331        return;
3332    }
3333    if (!defined($ext_seen{"c"}) && $InitSharedLibraryFinal == 0) {
3334        # Remember that we made this definition
3335        $InitSharedLibraryFinal = 1;
3336        my $rule = $extdef{"c:o"};
3337        print FD "$rule\n";
3338    }
3339
3340    # See if this library needs an exports list
3341    my $exports = "";
3342    if (defined($shared_libraries_exports{$libbasename})) {
3343        my $exportFile = $shared_libraries_exports{$libbasename};
3344        if ($libdir ne "." && !($exportFile =~ /^\//)) {
3345            # make sure the exportFile refers to the correct location
3346            $exportFile = "\$(abs_srcdir)/$exportFile";
3347        }
3348        $exports = "-export $exportFile";
3349    }
3350    my $otherlibs = "";
3351    if (defined($shared_libraries_libs{$libbasename})) {
3352        $otherlibs = $shared_libraries_libs{$libbasename};
3353    }
3354    if (!defined($usertargets{"$libdir/$newlibname"})) {
3355        print FD "# Build the shared library from the shared object files\n";
3356        print FD "$libdir/$newlibname: $libdir/$libname
3357\t(cd $libdir && \$(CREATESHLIB) --mode=link -version-info \"\@ABIVERSION\@\" -o $libname $exports -rpath \$(libdir) $otherlibs)\n";
3358    }
3359    # If there is a profiling library, we need to build it
3360    # now, as part of this target, to handle the case where the
3361    # profiling library name might be the same as the regular name
3362    my $libbase = $libname;
3363    my $libext = ".so";
3364    if ($libbase =~ /lib(.*)(\..*)/) {
3365        $libbase = $1;
3366        $libext = $2;
3367    }
3368    if (defined($profile_libraries{$libbase})) {
3369        my $newbase = $profile_libraries{$libbase};
3370        $libname = "lib" . $newbase . $libext;
3371        if ($newlibname =~ /(.*lib)[^\/]*(\..*)/) {
3372            $newlibname = $1 . $newbase . $2;
3373        }
3374        print FD "\tif [ -n \"\@NO_WEAK_SYM\@\" -a \\
3375\t\t\"$libbase\" != \"$newbase\" ] ; then \\\n";
3376
3377        my $libbasename = $libname;
3378        $libbasename =~ s/^lib//;
3379        $libbasename =~ s/\.la$//;
3380        if (defined($shared_libraries_exports{$libbasename})) {
3381            my $exportFile = $shared_libraries_exports{$libbasename};
3382            if ($libdir ne "." && !($exportFile =~ /^\//)) {
3383                # make sure the exportFile refers to the correct location
3384                $exportFile = "\$(abs_srcdir)/$exportFile";
3385            }
3386            $exports = "-export $exportFile";
3387        }
3388        my $otherlibs = "";
3389        if (defined($shared_libraries_libs{$libbasename})) {
3390            $otherlibs = $shared_libraries_libs{$libbasename};
3391        }
3392
3393        print FD "\t(cd $libdir && \$(CREATESHLIB) --mode=link -version-info \"\@ABIVERSION\@\" -o $libname $exports -rpath \$(libdir) $otherlibs);\\\n";
3394
3395        print FD "\tfi\n";
3396    }
3397}
3398
3399
3400# Generate the target all-executable-local
3401sub TargetProgramsLocal {
3402    print FD "all-executable-local:";
3403    foreach $pgm (keys (%programs)) {
3404        if (defined($extra_programs{$pgm})) { next; }
3405        if (defined($extra_libs{$pgm})) { next; }
3406        print FD " $pgm";
3407    }
3408    print FD "$newline";
3409}
3410
3411
3412
3413#
3414# ===========================================================================
3415sub TargetPrograms {
3416    foreach $pgm (keys(%programs)) {
3417        # If there was a manual target, skip
3418        if (defined($usertargets{$pgm})) {
3419            print "Skipping generation of rule for $pgm because Makefile.sm already contains one\n";
3420            next;
3421        }
3422        &print_make_line( FD,  "$pgm: " );
3423        $pgmobjs = "";
3424        foreach $sourcefile (split(/\s+/,$programs{$pgm})) {
3425            $obj = $sourcefile;
3426            # Convert to object file
3427            $ext = $sourcefile;
3428            $ext =~ s/^.*\.//g;
3429            if (defined($extrules{"$ext:o"})) {
3430                $obj =~ s/\.$ext/\.o/g;
3431                &print_make_line( FD, "$obj " );
3432                $pgmobjs .= "$obj ";
3433            }
3434            else {
3435                if ($ext ne "h") {
3436                    print STDERR "Unknown extension $ext for $sourcefile for program $pgm\n";
3437                }
3438            }
3439        }
3440        # Add dependencies on libraries if requested
3441        $debug_lib_dependencies = 0;
3442        if ($convert_Ldir_to_relative) {
3443            print STDERR "Checking for relative dirs\n" if $debug_lib_dependencies;
3444            # convert -L dir -lname into dir/libname.a
3445            $libdep = "";
3446            if (defined($pgm_ldadd{$pgm})) {
3447                $libdep = $pgm_ldadd{$pgm};
3448            }
3449            $libdep =~ s/-L\s*([\w\.\/]*)\s*-l([\w-]*)//;
3450            $libdir = $1;
3451            $libname = $2;
3452            print STDERR "Checking $libdir and $libname\n" if $debug_lib_dependencies;
3453            if (defined($libdir) && defined($libname) &&
3454                $libdir ne "" && $libname ne "" &&
3455                !defined($external_libraries{$libname})) {
3456                &print_make_line( FD, " $libdir/lib$libname.a" );
3457            }
3458        }
3459        $otherdep = "";
3460        if (defined($pgm_depadd{$pgm})) {
3461            $otherdep = $pgm_depadd{$pgm};
3462        }
3463        if (defined($otherdep)) {
3464            &print_make_line( FD, " $otherdep" );
3465        }
3466        if (defined($depadd_all)) {
3467            &print_make_line( FD, " $depadd_all" );
3468        }
3469
3470        # Use the link rule appropriate for this program type
3471        #$pgmtype = $pgmsrctype{$pgm};
3472        &print_make_endline( FD );
3473        &print_make_setpos( 8 );
3474        $ruleline = "\t$progrules{$pgmsrctype{$pgm}} -o $pgm $pgmobjs";
3475        # We really need an libs before LIBS and libs after libs.
3476        if (defined($pgmlibs{$pgm})) {
3477            $ruleline .= " $pgmlibs{$pgm}";
3478        }
3479        if (defined($pgm_ldadd{$pgm})) {
3480            $ruleline .= " $pgm_ldadd{$pgm}";
3481        }
3482        $ruleline .= " \${LIBS}";
3483        &print_make_longline( FD, $ruleline );
3484    }
3485
3486}
3487
3488#
3489# ===========================================================================
3490sub TargetTags {
3491    if (!$local_tags && !$root_tags) { return; }
3492
3493    my $headerFiles = "";
3494    my $foundDerivedHeader = 0;
3495    my $sourceFiles = "";
3496    my $foundDerivedSource = 0;
3497    my $inputSources = "";
3498
3499    # Generate a listing of header and source files
3500    $has_sources = 0;
3501    $has_headers = 0;
3502    if ($regular_sources =~ /\S/) {
3503        printMakeVariable( FD, "SOURCES", $regular_sources );
3504        $inputSources = $regular_sources;
3505        $has_sources = 1;
3506    }
3507    elsif (defined($makevars{'SOURCES'})) {
3508        if ($makevars{'SOURCES'} =~ /\S/) {
3509            $has_sources = 1;
3510            $inputSources = $makevars{'SOURCES'};
3511        }
3512    }
3513    if ($has_sources) {
3514        foreach my $file (split(/\s+/,$inputSources)) {
3515            if (! ($file =~ /\S/)) { next; }
3516            # Check that these files exist, either directly or
3517            # as a '.in' version
3518            if (-s "$file.in") {
3519                $sourceFiles .= "\$(abs_builddir)/$file ";
3520                $foundDerivedSource = 1;
3521            }
3522            elsif (-s "$file") {
3523                $sourceFiles .= "$file ";
3524            }
3525            else {
3526                # Only complain about C files for now
3527                if ($file =~ /.*\.c$/) {
3528                    print STDERR "Warning: source file $file or $file.in not found in $curdir\n";
3529                }
3530            }
3531        }
3532    }
3533
3534    if ($regular_headers ne "") {
3535        printMakeVariable( FD, "HEADERS", $regular_headers );
3536        $has_headers = 1;
3537    }
3538    if (defined($makevars{'HEADERS'})) {
3539        $has_headers = 1;
3540        # Add these files to the headers variable.
3541        # headers is used to check on files that aren't handled by
3542        # simplemake
3543        foreach my $file (split(/\s+/,$makevars{'HEADERS'})) {
3544            if (! ($file =~ /\S/)) { next; }
3545            $headers{$file} = 1;
3546            # Check that these files exist, either directly or
3547            # as a '.in' version
3548            if (-s "$file.in") {
3549                $headerFiles .= "\$(abs_builddir)/$file ";
3550                $foundDerivedHeader = 1;
3551            }
3552            elsif (-s "$file") {
3553                $headerFiles .= "$file ";
3554            }
3555            else {
3556                print STDERR "Warning: header file $file or $file.in not found in $curdir\n";
3557            }
3558        }
3559    }
3560
3561    if ($has_headers || $has_sources) {
3562        # Make it eaiser to change the tags program options.
3563        # For example, this adds .i as a known "C" language file
3564        printMakeVariable( FD, "ETAGS", "\@ETAGS\@ \@ETAGSADD\@" );
3565        # The value of ETAGS was "etags --langmap=c:+.i" but
3566        # some Linux systems have a very old version of etags
3567        # that does not support --langmap.
3568    }
3569
3570    # Add a synonym for tags.
3571    if ($foundDerivedHeader) {
3572        printMakeVariable( FD, "HEADERFILES", $headerFiles );
3573    }
3574    else {
3575        printMakeVariable( FD, "HEADERFILES", '$(HEADERS)' );
3576    }
3577    if ($foundDerivedSource) {
3578        printMakeVariable( FD, "SOURCEFILES", $sourceFiles );
3579    }
3580    else {
3581        printMakeVariable( FD, "SOURCEFILES", '$(SOURCES)' );
3582    }
3583    print FD "tags: TAGS$newline";
3584    # By adding "Makefile" to TAGS, we ensure that the TAGS target
3585    # will be rebuilt anytime the package is reconfigured.  We
3586    # could also make TAGS always rebuild, to catch any source changes.
3587    print FD "TAGS: Makefile";
3588    # Only generate a local etags call if there are local sources
3589    # This target is designed for VPATH builds to build a TAGS file in
3590    if ($has_headers || $has_sources) {
3591        if ($local_tags) {
3592            print FD '${HEADERFILES} ${SOURCEFILES}
3593        here=`pwd`;\
3594        (cd ${srcdir} && $(ETAGS) -o $$here/TAGS --append ${HEADERFILES} ${SOURCEFILES};)
3595';
3596        }
3597        elsif ($root_tags) {
3598            print FD "\${HEADERFILES} \${SOURCEFILES}$newline";
3599            if (defined($rootdirpath)) {
3600                $rpath = $rootdirpath;
3601                $rpath =~ s/\/$//;
3602            }
3603            else {
3604                # Use current directory
3605                # Question: in this case, should we leave out the tags
3606                # target?
3607                $rpath = ".";
3608            }
3609            # For vpath builds, make the root path point to the
3610            # VPATH root.
3611           
3612            print FD "\there=\`cd $rpath && pwd\` ; cd \${srcdir} && \$(ETAGS) -o \$\$here/TAGS --append \${HEADERFILES} \${SOURCEFILES}$newline";
3613        }
3614        else {
3615            print FD "$newline";
3616        }
3617    }
3618    else {
3619        print FD "$newline";
3620    }
3621    # Tags on only the subdirs (really the source subdirs) and any
3622    # additional tags dirs
3623    @tmp_tags_dirs = (@subdirs,@tags_dirs);
3624    &RecursiveOp( "TAGS", "tmp_tags_dirs" );
3625    $#tmp_tags_dirs = -1;
3626}
3627#
3628# The generation of documentation (e.g., manual pages) is handled
3629# a little differently.  To make it easier to manage a VPATH build of
3630# everything, including the documentation, we:
3631#    Add the document output types as file extensions to SUFFIX
3632#    Add generic build rules (using variables for options)
3633#    Create targets using variable substitution.
3634# For example, to add html output (this shows *only* the document rules)
3635#
3636# .SUFFIXES: .c .html
3637# .c.html:
3638# \tdoctext -html $(DOCTEXT_OPTIONS) $<
3639# HTML: ${mpi_sources:.c=.html}
3640#
3641# In addition, we may need to generate a document target even if there are
3642# no files in this directory *if* there are subdirectories (the usual
3643# recursive target).
3644#
3645# Temporary repository:
3646# the doctext line from MPICH1
3647#       $doctext -ext 3 -mpath ../../man/man3 -I pubinc -heading MPI \
3648#                -quotefmt /home/MPI/mansrc/fortnotes \
3649#                -ignore EXPORT_MPI_API \
3650#                /home/MPI/mansrc/errnotes *.c ; \
3651#
3652# SuffixDocs: Add any suffix rules for this directory
3653sub SuffixDocs {
3654    # global: do_docs, suffixes, docsrc
3655    if (! $do_docs) { return; }
3656    foreach my $kind (keys(%docsrc)) {
3657        if ($docsrc{$kind} ne "") {
3658            $suffixes .= " .$kind";
3659        }
3660    }
3661    # Add source file suffixes
3662    if (! $suffixes || ! ($suffixes =~ /\.txt/) ) {
3663        $suffixes .= " .txt";
3664    }
3665}
3666sub VariableDocs {
3667    # global: do_docs, suffixes, docsrc
3668    if (! $do_docs) { return; }
3669    foreach my $kind (keys(%docsrc)) {
3670        ;
3671    }
3672    # Let us set doctext from configure.  We only need this if
3673    # we saw any sources.  This expresion is true if docsrc is non-empty
3674    if (scalar(%docsrc)) {
3675        printMakeVariable( FD, "DOCTEXT", "\@DOCTEXT\@" );
3676    }
3677}
3678
3679#
3680# Generate the rule for generating documentation from the source files
3681#
3682sub RuleDocs {
3683    # global: do_docs, docsrc, FD, newline
3684    if (! $do_docs) { return; }
3685    $rootdir = $rootdirpath;
3686    foreach my $kind (keys(%docsrc)) {
3687        # Set the default suffix
3688        $docsrcsuffix = ".c";
3689        if (defined($docsrc{$kind}) && $docsrc{$kind} ne "") {
3690            $docdestdir = $globaldocdir;
3691            if (defined($docdir{$kind}) && $docdir{$kind} ne "") {
3692                $docdestdir = $docdir{$kind};
3693            }
3694            # Replace ROOTDIR, including handling any doubled //
3695            $docdestdir =~ s/ROOTDIR/$rootdir/g;
3696            $docdestdir =~ s/\/\//\//g;
3697            # Replace any occurance of $dockinddirval is docdestdir
3698            if (defined($docthiskinddir{$kind})) {
3699                $dockinddirval = $docthiskinddir{$kind};
3700            }
3701            else {
3702                $dockinddirval = $dockinddir{$kind};
3703            }
3704            $docdestdir =~ s/(\$\w+)/$1/eeg;     # see man perlfaq4
3705            #
3706            # Replace ROOTDIR etc in any doc_namedefs
3707            $docargs = $doc_namedefs;
3708            if ($docargsAdd ne "") {
3709                $docargs .= " $docargsAdd";
3710            }
3711            $docargs =~ s/ROOTDIR/$rootdir/g;
3712            $docargs =~ s/\/\//\//g;
3713           
3714            # Check for an alternative suffix
3715            $docfiles = &ExpandMakeVars( $docsrc{$kind} );
3716            print "file list = $docfiles\n" if $debug;
3717            for $file (split(/\s+/,$docfiles)) {
3718                $file =~ /.*(\..*)$/;
3719                $suffix = $1;
3720                if ($docsrcsuffix ne $suffix) {
3721                    $docsrcsuffix = $suffix;
3722                }
3723            }
3724            print FD "$docsrcsuffix.$kind:$newline";
3725            $extarg = "";
3726            if ($kind eq "man" && ($docdestdir =~ /man(\d)$/)) {
3727                $extarg = "-ext $1";
3728            }
3729            print FD "\t\$(DOCTEXT) $doctextOptionName{$kind} -mpath $docdestdir $extarg -heading $doc_heading \\$newline";
3730            print FD "\t\t-quotefmt $docargs \$<$newline";
3731        }
3732    }
3733}
3734
3735#
3736# Given a list of sources, return an array containing the distinct suffixes
3737# (without the leading .)
3738sub GetSuffixList {
3739    my %suffixSeen = ();
3740    my $vars = $_[0];
3741    my @suffixes = ();
3742
3743    # Check for an alternative suffix
3744    $vars = &ExpandMakeVars( $vars );
3745    print "file list = $vars\n" if $debug;
3746    for $file (split(/\s+/,$vars)) {
3747        $file =~ /.*\.(.*)$/;
3748        $suffix = $1;
3749        if (!defined($suffixSeen{$suffix})) {
3750            $suffixSeen{$suffix} = 1;
3751            $suffixes[$#suffixes+1] = $suffix
3752        }
3753    }
3754    return @suffixes;
3755}
3756
3757sub SubForSuffixes {
3758    my $src = $_[0];
3759    my $suffixarrayName = $_[1];
3760    my $repSuffix = $_[2];
3761 
3762    for $suffix (@$suffixarrayName) {
3763        $src =~ s/\.$suffix/\.$kind/;
3764    }
3765    return $src;
3766}
3767
3768#
3769# Generate the documentation targets.
3770#
3771sub TargetDocs {
3772    if (! $do_docs || ! $maint_targets) { return; }
3773    my %didkind = ( "html" => 0, "man" => 0, "latex" => 0 );
3774
3775    print FD $makeBlockSep;
3776    foreach my $kind (keys(%docsrc)) {
3777        $targetKind = $docTargetName{$kind};
3778        print FD "$targetKind: ";
3779        my $src = $docsrc{$kind};
3780        if ($src ne "") {
3781            if ($src =~ /^\s*\$[\{\(][_\w]*[\}\)]\s*$/) {
3782                # a single variable: use make substitution if a single
3783                # suffix
3784                @suffixes = &GetSuffixList( $src );
3785                if ($#suffixes == 0) {
3786                    $src =~ s/\}/:.$suffixes[0]=.$kind\}/;
3787                }
3788                else {
3789                    # manually substitute
3790                    $src = &SubForSuffixes( $src, "suffixes", $kind );
3791                }
3792            }
3793            elsif ($src =~ /\$/) {
3794                # Perform variable expansion if possible
3795                $src = &ExpandMakeVars( $src );
3796                @suffixes = &GetSuffixList( $src );
3797                # Convert the extensions to the document type
3798                #$src =~ s/\.c/.$kind/;
3799                $src = &SubForSuffixes( $src, "suffixes", $kind );
3800            }
3801            else {
3802                $src =~ s/\.c/.$kind/;
3803            }
3804            print FD "$src$newline";
3805        }
3806        else {
3807            # This is the recursive branch
3808            print FD "$newline";
3809        }
3810        # If we're at the top; create any directories that are needed
3811        # This assumes a particular layout for the directories that
3812        # we'll eventually want to make adjustable.
3813        if ($doc_attop) {
3814            my @dirs = ();
3815            if ($kind eq "html") {
3816                @dirs = ( "www", "www/www1", "www/www3" );
3817            }
3818            elsif ($kind eq "man") {
3819                @dirs = ( "man", "man/man1", "man/man3" );
3820            }
3821            elsif ($kind eq "latex") {
3822                @dirs = ( "doc", "doc/refman" );
3823            }
3824            else {
3825                print STDERR "Unrecognized document type $kind\n";
3826            }
3827            foreach my $dir (@dirs) {
3828                print FD "\tif [ ! -d \${DESTDIR}$dir ] ; then mkdir \${DESTDIR}$dir ; fi$newline";
3829            }
3830        }
3831        &RecursiveOp( $targetKind );
3832        if ($#doc_subdirs >= 0) {
3833            &RecursiveOp( $targetKind, "doc_subdirs" );
3834        }
3835        if (defined($usertargets{"${targetKind}-local"})) {
3836            print FD "\t\${MAKE} ${targetKind}-local$newline";
3837        }
3838        $didkind{$kind} = 1;
3839    }
3840    #
3841    # For any directory that does not have any source files, we must still
3842    # generate a target *if* any directory set the source.
3843    foreach $kind ("html", "man", "latex") {
3844        $targetKind = $docTargetName{$kind};
3845        if (! $didkind{$kind} && $globaldockind{$kind}) {
3846            print FD "$targetKind:$newline";
3847            &RecursiveOp( $targetKind );
3848            if ($#doc_subdirs >= 0) {
3849                &RecursiveOp( $targetKind, "doc_subdirs" );
3850            }
3851        }
3852    }
3853    print FD $makeBlockSep;
3854}
3855
3856#
3857# Install target.  Question: does this need to list (or use a shell command
3858# to get) the filename for each individual file?
3859#
3860sub InstallDocs {
3861    # Add target only at the top
3862    if (!$doc_attop) { return; }
3863
3864    # Instead of this approach, we used a more general installdir
3865    # that handles these cases.
3866#     print FD "install-docs:$newline";
3867#     # Each document type is different.  In addition, we want the install
3868#     # to work even if the documents have not been built.
3869#     if ((!$didkind{"html"}) && $globaldockind{"html"}) {
3870#         print FD "\tif [ ! -d \$(htmldir) ] ; then \$(MKDIR_P) \$(htmldir) ; fi\n";
3871#       print FD "\tif [ -d www/www3 ] ; then \\$newline";
3872#       print FD "\t\$(INSTALL_DATA) www/www3/* \$(htmldir)/www3/ ; fi$newline";
3873#       print FD "\tif [ -d www/www1 ] ; then \\$newline";
3874#       print FD "\t\$(INSTALL_DATA) www/www1/* \$(htmldir)/www1/ ; fi$newline";
3875#     }
3876#     if ((!$didkind{"man"}) && $globaldockind{"man"}) {
3877#         print FD "\tif [ ! -d \$(mandir) ] ; then \$(MKDIR_P) \$(mandir) ; fi\n";
3878#       print FD "\tif [ -d man/man3 ] ; then \\$newline";
3879#       print FD "\t\$(INSTALL_DATA) man/man3/* \$(mandir)/man3/ ; fi $newline";
3880#       print FD "\tif [ -d man/man1 ] ; then \\$newline";
3881#       print FD "\t\$(INSTALL_DATA) man/man1/* \$(mandir)/man1/ ; fi $newline";
3882#     }
3883    # LaTeX manual is different and requires a special case
3884}
3885
3886# Add any dirs that are referred to by InstallDocs
3887sub InstallDocDirs {
3888    # Add target only at the top
3889    if (!$doc_attop) { return; }
3890
3891    print FD "htmldir         = \@htmldir\@\nmandir          = \@mandir\@\n";
3892}
3893
3894#
3895# Installation is complicated by VPATH builds; files that are derived and
3896# files that are not may be in different locations (one relative, the other
3897# absolute with respect to the source tree)
3898#
3899# Also, note that the documents and some other files may be pre-existing, so
3900# that we need to get them from the srcdir, not the build dir.  However,
3901# maintainers may create them in the builddir.
3902sub TargetInstall {
3903    %dirschecked = ();
3904    if (!scalar(%install_files) && !scalar($install_dirs) &&
3905        !scalar(%optinstall_files) && !scalar($optinstall_dirs)) {
3906        if (defined($usertargets{"install-local"}) && !$gIssuedInstallLocal) {
3907            # First add the indirect to the install-local target (when
3908            # there are no local files to install at all)
3909            print FD "install: install-local $newline";
3910        }
3911        return;
3912    }
3913    print FD "# Install target$newline";
3914    &TargetInit( "install" );
3915    print FD " FORCE_TARGET $newline";
3916    # Create the directories for the install directories
3917    foreach $kind (keys(%install_dirs)) {
3918        $dir = $InstallDirFromKind{$kind};
3919        if ($dir eq "") {
3920            print STDERR "No known installation dir for install_$kind\n";
3921            next;
3922        }
3923        if (!defined($dirschecked{$dir})) {
3924            # Check on dependent directories
3925            foreach $checkdir (split(/\s+/,$required_dirs{$dir})) {
3926                if ($checkdir ne "" && !defined($dirschecked{$checkdir})) {
3927                    $dirschecked{$checkdir} = 1;
3928                    print FD "\tif [ ! -d \${DESTDIR}\${$checkdir} ] ; then \$(MKDIR_P) \${DESTDIR}\${$checkdir} ; fi$newline";
3929                }
3930            }
3931            print FD "\tif [ ! -d \${DESTDIR}\${$dir} ] ; then \$(MKDIR_P) \${DESTDIR}\${$dir} ; fi$newline";
3932            $dirschecked{$dir} = 1;
3933        }
3934    }
3935
3936    # Handle the files
3937    foreach $kind (keys(%install_files)) {
3938        $dir = $InstallDirFromKind{$kind};
3939        if ($dir eq "") {
3940            print STDERR "No known installation dir for install_$kind\n";
3941            next;
3942        }
3943        if (!defined($dirschecked{$dir})) {
3944            # Check on dependent directories
3945            foreach $checkdir (split(/\s+/,$required_dirs{$dir})) {
3946                if ($checkdir ne "" && !defined($dirschecked{$checkdir})) {
3947                    $dirschecked{$checkdir} = 1;
3948                    print FD "\tif [ ! -d \${DESTDIR}\${$checkdir} ] ; then \$(MKDIR_P) \${DESTDIR}\${$checkdir} ; fi$newline";
3949                }
3950            }
3951            print FD "\tif [ ! -d \${DESTDIR}\${$dir} ] ; then \$(MKDIR_P) \${DESTDIR}\${$dir} ; fi$newline";
3952            $dirschecked{$dir} = 1;
3953        }
3954        #
3955        # If there is an install-local target, invoke it here:
3956        if (defined($usertargets{"install-local"}) && !$gIssuedInstallLocal) {
3957            if ($install_local_dirs ne "") {
3958                foreach my $dir (split(/\s+/,$install_local_dirs)) {
3959                    foreach $checkdir (split(/\s+/,$required_dirs{$dir})) {
3960                        if ($checkdir ne "" && !defined($dirschecked{$checkdir})) {
3961                            $dirschecked{$checkdir} = 1;
3962                            print FD "\tif [ ! -d \${DESTDIR}\${$checkdir} ] ; then \$(MKDIR_P) \${DESTDIR}\${$checkdir} ; fi$newline";
3963                        }
3964                    }
3965                    if ($dir ne "" && !defined($dirschecked{$dir})) {
3966                        $dirschecked{$dir} = 1;
3967                        print FD "\tif [ ! -d \${DESTDIR}\${$dir} ] ; then \$(MKDIR_P) \${DESTDIR}\${$dir} ; fi$newline";
3968                    }
3969                }
3970            }
3971            print FD "\t\${MAKE} install-local$newline";
3972            $gIssuedInstallLocal = 1;
3973        }
3974
3975        foreach $file (split(/\s+/,$install_files{$kind})) {
3976            $destfile = $file;
3977            $destfile =~ s/.*\///;
3978            $this_install_method = $install_methods{$kind};
3979            if ($this_install_method eq "") {
3980                $this_install_method = '$(INSTALL)';
3981                }
3982            print FD "\t$this_install_method $file \${DESTDIR}\${$dir}/$destfile$newline";
3983        }
3984    }
3985
3986    # Install any directories.  This asks for all files in the directory
3987    # to be installed.  It is typically used for things like manpages
3988    # that may be very numerous
3989    foreach $kind (keys(%install_dirs),keys(%optinstall_dirs)) {
3990        $dir = $InstallDirFromKind{$kind};
3991        foreach $srcdir (split(/\s+/,$install_dirs{$kind})) {
3992            # Choose the installation method based on the kind value
3993            if (!defined($install_methods{$kind})) {
3994                $this_install_choice = '$(INSTALL_PROGRAM)';
3995            }
3996            else {
3997                $this_install_choice = $install_methods{$kind};
3998            }
3999
4000            # This handles 2-level directories, such as man pages and
4001            # html pages (organized as man/man1-8 or www/www1-8).  A fully
4002            # recursive approach could be used, but it is felt that an
4003            # install should be constrained.  If there is a reason for an
4004            # install with three levels of directories, either install the
4005            # subdirectories separately or modify this code.
4006
4007            # Sigh.  This causes some make programs (such as gnumake)
4008            # to print a message about an ignored error.  To avoid that,
4009            # we turn the @-test into an @if test
4010            #print FD "\t\@-test -d $srcdir && cd $srcdir && for name in * ; do \\
4011            print FD "\t\@if test -d $srcdir && cd $srcdir ; then \\
4012\t for name in * ; do \\
4013\t  if [ \"\$\$name\" = \"*\" ] ; then continue ; fi ; \\
4014\t  if [ -f \$\$name ] ; then \\
4015\t    echo \"$this_install_choice \$\$name \${DESTDIR}\${$dir}/\$\$name\" ; \\
4016\t    $this_install_choice \$\$name \${DESTDIR}\${$dir}/\$\$name ; \\
4017\t  elif [ -d \$\$name ] ; then \\
4018\t    if [ ! -d \${DESTDIR}\${$dir}/\$\$name ] ; then \$(MKDIR_P) \${DESTDIR}\${$dir}/\$\$name ; fi ;\\
4019\t    ( cd \$\$name && for name2 in * ; do \\
4020\t        if [ \"\$\$name2\" = \"*\" ] ; then continue ; fi ; \\
4021\t        if [ -f \$\$name2 ] ; then \\
4022\t            echo \"$this_install_choice \$\$name2 \${DESTDIR}\${$dir}/\$\$name/\$\$name2\" ; \\
4023\t            $this_install_choice \$\$name2 \${DESTDIR}\${$dir}/\$\$name/\$\$name2 ; \\
4024\t        elif [ -d \$\$name2 ] ; then  \\
4025\t            echo \"cp -rp \$\$name2 \${DESTDIR}\${$dir}/\$\$name\" ; \\
4026\t            cp -rp \$\$name2 \${DESTDIR}\${$dir}/\$\$name ; \\
4027\t        fi \\
4028\t    done ) ; \\
4029\t  else \\
4030\t    echo \"Unknown file type for \$\$name\" ; \\
4031\t  fi ; \\
4032\t done ; \\
4033\tfi$newline";
4034        }
4035    }
4036
4037    foreach $kind (keys(%optinstall_files)) {
4038        $dir = $InstallDirFromKind{$kind};
4039        if (!defined($dirschecked{$dir})) {
4040            print FD "\tif [ ! -d \${DESTDIR}\${$dir} ] ; then \$(MKDIR_P) \${DESTDIR}\${$dir} ; fi$newline";
4041            $dirschecked{$dir} = 1;
4042        }
4043        foreach $filelist ($optinstall_files{$kind}) {
4044            foreach $file (split( /\s+/, $filelist)) {
4045                $destfile = $file;
4046                $destfile =~ s/.*\///;
4047                # Choose the installation method based on the kind value
4048                if (!defined($install_methods{$kind})) {
4049                    $this_install_choice = '$(INSTALL_PROGRAM)';
4050                }
4051                else {
4052                    $this_install_choice = $install_methods{$kind};
4053                }
4054                print FD "\tif [ -s $file ] ; then $this_install_choice $file \${DESTDIR}\${$dir}/$destfile ; fi$newline";
4055            }
4056        }
4057    }
4058    foreach $extradir (@install_subdirs) {
4059        # Check for configure substitutions in the list.  Make
4060        # these conditional, so that they can be empty.  Also note that
4061        # they could also contain *multiple* directories, so we have
4062        # to handle them in a general way
4063        #$endline = "";
4064        if ($extradir =~ /^@/) {
4065            print FD "\tfor dir in $extradir - ; do \\$newline";
4066            print FD "\t\tif [ \"\$\$dir\" = \"-\" ] ; then break ; fi ;\\$newline";
4067            print FD "\t\t(cd \$\$dir && \$(MAKE) INSTALL_STRIP_FLAG=\$(INSTALL_STRIP_FLAG) PACKAGE=\$(PACKAGE) install) ;\\$newline";
4068            print FD "\tdone$newline";
4069        }
4070        else {
4071            print FD "\t(cd $extradir && \$(MAKE) INSTALL_STRIP_FLAG=\$(INSTALL_STRIP_FLAG) install)$newline";
4072        }
4073    }
4074    &TargetPostamble( "install" );
4075    print FD "$newline";
4076
4077    # Install documentation
4078    &InstallDocs;
4079    #
4080    print FD "install-strip:$newline";
4081    print FD "\t\$(MAKE) INSTALL_STRIP_FLAG=-s install$newline";
4082   
4083    #
4084    # We should also create an uninstall target.  Rather than
4085    # unilaterally uninstalling files, we may want an option to create
4086    # a file that will uninstall only the installed files (as MPICH-1
4087    # does).
4088    &TargetInit( "uninstall" );
4089    print FD "\n";
4090    foreach $kind (keys(%install_files)) {
4091        $dir = $InstallDirFromKind{$kind};
4092        foreach $file (split(/\s+/,$install_files{$kind})) {
4093            $destfile = $file;
4094            $destfile =~ s/.*\///;
4095            if (defined($uninstall_methods{$kind})) {
4096                # This branch is subtly different from the else branch below
4097                # because it also passes the $file as the first argument. 
4098                # Strictly speaking, this is not compatible with using
4099                # libtool directly, so if we ever replace createshlib then
4100                # we should rework this uninstall target
4101                # just a bit. [goodell@mcs 2007-11-28]
4102                print FD "\t-$uninstall_methods{$kind} $file \${DESTDIR}\${$dir}/$destfile$newline";
4103            }
4104            else {
4105                print FD "\t-rm -f \${DESTDIR}\${$dir}/$destfile$newline";
4106            }
4107        }
4108    }
4109    foreach $kind (keys(%optinstall_files)) {
4110        $dir = $InstallDirFromKind{$kind};
4111        foreach $file (split(/\s+/,$optinstall_files{$kind})) {
4112            $destfile = $file;
4113            $destfile =~ s/.*\///;
4114            if (defined($uninstall_methods{$kind})) {
4115                # This branch is subtly different from the else branch below
4116                # because it also passes the $file as the first argument. 
4117                # Strictly speaking, this is not compatible with using
4118                # libtool directly, so if we ever replace createshlib then
4119                # we should rework this uninstall target just a
4120                # bit. [goodell@mcs 2007-11-28]
4121                print FD "\t-$uninstall_methods{$kind} $file \${DESTDIR}\${$dir}/$destfile$newline";
4122            }
4123            else {
4124                print FD "\t-rm -f \${DESTDIR}\${$dir}/$destfile$newline";
4125            }
4126        }
4127    }
4128    # Handle uninstalls controlled by subdirs
4129    if ($#install_subdirs >= 0) {
4130        &RecursiveOp( "uninstall", "install_subdirs" );
4131    }
4132    &TargetPostamble( "uninstall" );
4133
4134    # also add the recursive installcheck target
4135    &TargetInit( "installcheck" );
4136    if (defined($usertargets{"installcheck-local"})) {
4137        print FD " installcheck-local";
4138    }
4139    print FD $newline;
4140    if ($#install_subdirs >= 0) {
4141        &RecursiveOp( "installcheck", "install_subdirs" );
4142    }
4143    &TargetPostamble( "installcheck" );
4144}
4145
4146#--------------Kumud_parallel_fix--------------------------------
4147
4148#============================================================================
4149#The target to desend into sub-directories and create all the executables that
4150#needs to be created
4151#INSTALL_BIN = myexecutable
4152sub TargetExecutables {
4153
4154    print FD "all-executable: all-executable-local$newline";
4155    foreach $dir (@extra_dirs, @subdirs) {
4156        if ($dir eq ".") {
4157             # the pre-requisite all-executable-local already take care of this case.   
4158        }
4159        elsif ($dir =~ /@([^@]*)@/) {
4160            # May be a replaced variable
4161            print FD "\t${quietmake}for dir in $dir - ; do \\$newline";
4162            print FD "\t\tif [ \"\$\$dir\" = \"-\" ] ; then break ; fi ; \\$newline";
4163            print FD "\t\tif ( cd \$\$dir && \${MAKE} all-executable ) ; then : ; else exit 1; fi \\$newline";
4164            print FD "\tdone$newline";
4165        }
4166        else {
4167            print FD "\t${quietmake}(cd $dir && \${MAKE} all-executable )$newline";
4168        }
4169    }
4170   
4171
4172   
4173}
4174
4175
4176#
4177# ===========================================================================
4178# Other targets and stuff to be added:
4179#   CPP
4180#   Including common headers (e.g., all file.sm's get a common header of
4181#       variables defined by configure.  This is cleaner than the automake
4182#       approach of including *every* AC_SUBST value).
4183#   Support for shared libraries.  Unlike automake, we will not require
4184#       separate rules (automake uses lib_LTLIBRARIES and la extensions)
4185#       for shared library support.
4186#   Handling files to be installed (e.g., automake's sbin_PROGRAMS = ...)
4187#      (automake understands <dir>_PROGRAMS and <dir>_LIBRARIES)
4188#   target_LDFLAGS and general LDFLAGS
4189#   INCLUDES (automake variable that we've adopted) needs better control.
4190#   Support for .F and .F90 extensions (Fortran with preprocessor)
4191#   FLIBS
4192#   Linker choice.  simplemake uses the file type of the *first* source file.
4193#       automake has a matrix that depends on the source files referred to.
4194#   SCRIPTS (as in bin_SCRIPTS) targets
4195#   HEADERS variables (as in prog_HEADERS).  In many cases, this should
4196#       be determined automatically.  Note that it is needed for correct TAGS
4197#       generation.
4198
4199# Miscellaneous Routines
4200sub printHelp {
4201    print STDERR "\
4202simplemake [ -nocomments ] [ -am ] [ -libdir=NAME=DIR ] [ -include=LIST ]\
4203           files \
4204    -nocomments      - Exclude Makefile comments from generated file\
4205    -libdir=NAME=DIR - library NAME is located in directory DIR\
4206    -am              - Automake style target names\
4207    -include=LIST    - CPP style list of include directories (e.g., -Ia -Ib)\
4208                       These define INCLUDES unless a Makefile.sm defines\
4209                       that value\
4210    -v               - verbose output\
4211    -common=file     - Read text to include in every output file\
4212    -distrib         - Turn off all maintenance targets (make a distribution\
4213                       version)\
4214    -vpath=[yes|no]  - Create VPATH targets\
4215\
4216    -depend          - Generate dependency information as a make target\
4217    -depend=static   - Generate dependency information when simplemake runs\
4218    -nodepend        - Do not generate dependency information\
4219\
4220    -rootdir=PATH    - Set the root directory for all Makefiles\
4221    -configdir=PATH  - Location of the configure that controls the Makefile\
4222                       in this directory (used to rebuild a single \
4223                       Makefile.in)\
4224    -debug           - Turn on debugging output\
4225    -dos             - Use DOS-style newlines on output files\
4226    -interdirsleep   - Use a sleep between directory builds to handle problems\
4227                       with file systems that are not time-synchronized\
4228                       with the build node.  -interdirsleep=nn specifies\
4229                       an nn second sleep.\
4230    -smroot=dir      - Location of simplemake (absolute location)\
4231    -help            - This output\
4232    \n";
4233    print STDERR "\
4234    Recognized target forms\
4235    libname_a_SOURCES = source files for library \"name\"\
4236    libname_a_DIR     = location of directory into which lib \"name\" goes\
4237    SUBDIRS = blank separated list of subdirectories to process.  Use \".\"\
4238              to control the order in which the current directory is processed\
4239    DOC_SUBDIRS = blank separate list of subdirectories containing \
4240              documentation but no code source.  These directories may\
4241              contain files used as input to documentation generators.\
4242    EXTRA_PROGRAMS = names of programs to define rules for but not to build\
4243                     by default\
4244    EXTRA_LIBS = names of libraries to define rules for but not to build\
4245                     by default\
4246    name_SOURCES = source files for program \"name\"\
4247    name_LDADD   = extra linker flags for building program \"name\"\
4248\
4249    LDADD = extra linker flags to add to all programs\
4250    simplemake also allows all usual Makefile commands, including variable\
4251    assignment and targets.\n";
4252}
4253
4254#
4255# Generate dependency information when possible.  This version simply
4256# uses gcc -MM; if that doesn't work, does nothing. 
4257#
4258# Automake strives to generate the dependencies.  This is a better approach,
4259# but it is very difficult to implement in practice, particularly where the
4260# development environment is not GNU. 
4261#
4262# This is somewhat tricky because the current organization of MPICH2
4263# makes use of many -I<dir> switches, that are selected at configure time,
4264# so some files may not be where expected.
4265sub AddDependency {
4266    $target = $_[0];
4267    if (defined($makevars{"INCLUDES"})) {
4268        $include = $makevars{"INCLUDES"};
4269    }
4270    else {
4271        $include = $include_list;
4272    }
4273    print "Trying $make_depend $include $target\n" if $debug;
4274    $cmdline = "$make_depend $include $target";
4275    if (! $debug) {
4276        $cmdline .= " 2>/dev/null";
4277    }
4278    $cmdline .= " |";
4279    print "Depend commandline = $cmdline\n" if $debug;
4280    open( DEPFD, $cmdline ) || return;
4281    while (<DEPFD>) {
4282        # Remove files that are provided by the device
4283        s/\S*mpidpre\.h//g;
4284        s/\S*mpidpost\.h//g;
4285
4286        # For derived object files like lo and _xxx.o, add these
4287        if ($do_profilelibs && $found_profilelib) {
4288            s/^(.*)\.o:(.*)/$1.o _$1.o:$2/;
4289        }
4290        if ($do_sharedlibs || $found_sharedlib) {
4291            s/^(.*)\.o(.*)/$1.o $1.lo$2/;
4292        }
4293        print FD $_ ;
4294    }
4295    close( DEPFD );
4296}
4297
4298#
4299#
4300sub TargetDependenciesStatic {
4301    print FD "# Dependencies$newline";
4302    # Libraries first
4303    foreach $lib (keys(%libraries)) {
4304        foreach $sourcefile (split(/\s+/,&ExpandMakeVars($libraries{$lib}))) {
4305            # Get extension
4306            $ext = $sourcefile;
4307            $ext =~ s/^.*\.//g;
4308            # We only know about C for now.
4309            if ($ext eq "c") {
4310                &AddDependency( $sourcefile );
4311            }
4312        }
4313    }
4314    # Programs
4315    foreach $pgm (keys(%programs)) {
4316        foreach $sourcefile (split(/\s+/,$programs{$pgm})) {
4317            $ext = $sourcefile;
4318            $ext =~ s/^.*\.//g;
4319            # We only know about C for now.
4320            if ($ext eq "c") {
4321                &AddDependency( $sourcefile );
4322            }
4323        }
4324    }
4325}
4326
4327#
4328# Design:
4329# Each source file has an associated file containing dependencies, stored in
4330# a subdirectory .deps
4331#    Each source file foo has .deps/foo.d
4332#    The Makefile includes .deps/alldeps
4333#
4334# Because we want to support VPATH builds, we can't create these in the
4335# real source directory, so these directories and files must be created
4336# at configure time.
4337#
4338sub TargetDependenciesDynamic {
4339    my $has_sources = 0;
4340
4341    # First, are there any sources?
4342    # a hash in a scalar context is 0 if empty and nonzero otherwise
4343    if (scalar(%libraries) || scalar(%programs)) {
4344        $has_sources = 1;
4345    }
4346   
4347   
4348    # Some makes will accept sinclude instead of -include
4349    # -include is gnumake for "include if file exists, ignore otherwise"
4350    if ($makeInclude eq "") { $makeInclude = "-include"; }
4351
4352    print FD $makeBlockSep;
4353    print FD "# Dependencies$newline";
4354    # This definition follows the one for COMPILE_C
4355    if ($has_sources) {
4356        # By setting DEPS_DIR to just ., you can use -MMD to update the
4357        # dependencies with gcc
4358        print FD "DEPS_DIR = .deps$newline";
4359        # We'd like to use $found_profilelib to decide whether
4360        # to include the _$*.o in the target string. 
4361        # But make wants to do the $* substitutions before variable
4362        # substitutions
4363        printMakeVariable( FD, "MAKE_DEPEND_C",
4364             "\@MAKE_DEPEND_C\@ \$(DEFS) \$(INCLUDES) \$(CPPFLAGS)$newline" );
4365        print FD "dependencies: \$(DEPS_DIR)/timestamp$newline";
4366    }
4367    else {
4368        print FD "dependencies:$newline";
4369    }
4370    &RecursiveOp( "dependencies" );
4371
4372    # First, generate the targets to maintain the individual files.
4373    # This makes it easy to update the dependency contents without
4374    # regenerating the entire list.
4375    # Note that we don't always want to use this target, since
4376    # the dependencies may need to be regenerated when other files change.
4377    # Even better is to use this to update the dependency files
4378    # when each file is compile (gcc can almost do this, as long as
4379    # you don't mind having .d files in the build directory)
4380    if ($has_sources) {
4381        # Use $found_profilelib to decide whether to add _xxx.o to the
4382        # target name.  This requires that the MAKE_DEPEND_C compiler
4383        # accept the -MT option
4384        #
4385        my %sawFile = ();
4386        foreach $lib (keys(%libraries)) {
4387            # Its possible that the same file is used in several libraries.
4388            # Thus, we only look at unique files.
4389            foreach $sourcefile (split(/\s+/,&ExpandMakeVars($libraries{$lib}))) {
4390                if (defined($sawFile{$sourcefile})) { next; }
4391                $sawFile{$sourcefile} = 1;
4392                # FIXME: If, for some reason, the source file is created by
4393                # configure, then simplemake will get confused.
4394                my $srcdirloc = '$(srcdir)/';
4395                $ext = $sourcefile;
4396                $ext =~ s/^.*\.//g;
4397                $sourcebasename = $sourcefile;
4398                $sourcebasename =~ s/\.\w*$//;
4399                my $targetOpts = "-MT \'_$sourcebasename.o $sourcebasename.o\'";
4400                if (!$found_profilelib) {
4401                    $targetOpts = "";
4402                }
4403                # We can not use $< in an explicit target context because
4404                # some Make programs do not handle them properly (Solaris,
4405                # for one)
4406                if ($ext eq "c") {
4407                    if (! -s $sourcefile) {
4408                        my $missingFile = "$curdir/$sourcefile";
4409                        $missingFile =~ s%//%/%g;
4410                        print STDERR "Sourcefile $missingFile does not exist.\
4411simplemake is assuming that this file will be created by the configure step\
4412in the build directory\n";
4413                        $srcdirloc = '';
4414                    }
4415                    print FD "\$(DEPS_DIR)/$sourcebasename.d: $srcdirloc$sourcefile$newline";
4416                    print FD "\t\$(MAKE_DEPEND_C) $targetOpts $srcdirloc$sourcefile >\$(DEPS_DIR)/$sourcebasename.d$newline";
4417                }
4418            }
4419        }
4420    }
4421
4422    if ($has_sources) {
4423        print FD "\$(DEPS_DIR)/timestamp: ";
4424        # FIXME: Create a single list of source files (remove duplicates)
4425        foreach $lib (keys(%libraries)) {
4426            $sourcefiles = $libraries{$lib};
4427            PrintMakeLongline( FD, "$sourcefiles ", "append" );
4428        }
4429        foreach $pgm (keys(%programs)) {
4430            print "Adding sources for $pgm to deps\n" if $debug;
4431            $sourcefiles = $programs{$pgm};
4432            PrintMakeLongline( FD, "$sourcefiles ", "append" );
4433        }
4434        # Add Makefile as a dependency, since changes in the Makefile
4435        # can change the dependencies (particularly different configure
4436        # choices)
4437        PrintMakeLongline( FD, "Makefile", "last" );
4438
4439        # We always use a "newalldeps" incase there is a failure
4440        # creating the new list of dependency files.
4441        print FD "\trm -f \$(DEPS_DIR)/newalldeps$newline";
4442        my %sawFile = ();
4443        foreach $lib (keys(%libraries)) {
4444            foreach $sourcefile (split(/\s+/,&ExpandMakeVars($libraries{$lib}))) {
4445                if (defined($sawFile{$sourcefile})) { next; }
4446                $sawFile{$sourcefile} = 1;
4447                my $srcdirloc = '$(srcdir)/';
4448                $ext = $sourcefile;
4449                $ext =~ s/^.*\.//g;
4450                $sourcebasename = $sourcefile;
4451                $sourcebasename =~ s/\.\w*$//;
4452                if ($ext eq "c") {
4453                    if (! -s $sourcefile) {
4454                        $srcdirloc = '';
4455                    }
4456                    $targetOpts = "-MT \'_$sourcebasename.o $sourcebasename.o\'";
4457                    if (!$found_profilelib) {
4458                        $targetOpts = "";
4459                    }
4460                    print FD "\t\$(MAKE_DEPEND_C) $targetOpts $srcdirloc$sourcefile >\$(DEPS_DIR)/$sourcebasename.d$newline";
4461                    print FD "\techo \"$makeInclude \$(DEPS_DIR)/$sourcebasename.d\" >>\$(DEPS_DIR)/newalldeps$newline";
4462                }
4463            }
4464        }
4465
4466        # Programs
4467        foreach $pgm (keys(%programs)) {
4468            foreach $sourcefile (split(/\s+/,$programs{$pgm})) {
4469                if (defined($sawFile{$sourcefile})) { next; }
4470                print "Adding deps command for program source $sourcefile\n" if $debug;
4471                $sawFile{$sourcefile} = 1;
4472                my $srcdirloc = '$(srcdir)/';
4473                $ext = $sourcefile;
4474                $ext =~ s/^.*\.//g;
4475                $sourcebasename = $sourcefile;
4476                $sourcebasename =~ s/\.\w*$//;
4477                if ($ext eq "c") {
4478                    if (! -s $sourcefile) {
4479                        $srcdirloc = '';
4480                    }
4481                    $targetOpts = "-MT \'_$sourcebasename.o $sourcebasename.o\'";
4482                    if (!$found_profilelib) {
4483                        $targetOpts = "";
4484                    }
4485                    print FD "\t\$(MAKE_DEPEND_C) $targetOpts $srcdirloc$sourcefile >\$(DEPS_DIR)/$sourcebasename.d$newline";
4486                    print FD "\techo \"$makeInclude \$(DEPS_DIR)/$sourcebasename.d\" >>\$(DEPS_DIR)/newalldeps$newline";
4487                }
4488            }
4489        }
4490
4491        print FD "\tif [ -s \$(DEPS_DIR)/newalldeps ] ; then mv -f \$(DEPS_DIR)/newalldeps \$(DEPS_DIR)/alldeps ; fi$newline";
4492        print FD "\tdate >\$(DEPS_DIR)/timestamp$newline";
4493
4494        print FD "$makeInclude \$(DEPS_DIR)/alldeps$newline";
4495    }
4496   
4497    print FD "# End of Dependencies$newline";
4498    print FD $makeBlockSep;
4499}
4500
4501sub DistCleanDependencies {
4502    # Eventually, this should output only in Makefiles that have the
4503    # dependencies directory
4504    print FD "\t-${quietLine}rm -rf \$(DEPS_DIR)$newline";
4505}
4506
4507# ===========================================================================
4508#
4509# Routines to support autoconf and configure, including extracting information
4510# from the configure file and rebuilding configure from configure.in
4511#
4512#
4513# Extract derived files from autoconf
4514# Also record whether there is an AC_CONFIG_HEADER
4515# If AC_OUTOUT contains any shell variables, you can use
4516#   <variable_name>_VALUES=vals
4517# (all on one line!) to provide the set of possible values.
4518# Otherwise, no special code will be generated for those output files,
4519# and a warning message will be issued.
4520# FIXME: the name is recorded and added to the files, but simplemake
4521# may not be careful about the file or about directory paths involving the
4522# xxx_VALUE variable.  Still experimental
4523sub ReadAutoconf {
4524    $configure_has_config_headers = "no";
4525    %confvars = ();
4526    open FDCONF, "configure.in" || die "Could not open configure.in file";
4527    while (<FDCONF>) {
4528        #if (/^\s*#/) { next; }
4529        if (/^\s*AC_CONFIG_HEADER\((.*)\)/) {
4530            # Record file name of header in result variable
4531            # We also need to add this to the list of files to remove
4532            # in the distclean target
4533            $configure_has_config_headers = $1;
4534        }
4535        if (/^\s*(\w*)_VALUES=(.*)/) {
4536            # This is a special case, used below
4537            $confvars{$1}=$2
4538        }
4539        if (/^\s*AC_OUTPUT\(/) {
4540            # First, read past all continued lines
4541            $line = "";
4542            # Remove any M4 dnl line
4543            s/\sdnl\s.*//;
4544            # Later versions of Autoconf do not require explicit continuation
4545            # so we also read until we find the closing paren
4546            while (/\\\s*$/) {
4547                s/\r?\n$//; # Removes eol on both Unix and Windows
4548                chop($_); # remove the backslash
4549                $line .= $_;
4550                $_ = <FDCONF>;
4551                die "unexpected EOF in configure.in, aborting" unless defined $_;
4552                # Remove any M4 dnl line
4553                s/\sdnl\s.*//;
4554                # Remove any shell comment line
4555                s/\s#.*//;
4556            }
4557            $line .= $_;
4558            $line =~ s/\r?\n$//; # Removes eol on both Unix and Windows
4559            $line =~ s/,.*/\)/;  # Changes a ,... to ) to handle
4560                                 # AC_OUTPUT(files...,[command]),
4561                                 # where the final ) may not be on this line
4562            #print $line;
4563            # If there's no closing paren yet, keep reading
4564            while (! ($line =~ /\)/)) {
4565                $_ = <FDCONF>;
4566                die "unexpected EOF in configure.in, aborting" unless defined $_;
4567                s/\r?\n$//; # Removes eol on both Unix and Windows
4568                # Remove any M4 dnl line
4569                s/\sdnl\s.*//;
4570                # Remove any shell comment line
4571                s/\s#.*//;
4572                $line .= $_ . " ";
4573            }
4574            #print "ac_output line = $line\n";
4575            $line =~ /^\s*AC_OUTPUT\((.*)\)\s*$/;
4576            $files = $1;
4577            if (! defined($files) ) {
4578                print STDERR "Unable to find file names in AC_OUTPUT\n";
4579                $files = "";
4580            }
4581            #print "files for ac_output = $files\n";
4582            @autoconf_files = split(/\s+/,$files);
4583            # Create a hash by directory
4584            # FIXME: Should curdir be blank by default?
4585            if (!$curdir) { $curdir = ""; }
4586            $lcurdir = $curdir;
4587            $lcurdir =~ s/\/$//;
4588            foreach $file (@autoconf_files) {
4589                if ($file =~ /^(.*)\/([^\/]*)$/) {
4590                    # File contains a directory path, so update the
4591                    # appropriate directory entry
4592                    my $ndir     = "$curdir$1";
4593                    my $leaffile = $2;
4594
4595                    if (defined($autoconf_files_by_dir{$ndir})) {
4596                        $autoconf_files_by_dir{$ndir} .= " $leaffile";
4597                    }
4598                    else {
4599                        $autoconf_files_by_dir{$ndir} = "$leaffile";
4600                    }
4601                    #print "{$ndir} .= $2\n";
4602                    # Also add files that are in directories with no simplemake
4603                    # input (e.g., in include directories with no makefile)
4604                    if (! -s "$ndir/Makefile.sm") {
4605                        if (defined($autoconf_files_by_dir{$lcurdir})) {
4606                            $autoconf_files_by_dir{$lcurdir} .= " $file";
4607                        }
4608                        else {
4609                            $autoconf_files_by_dir{$lcurdir} = "$file";
4610                        }
4611                    }
4612                    else {
4613                        # We also need to handle files that do have a
4614                        # Makefile.sm,
4615                        # but that aren't in the "usual" path.  Those
4616                        # are directories that are not included in the
4617                        # SUBDIRS path.  These are used only by the distclean
4618                        # target
4619                        $autoconf_files_by_dir_orig{$lcurdir} .= " $file";
4620                    }
4621                }
4622                elsif ($file =~ /^\$[\{\(]?(\w*)[\}\)]?/) {
4623                    # Another special case.  The name is actually
4624                    # a shell variable.  This is too hard for us right now,
4625                    # so generate a warning and do NOT add it to the list
4626                    # To handle this case, you can provide
4627                    # <variable-name>_VALUES
4628                    $varname = $1;
4629                    if (defined($confvars{$varname})) {
4630                        # add to autoconf_files_by_dir
4631                        foreach $filename (split(/\s+/,$confvars{$varname})) {
4632                            $autoconf_files_by_dir{$lcurdir} .= " $file";
4633                        }
4634                    }
4635                    else {
4636                        print STDERR "Shell variable $varname will not be added to the list\
4637of known autoconf files for ";
4638                        if (defined($lcurdir) && $lcurdir ne "") {
4639                            print STDERR "$lcurdir.\n";
4640                        }
4641                        else {
4642                            print STDERR "the top directory.\n";
4643                        }
4644                    }
4645                }
4646                elsif ($file =~ /^.*$/) {
4647                    if (defined($autoconf_files_by_dir{"$lcurdir"})) {
4648                        $autoconf_files_by_dir{"$lcurdir"} .= " $file";
4649                    }
4650                    else {
4651                        $autoconf_files_by_dir{"$lcurdir"} = "$file";
4652                    }
4653
4654                    #print "{$lcurdir} .= $file\n";
4655                }
4656            }
4657            # Add files that configure generates in the current directory
4658            $autoconf_files_by_dir{$lcurdir} .= " config.status config.log config.cache *conf.cache config.system";
4659            #print "$files\n";
4660            last;
4661        }
4662    }
4663    close FDCONF;
4664}
4665#
4666# Find how to get from path_child to path_parent.  Return as
4667# ../.. etc, suitable for using cd to get to the parent
4668sub GetPathToParent {
4669    my ($path_child, $path_parent) = @_;
4670    # Remove parent path from child path
4671    if (defined($path_parent)) {
4672        # first, deal with a possible "." path
4673        $path_parent = quotemeta $path_parent;
4674        #print "path_parent = $path_parent, child = $path_child\n";
4675        $path_child =~ s/^$path_parent//;
4676        #print "After parent, child = $path_child\n";
4677        # convert all of the non directory separators into ..
4678    }
4679    else {
4680        print STDERR "Path to parent is unknown in GetPathToParent\n";
4681        # Set a default
4682        $path_child = ".";
4683    }
4684    $path_child =~ s/[^\/\.]*\//..\//g;
4685    return $path_child;
4686}
4687
4688#
4689# Remove any trailing .. from the directory as well as that many directories
4690sub CleanCurDir {
4691    my $dir = $_[0];
4692    my $depth = 0;
4693
4694    # Handle any /.. at the end
4695    print "Cleaning directory name $dir...\n" if $debug_confdir;
4696    $dir =~ s/\/$//;
4697    while ($dir =~ /\/\.\.$/) {
4698        $depth++;
4699        $dir =~ s/\/\.\.$//;
4700    }
4701    while ($depth > 0) {
4702        $dir =~ s/\/[^\/]*//;
4703        $depth--;
4704    }
4705
4706    # We sometimes get ../ in the middle
4707    while ($dir =~ /(.*)\/[^\/\.]+\/\.\.(.*)/) {
4708        print "Changing $dir to $1$2\n" if $debug_confdir;
4709        $dir = "$1$2";
4710    }
4711    if ($dir ne "") { $dir .= "/"; }
4712    print "Cleaned directory name is $dir\n" if $debug_confdir;
4713    return "$dir";
4714}   
4715#
4716# ===========================================================================
4717# Pretty print output lines.  These routines insert line breaks and tabs
4718# to keep the generated makefile from being too ugly.  These also use
4719# tabs after a continuation line.
4720$linelen = 0;
4721sub printInit {
4722    $linelen = 0;
4723}
4724sub print_make_line {
4725    my $FD = $_[0];
4726    my $line = "$_[1]";
4727    my $len = length($line);
4728    if ($linelen + $len + 2 > $maxline) {
4729        print $FD "\\$newline\t";
4730        $linelen = 8;
4731    }
4732    print $FD $line;
4733    $linelen += $len;
4734    }
4735# print_make_line_nobreak is like print_make_line, but it never breaks a line
4736# This is needed when the output is a configure variable that may end
4737# up being replaced with blanks; if this occurs alone on a line, some
4738# make programs become confused.
4739sub print_make_line_nobreak {
4740    my $FD = $_[0];
4741    my $line = "$_[1]";
4742    my $len = length($line);
4743    print $FD $line;
4744    $linelen += $len;
4745    }
4746sub print_make_endline {
4747    my $FD = $_[0];
4748    print $FD $newline;
4749    $linelen = 0;
4750}
4751sub print_make_setpos {
4752    $linelen = $_[0];
4753}
4754# print_make_longline is intended for printing long lines that contains blanks
4755# This adds the newline at the end
4756sub print_make_longline {
4757    my $FD = $_[0];
4758    my $line = $_[1];
4759    &PrintMakeLongline( $FD, $line, "last" );
4760}
4761
4762# New print routines
4763# PrintMakeLongline( FD, line, flag ) - line may have spaces, will break
4764# as spaces in line.  Flag may be "append" or "last".  line may be empty
4765# (to use flag = "last" to terminate.
4766sub PrintMakeLongline {
4767    my $FD = $_[0];
4768    my $line = $_[1];
4769    my $flag = $_[2];
4770
4771    my $len = length( $line );
4772    if ($linelen + $len + 2 < $maxline) {
4773        print $FD $line;
4774    }
4775    else {
4776        # Use space, not \s, because we want tabs to remain tabs
4777        foreach my $token (split(/ /,$line)) {
4778            # We must be careful not to add a blank if the token is
4779            # a \ used at the end of a line to continue to the
4780            # next line
4781            if ($token eq "\\") {
4782                &print_make_line( $FD, "$token" );
4783            }
4784            else {
4785                &print_make_line( $FD, "$token " );
4786            }
4787        }
4788    }
4789    if ($flag eq "last") {
4790        &print_make_endline( $FD );
4791    }
4792}
4793# Print a Make variable definition only if it hasn't been made already
4794# Add and prepend value that may have been specified
4795sub printMakeVariable {
4796    my ($FD,$var,$definition) = @_;
4797
4798    if (!defined($addedMakeVars{$var})) {
4799        $addedMakeVars{$var} = $definition;
4800        if (defined($PrependVar{$var})) {
4801            $definition = $PrependVar{$var} . $definition;
4802        }
4803        my $nspace = 16 - length($var);
4804        my $blanks = "";
4805        while ($nspace > 0) { $blanks .= " "; $nspace-- }
4806        PrintMakeLongline( $FD, "$var$blanks= $definition", "last" );
4807    }
4808    elsif ($addedMakeVars{$var} ne $definition) {
4809        my $value = $addedMakeVars{$var};
4810        print STDERR "Variable $var, being defined with $definition, already has value $value\n";
4811    }
4812}
4813#
4814# Find a working autoconf.
4815# If the variables autoconf and autoconf_version are set, try to
4816# find one that works in the user's path.  The format for these
4817# variables is
4818#   autoconf = name:name:...:lasthope
4819#   autoconf_version = number
4820#   Check each autoconf name for handling version.  If all else fails,
4821#   unconditionally accept lasthope
4822sub FindWorkingAutoconf {
4823    if ($autoconf_version ne "") {
4824        foreach $file (split(/:/,$autoconf)) {
4825            $lastfile = $file;
4826            # Grumble.  I need to redirect stderr to stdout before this
4827            # open.  We use open with a pipe and then exec so that we
4828            # can get stderr redirection to work correctly.
4829            #
4830            # Additional grumble.  Perl doesn't flush output the
4831            # way you'd like.  Of course, if you turn on -debug,
4832            # things do get flushed.
4833            $pid = open( ACFD, "-|");
4834            if ($pid == 0) {
4835                close FD;  # without flushing
4836                open STDIN, "/dev/null";
4837                open STDERR, ">>&STDOUT";
4838                exec split(/\s+/,"$file --version");
4839            }
4840            else {
4841                $found_version = "";
4842                while (<ACFD>) {
4843                    print STDERR "$_" if $debug;
4844                    if (/[Aa]utoconf\s.*([12]\.[0-9]+)/) {
4845                        $found_version = $1;
4846                        last;
4847                    }
4848                }
4849                close( ACFD );
4850                print STDERR "Autoconf $file is version $found_version\n" if $debug;
4851                if ($found_version >= $autoconf_version) {
4852                    $autoconf = $file;
4853                    print STDERR "Using autoconf $file\n" if $debug;
4854                    return;
4855                }
4856            }
4857        }
4858        # If we got here, use the lastchance
4859        $autoconf = $lastfile;
4860    }
4861}
4862#
4863# ----------------------------------------------------------------------------
4864# Coverage analysis
4865# One useful target for package maintainers is coverage analysis. 
4866# The following code creates the targets for the gcc coverage analyzer,
4867# gcov.  In tests, this analyzer worked with programs built from libraries
4868# and with sources in multiple directories.
4869#
4870# To use the gcc coverage analyzer, the following steps must be taken
4871# 1.  All file must be compiled with -fprofile-arcs -ftest-coverage, and
4872#     without optimization
4873# 2.  Programs are run as usual
4874# 3.  To create coverage data, run
4875#         gcov -f -b sourcefile
4876#     over all source files.  The result is (for each sourcefile) a
4877#     new file, "sourcefile.gcov", which annotates the source file with
4878#     the number of times each statement was executed
4879#
4880# To add support for these, simplemake adds the following targets in
4881# maintenance target mode (e.g., not in the distributed version):
4882#     Add to clean (all with ${srcdir}) *.bb, *.bbg, *.da, *.c.gcov . 
4883#         These are all created by either gcc or by running programs
4884#         built with -ftest-coverage.
4885#     Add a recursive coverage target that does:
4886#         Run gcov on each source file (if any), where a .da file is present
4887#     We may be able to use a target like:
4888#         $*.c.gcov depends on $*.da (.da.gcov)
4889#     We let the configure step add the compiler options (so that a
4890#     separate simplemake build is not required to add or remove
4891#     coverage analysis.
4892#
4893# ToDo:
4894# In the install step, mkdir isn't right, since it will make only one
4895# directory level, and mkdir -p isn't universally available.  We probably
4896# need either a MKDIR_P command, determined byu configure, or an
4897# mkinstalldirs script.  I'd prefer a mkdirp script, used only if mkdir -p
4898# did not work, and chosen by configure in that case.
4899# This is partially done (MKDIR_P and that is set to mkdir -p)
4900# ----------------------------------------------------------------------------
4901# Add the clean target for the coverage analyzer.
4902# We inculde the local directory because, particularly for the test programs,
4903# these files may be left in the current directory rather than the source
4904# directory.
4905#
4906sub GcovClean {
4907    if ($maint_targets) {
4908        print FD "\t-${quietLine}rm -f \${srcdir}/*.bb \${srcdir}/*.bbg \${srcdir}/*.da$newline";
4909        print FD "\t-${quietLine}rm -f \${srcdir}/*.gcda \${srcdir}/*.gcno$newline";
4910        print FD "\t-${quietLine}rm -f *.gcov *.bb *.bbg *.da *.gcda *.gcno$newline";
4911    }
4912}
4913
4914# coverage target
4915sub TargetGcov {
4916    if (!$maint_targets) { return; }
4917    &TargetInit( "coverage" );
4918    print FD "$newline";
4919    foreach $lib (keys(%libraries)) {
4920        $sourcefiles = $libraries{$lib};
4921        PrintMakeLongline( FD,
4922           "\t-${quietmake}for file in $sourcefiles ; do \\", "last" );
4923        print FD "\t\tgcov -b -f \$\$file ; done$newline";
4924    }
4925    &RecursiveOp( "coverage" );
4926    &TargetPostamble( "coverage" );
4927}
4928#
4929# ----------------------------------------------------------------------------
4930#
4931# ToDo
4932# Should we add a target to strip debugging information from the object files?
4933# For example, strip -S *.o .  Ths usually isn't necessary if -g is not
4934# selected when building the object files.
4935#
4936# David Ashton suggests an option to print a warning message for
4937# each source file (e.g., *.c, *.cxx, *.f, *.f90) that has no corresponding
4938# entry in the Makefile.sm
4939#
4940# Here is a start on that.
4941# What is still needed is a way to check for defined sources when the source