#! /bin/sh
#
# If these # comments don't work with your shell, trim them.
# This script is derived from Larry Wall's general-purpose Configure script.
#
# Mark C Favas 1992
#

: Set list of required files
MANIFEST="XTAB XLIB xsel.f"

cat >/tmp/c1$$ <<EOF
ARGGGHHHH!!!!!

SCO csh still thinks true is false. Write to SCO today and tell them that next
year Install ought to "rm /bin/csh" unless they fix their blasted shell. :-)

(Actually, Install ought to just patch csh in place. Hmm. Hmmmmm. All
we'd have to do is go in and swap the && and || tokens, wherever they are...)

[End of diatribe. We now return you to your regularly scheduled programming.]

EOF
cat >/tmp/c2$$ <<EOF
OOPS!  You naughty creature!  You didn't run Install with sh!
I will attempt to remedy the situation by running sh for you...

EOF

true || cat /tmp/c1$$ /tmp/c2$$
true || exec sh $0

export PATH || cat /tmp/c2$$
export PATH || exec sh $0
rm -f /tmp/c1$$ /tmp/c2$$

PATH=".:$PATH:/bin:/usr/bin:/usr/local/bin:/usr/ucb:/usr/bsd:/usr/local"
PATH=":$PATH:/usr/lbin:/usr/etc:/etc:/usr/new:/usr/new/bin:/usr/nbin"

if test ! -t 0; then
    echo "Say 'sh Install', not 'sh <Install'"
    exit 1
fi

(alias) >/dev/null 2>&1 && \
    echo "(I see you are using the Korn shell (ksh). Some ksh's fail to" && \
    echo "work correctly on Install, especially on exotic machines." && \
    echo "If your ksh fails on this script, try the Bourne shell instead.)"

: Create the directory to hold the source files, if not already created.
SRC=src
if test ! -d "$SRC"; then
    mkdir $SRC
fi

: Get where we are
curdir=`pwd`

: clean up
rm -f *.imp select >/dev/null 2>&1

: Create working directory if necessary, and cd to it
if test ! -d UU; then
    mkdir UU
fi
cd UU

: Initialize some variables here
sh=''
memory='250000'
mach_type=''
gks=''
cmp=''
f77=''
loclist=''
chmod=''
expr=''
sed=''
grep=''
echo=''
cat=''
rm=''
mv=''
cp=''
tr=''
grep=''
trylist=''
test=''
uname=''
machine=''
awk=''
nawk=''
make=''
bin=''
contains=''
makeflags=''
strings=''
optimize=''
ldflags=''
libs=''
n=''
c=''
spitshell=''
shsharp=''
sharpbang=''
startsh=''
addlibs=''

: Some greps do not return status, grrr.
echo "grimblepritz" >contains.txt
if grep blurfldyick contains.txt >/dev/null 2>&1 ; then
    contains=contains
elif grep grimblepritz contains.txt >/dev/null 2>&1 ; then
    contains=grep
else
    contains=contains
fi
: the following should work in any shell
case "$contains" in
contains*)
    cat >contains <<'EOS'
grep "$1" "$2" >.greptmp && cat .greptmp && test -s .greptmp
EOS
chmod +x contains
esac

: Determine how to suppress newline on echo command
(echo "hi there\c" ; echo " ") >echotmp
if $contains c echotmp >/dev/null 2>&1 ; then
    n='-n'
    c=''
else
    n=''
    c='\c'
fi

: Here we go...
cat << EOH

Beginning Xtal installation...

This currently running process (sh Install) obtains information about your
system and produces some scripts and a makefile in the current directory -
($curdir).
The scripts all have the subscript ".imp" and should not be deleted, since
they are used later by the "make" utility. The file which contains the
instructions for the make utility is called "Makefile", and also should not
be deleted. A directory called "$SRC" is created, which will be used at a
later stage to hold the source code and object files for Xtal. A script
called "xtal" will also be produced, which can be used to execute the Xtal
suite of programs.

Information as to what to do after the Install script finishes appears in
the Installation section of the Xtal Reference Manual, and is also given at
the end of this script.

EOH
echo $n "[Type carriage return to continue] $c"
read ans

: Eunice requires " " instead of "", can you believe it
echo " "

trap 'echo " "; exit 1' 1 2 3

: We must find out about Eunice early
eunicefix=':'
if test -f /etc/unixtovms; then
    eunicefix=/etc/unixtovms
fi
if test -f /etc/unixtovms.exe; then
    eunicefix=/etc/unixtovms.exe
fi

: Now test for existence of requisite files
echo "First, let's make sure you have everything. Checking..."
rm -f missing
(cd ..; ls `echo $MANIFEST` >/dev/null 2>>UU/missing)
if test -s missing; then
    cat missing
    kill $$
fi
echo "Looks good..."

: See if sh knows # comments
if sh -c '#' >/dev/null 2>&1 ; then
    shsharp=true
    spitshell=cat
    if test -f /bsd43/bin/echo; then
        echo "#!/bsd43/bin/echo hi" > spit.sh
    else
        echo "#!/bin/echo hi" > spit.sh
    fi
    $eunicefix spit.sh
    chmod +x spit.sh
    ./spit.sh > today
    if $contains hi today >/dev/null 2>&1; then
        sharpbang='#!'
    else
        echo "#! /bin/echo hi" > spit.sh
        $eunicefix spit.sh
        chmod +x spit.sh
        ./spit.sh > today
        if test -s today; then
            sharpbang='#! '
        else
            sharpbang=': use '
        fi
    fi
else
    echo "Your sh doesn't understand # comments--I will strip them later on."
    shsharp=false
    echo "exec grep -v '^#'" >spitshell
    chmod +x spitshell
    $eunicefix spitshell
    spitshell=`pwd`/spitshell
    sharpbang=': use '
fi

: Figure out how to guarantee sh startup
echo " "
echo "Checking on how to guarantee sh startup on scripts..."
startsh=$sharpbang'/bin/sh'
cat >start.sh <<EOS
$startsh
set abc
test "$?abc" != 1
EOS
chmod +x start.sh
$eunicefix start.sh
if ./start.sh; then
    echo "Okay..."
else
    cat <<EOM
The scripts that will be generated by running Install use the "sh" syntax
and thus must be run by sh. The standard methods of guaranteeing sh startup
do not seem to work with your version of Unix. You will need to edit the
generated scripts so that they will be run by sh. If you do not know how to
do this, check with your system administrator or local Unix expert.
EOM
fi

: Now set up to do reads with possible shell escape and default assignment
case "$SHELL" in
'')  shl=sh
     ;;
*)   shl=$SHELL
     ;;
esac
cat <<EOS >myread
flag=\$1
ans='!'
while expr "X\$ans" : "X!" >/dev/null; do
    read ans
    case "\$ans" in
    !)
        $shl
        echo " "
        case "\$flag" in
        two_lines) echo "\$rp"
                   echo $n "[\$dflt] $c"
                   ;;
        *)         echo $n "\$rp $c"
                   ;;
        esac
        ;;
    !*)
        set \`expr "X\$ans" : "X!\(.*\)\$"\`
        sh -c "\$*"
        echo " "
        case "\$flag" in
        two_lines) echo "\$rp"
                   echo $n "[\$dflt] $c"
                   ;;
        *)         echo $n "\$rp $c"
                   ;;
        esac
        ;;
    esac
done
rp='Your answer:'
case "\$ans" in
'') ans="\$dflt";;
esac
EOS

: Find out where common programs are
echo " "
echo "Locating Unix system utilities..."
cat <<EOS >loc
$startsh
case \$# in
0) exit 1;;
esac
thing=\$1
shift
dflt=\$1
shift
for dir in \$*; do
    case "\$thing" in
    .)
        if test -d \$dir/\$thing; then
            echo \$dir
            exit 0
        fi
        ;;
    *)
        if test -f \$dir/\$thing; then
            echo \$dir/\$thing
            exit 0
        elif test -f \$dir/\$thing.exe; then
            : on Eunice apparently
            echo \$dir/\$thing
            exit 0
        fi
        ;;
    esac
done
echo \$dflt
exit 1
EOS
chmod +x loc
$eunicefix loc

: Set up list of programs we need to find
loclist="
sh
chmod
grep
cmp
awk
cat
cp
echo
expr
make
mv
rm
sed
tr
"

: These do not matter
trylist="
test
strings
nawk
uname
machine
"

: Path along which to search for programs
boPATH=""
eoPATH="/usr/plx /usr/5bin /vol/local/bin /usr/lib /lib /usr/local/lib
/sys5.3/bin /sys5.3/usr/bin /bsd4.3/bin /bsd4.3/usr/bin /bsd4.3/usr/ucb
/bsd43/usr/bin"
pth=`echo $boPATH:$PATH:$eoPATH: | sed -e 's/:/ /g'`

: Find them
found=true
for file in $loclist; do
    xxx=`./loc $file $file $pth`
    eval $file=$xxx
    case "$xxx" in
    /*)
        ;;
    *)
        found=''
        echo "I don't know where $file is. I hope it's in your PATH."
        ;;
    esac
done
case "$found" in
true)  echo "All necessary utilities found."
       ;;
*)     ;;
esac
: If the following are not found, it does not matter
echo " "
for file in $trylist; do
    xxx=`./loc $file $file $pth`
    eval $file=$xxx
    case "$xxx" in
    /*)
        ;;
    *)
        ;;
    esac
done
: If awk is not found, but nawk is, set awk to nawk
case "$awk" in
'awk')    case "$nawk" in
          *)    awk="$nawk"
                ;;
          esac
          ;;
esac
case "$test" in
test)
: Assume test is built into the shell
    ;;
/bin/test)
    if sh -c "PATH= test true" >/dev/null 2>&1; then
: Use the test built into the shell
        test=test
    fi
    ;;
*)
    test=test
    ;;
esac
case "$echo" in
echo)
: Assume echo is built into the shell
    ;;
/bin/echo)
    $echo $n "hi there$c" >Loc1.txt
    echo $n "hi there$c" >Loc2.txt
    if cmp Loc1.txt Loc2.txt >/dev/null 2>&1; then
: They are compatible, maybe even identical
    else
        case "$n" in
        '-n') n='' c='\c' ans='\c' ;;
        *) n='-n' c='' ans='-n' ;;
        esac
    fi
    ;;
*)
    : cross your fingers
    echo=echo
    ;;
esac

cat <<EOM
This script has been designed to run on all versions of the Unix operating
system. If it fails there are two alternate approaches. Edit this script
("Install") to correct the error and try running it again OR install Xtal
by hand as per the instructions in the Xtal Reference Manual.

In the event of a script failure, please send details of the failure to the
Xtal Coordinator (preferrably by electronic mail to xtal@crystal.uwa.edu.au).

EOM
echo $n "[Type carriage return to continue] $c"
read ans

: Set up shell script to do ~ expansion
cat >filexp <<EOS
$startsh
: expand filename
case "\$1" in
 ~/*|~)
    echo \$1 | $sed "s|~|\${HOME-\$LOGDIR}|"
    ;;
 ~*)
    if $test -f /bin/csh; then
        /bin/csh -f -c "glob \$1"
    else
        name=\`$expr x\$1 : '..\([^/]*\)'\`
        dir=\
\`$sed -n -e \
"/^\${name}:/{s/^[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:\([^:]*\).*"'\$'"/\1/" \
-e p -e q -e '}' </etc/passwd\`
        if $test ! -d "\$dir"; then
            me=\`basename \$0\`
            echo "\$me: can't locate home directory for: \$name" >&2
            exit 1
        fi
        case "\$1" in
        */*)
            echo \$dir/\`$expr x\$1 : '..[^/]*/\(.*\)'\`
            ;;
        *)
            echo \$dir
            ;;
        esac
    fi
    ;;
*)
    echo \$1
    ;;
esac
EOS
chmod +x filexp
$eunicefix filexp

: Determine whether this make supports MAKEFLAGS or MFLAGS
case "$strings" in
    strings) makeflags='$(MFLAGS) -$(MAKEFLAGS)'
             ;;
    *)       $strings $make >make.str 2>/dev/null
             if $contains MFLAGS make.str > /dev/null 2>&1; then
                 makeflags='$(MFLAGS)'
             else if $contains MAKEFLAGS make.str > /dev/null 2>&1; then
                 makeflags='-$(MAKEFLAGS)'
                 fi
             fi
             ;;
esac

: Try to guess what we are up against
if test "$uname" != "uname"; then
  set `$uname -a | $tr '[A-Z]' '[a-z]'`
  case "$1" in
  aix*) mach_type=ibm
        f77=xlf
        optimize='-O'
        gralibs='-lgksco -lgP -lm'
        fflags='-qcharlen=25000'
        ;;
  sun*) mach_type=sun
        f77=f77
        optimize='-O3'
        gralibs='-lgks77 -lgks -lsuntool -lsunwindow -lpixrect -lm'
        fflags='-libmil'
        case "$5" in
        sun4*) fflags="-dalign $fflags"
               ;;
        *)     ;;
        esac
        ;;
  hp*)  mach_type=hp
        f77=f77
        optimize='-O'
        fflags='-K +Obb2500'
        gralibs='-lgks1 -lgks2 -lddsox11 -lgkssb -lsb1 -lsb2 -lXhp11 -lX11 -ll'
        ;;
  irix*)  mach_type=sgi
        f77=f77
        optimize='-O2'
        fflags='-static -nocpp -G 0 -Olimit 2000'
        gralibs=''
        ;;
  ultrix*) mach_type=dec
        f77=f77
        optimize='-O2'
        fflags='-static -nocpp -G 0 -Olimit 2000'
        gralibs='/usr/lib/GKS3D/GKS3Dmotifconfig.o -lGKS3Dmotif -lGKS3Ddforbnd \
-lGKS3D /usr/lib/DXM/lib/Mrm/libMrm.a /usr/lib/DXM/lib/Xm/libXm.a \
/usr/lib/DXM/lib/Xt/libXt.a -lcursesX -li -lc -lX11'
        ;;
  linux*) mach_type=lnx
        f77=f77
        optimize='-O2'
        fflags=' '
        gralibs='-lX11'
        ;;
  *)    ;;
  esac
: If no joy on first arg returned by uname, try fifth
  if test "X$mach_type" = "X"; then
  case "$5" in
  ip[1-9]*) mach_type=sgi
        f77=f77
        optimize='-O2'
        fflags='-static -nocpp -G 0 -Olimit 2000'
        gralibs=''
        ;;
  *)    ;;
  esac
  fi
fi
: Still no joy
if test "X$mach_type" = "X" -a "$machine" != "machine"; then
  set `$machine | $tr '[A-Z]' '[a-z]'`
  case "$1" in
  news*) mach_type=sny
         f77=f77
         optimize='-O2'
         fflags='-static -nocpp -G 0 -Olimit 2000'
         gralibs=''
         ;;
  *)     ;;
  esac
fi

: determine where public executables will go
case "$bin" in
'')
bin=`./loc . /usr/local/bin /usr/local/bin /usr/lbin /usr/local /usr/bin /bin`
    ;;
*)  ;;
esac

: get answers from form, if there is a FORM file out there
form=n
if test -f ../FORM; then
    echo " "
    echo "A FORM file (question/answer form) exists."
    dflt=y
    rp="Do you want the answers to be read from it? [$dflt]"
    echo $n "$rp $c"
    . myread
    case "$ans" in
    n*) echo "OK, existing FORM ignored." ;;
    *)  echo "Fetching answers to questions from your FORM file..."
        form=y
        tmp="$n"
        ans="$c"
        . ../FORM
        case "$mach_type" in
        oth*) mach_type="   ";;
        esac
        case "$bin" in
        .)  bin="$curdir";;
        esac
        gralibs=`echo $gralibs | sed 's/\\\//g' | sed 's/  / /g'`
        n="$tmp"
        c="$ans"
        ;;
    esac
fi

: Did not want to use the form
if test "$form" = "n" ; then
: General instructions
cat <<EOM

The shell script you are currently running will examine your operating system
and ask questions to determine how the Xtal package should be installed.
If you do not know the answer to a question, you may type "!" to generate a
shell in which you can run normal Unix commands. To leave the generated shell
and come back to this script (at the same place as you left it), type "exit"
(if the shell is a csh) or CONTROL-D (if the shell is a sh (Bourne shell)).
If you type "!command", the Unix command will be run, the results displayed,
and the question prompt re-displayed. For example, you may type "!man f77" to
look up the options for the Fortran compiler.

Note that some questions have a default answer, given in square braces ([]).
Typing carriage return will enter the default answer. The defaults are
adjusted where possible to suit your operating system, but do not assume that
they will necessarily be correct for your installation.

If you prefer not to answer the installation questions interactively, a form
"FORM" will be generated for you to fill in at your leisure. When you have
filled out this form, type "sh Install" again and answer "yes" to the
question about using FORM. The answers from this form will then replace
the interactive question/answer session.

EOM
dflt=y
rp="Do you want a form to be generated? [$dflt]"
echo $n "$rp $c"
. myread
case $ans in
n*)     echo " "
        echo "Interactive questions it is, then."
        echo " "
        ;;
*)      echo " "
        echo "The name of the form will be FORM."
        cat >FORM <<EOF
$startsh
: Please fill this in and then re-type "sh Install".
: Lines in this form beginning with ":" are comment lines.
: Your answers must be enclosed in single quotes - e.g.
: question='answer'
: Some questions already have possible answers filled in. Please check to see
: if they are correct.

: Xtal supports the following Unix compiler types:
:
:       sun - Sun - Sun3, Sun4 or SPARC versions
:       sny - Sony NEWS
:       dec - DEC running Ultrix
:       ibm - IBM RISC RS6000
:       cra - Cray running Unicos
:       sgi - Silicon Graphics
:       hp  - Hewlett Packard running HP-UX
:       lnx - IBM PC running Linux
:       oth - Other

: What is your Fortran compiler type?

: =========
mach_type='$mach_type'
: =========

: What is the command - f77, fc, xlf - for the Fortran compiler?

: ===
f77='$f77'
: ===

: Fortran compilers usually provide different levels of optimization. By
: default, Xtal will be compiled using the "-O" level optimizer. If you want
: to use a different level it must be specified here. To use no optimization
: flags, answer "optimize=''".

: What optimizer flag should be used?

: ========
optimize='$optimize'
: ========

: Compilers which do not automatically retain the values of local variables in
: a subroutine provide a compile-time flag to force this action. The flag
: varies from compiler to compiler, and may be, for example, "-save" or
: "-static". A number of the Xtal routines require local variables to be saved.
: If your compiler has such a flag, specify it here, together with any other
: needed compiler flags apart from the optimizer flag. Your answer should
: NOT include flags concerning object libraries or the linking process, such
: as "-lm" or "-Bstatic". If there are no flags, answer "fflags=''".

: What other flags does the compiler need?

: ======
fflags='$fflags'
: ======

: Following the compilation of the Xtal routines, the object files will be
: "linked" or "loaded" together to form a single executable file. Often the
: linking/loading process requires specific options to be entered as flags.
: Enter those here. Do not specify the libraries needed by the linker. If
: there are no loader options to be specified, answer "ldflags=''".

: Additional linker flags, NOT including libraries?

: =======
ldflags='$ldflags'
: =======

: The Xtal routines PIG, PREVUE and PLOTX require either the GKS package or X11. 
: If you want to install PIG or PREVUE access to these libraries is essential.
: PLOTX can be used for some operations without GKS or X11, but for most 
: workstation screen activities GKS or X11 will be needed.

: If these routines are to be installed extra graphics libraries will need to
: specified for the linker process. Enter the filenames of the GKS or X11 
: libraries and of any other libraries that GKS depends upon. If you do 
: not intend to make use of GKS, answer "gralibs=''". If your answer has 
: to extend over more than one line, put a '\' as the last character on 
: the lines to be continued, e.g.
: gralibs='first_library second_library \\
:          third_library \\
:          final_library'
: Do not forget the final closing quotation mark.

: Which libraries are required for GKS or X11?

: =======
gralibs='$gralibs'
: =======

: Some Unix systems support "shared" libraries. Use of this facility results in
: a much smaller Xtal executable at a small cost in load-time speed. Some
: System V linkers will use shared libraries if "-lc_s" is entered as the final
: option. Other systems may use shared libraries as the default. Enter any
: explicit shared library options here. Enter any "special" library options
: here as well. If no extra libraries are required answer "addlibs=''".

: Any additional libraries?

: ======
addlibs=''
: ======

: Xtal uses a variety of supplied database files such as the error message
: file "xerror" and the CIFIO files "cifmap" and "cifreq", which need to be
: placed in a directory that is accessible by all users. This question has to
: do with which directory these files should be placed in.
: In addition, after you have run the test files and made sure that Xtal works
: correctly, the final installation step will result in the Xtal executable and
: the executable script for running Xtal being copied to the directory you
: designate here. Answer "bin='.'" if all of these files are to reside in the
: current directory, $curdir.
: If the directory you designate does not currently exist, you will have to
: create it using "mkdir" before the next stage of the installation process.

: Where will the publically accessible Xtal files and executables reside?

: ===
bin='$bin'
: ===

: The default QX array size for Xtal is 250000 words. This is usually
: adequate for small molecule calculations. If you plan to do macromolecular
: calculations, the suggested size is 1000000 words.

: Enter the QX array size in words for this installation.

: ======
memory='$memory'
: ======

: End of form
EOF
chmod +x FORM
$eunicefix FORM
mv FORM ..
exit
        ;;
esac

cat <<EOM

For some of the questions which ask for file or directory names, the "~name"
construct may be used to specify the login directory belonging to "name",
even if the shell you generally use does not accept "~name". This construct
is a form of shorthand. For example, ~mark may expand to /home/hewl/mark.
Questions which allow this type of entry will be indicated by the phrase
"(~name ok)".

If you make a mistake in entering an answer (i.e. the mistake is realized
after you have typed the carriage return) the Install script must be re-
started. To do this, enter the shell interrupt character (usually CONTROL-C,
but may be "#" or "@" on some systems) and re-enter "sh Install".

EOM
echo $n "[Type carriage return to continue] $c"
read ans

qno=0
qno=`expr $qno + 1`
cat <<EOQ

========== QUESTION $qno ==========

Xtal supports the following Unix compiler types:

        sun - Sun (Sun3, Sun4 or SPARC versions)
        sny - Sony NEWS
        dec - DEC running Ultrix
        ibm - IBM RISC (RS6000 versions)
        cra - Cray running Unicos
        sgi - Silicon Graphics
        hp  - Hewlett Packard running HP-UX
        lnx - IBM Compatible PC running Linux
        oth - Other

EOQ

case "$mach_type" in
'')    dflt=''
       rrp="What is your Fortran compiler type?"
       ;;
*)     dflt="$mach_type"
       rrp="What is your Fortran compiler type? [$dflt]"
       ;;
esac
cont=true
while $test "$cont" ; do
rp="$rrp"
echo $n "$rp $c"
. myread
case "$ans" in
oth*)                       mach_type='   '
                            cont=''
                            ;;
sun|sny|dec|ibm|cra|sgi|hp|lnx) mach_type=$ans
                            cont=''
                            ;;
*)                          ;;
esac
done

qno=`expr $qno + 1`
cat <<EOQ

========== QUESTION $qno ==========

EOQ
case "$f77" in
'')    dflt=''
       rp="What is the command (f77, fc, xlf) for the Fortran compiler?"
       ;;
*)     dflt=$f77
       rp="What is the command (f77, fc, xlf) for the compiler? [$dflt]"
       ;;
esac
echo $n "$rp $c"
. myread
f77=$ans

: Determine the optimize flag, if desired, or use for debug flag also
qno=`expr $qno + 1`
cat <<EOQ

========== QUESTION $qno ==========

Fortran compilers usually provide different levels of optimization. By
default, Xtal will be compiled using the "-O" level optimizer. If you want
to use a different level it must be specified here. To use no optimization
flags, enter "none".

EOQ
case "$optimize" in
'') dflt="-O"
    ;;
*)  dflt="$optimize"
    ;;
esac
rp="What optimizer flag should be used? [$dflt]"
$echo $n "$rp $c"
. myread
optimize="$ans"
case "$optimize" in
'none') optimize=''
     ;;
esac

qno=`expr $qno + 1`
cat <<EOQ

========== QUESTION $qno ==========

Compilers which do not automatically retain the values of local variables in
a subroutine provide a compile-time flag to force this action. The flag varies
from compiler to compiler, and may be, for example, "-save" or "-static". A
number of the Xtal routines require local variables to be saved. If your
compiler has such a flag, specify it here, together with any other needed
compiler flags (apart from the optimizer flag). Your answer should NOT include
flags concerning object libraries or the linking process, such as "-lm" or
"-Bstatic". If there are no flags, specify the word "none".

EOQ
case "$fflags" in
'')    dflt='none'
       ;;
*)     dflt="$fflags"
       ;;
esac
rp="What other flags does the compiler need?"
echo "$rp"
echo $n "[$dflt] $c"
set `echo "two_lines"`
. myread
case "$ans" in
none) ans='';
esac
fflags=$ans

qno=`expr $qno + 1`
cat <<EOQ

========== QUESTION $qno ==========

Following the compilation of the Xtal routines, the object files will be
"linked" or "loaded" together to form a single executable file. Often the
linking/loading process requires specific options to be entered as flags.
Enter those here. Do not specify the libraries needed by the linker. If
there are no loader options to be specified, enter "none".

EOQ
case "$ldflags" in
'') dflt="none"
    ;;
*)  dflt="$ldflags"
    ;;
esac
    rp="Additional linker flags (NOT including libraries)? [$dflt]"
$echo $n "$rp $c"
. myread
case "$ans" in
none) ans='';
esac
ldflags="$ans"

qno=`expr $qno + 1`
cat <<EOQ

========== QUESTION $qno ==========


Xtal contains two routines, PIG and PLOTX, that use the GKS package or X11. 
If you want to install PIG then access to these libraries is essential.
PLOTX can be used for some operations without GKS or X11, but for most 
workstation screen activities GKS or X11 will be needed.

If PIG or PLOTX are to be installed extra graphics libraries will need to
specified for the linker process. Enter the filenames of the GKS or X11 
libraries and of any other libraries that GKS or X11 depend upon. If you do 
not intend to make use of GKS/X11, enter "none"

EOQ

dflt=''
rp="Which libraries are required for GKS or X11?"
case "$gralibs" in
'') dflt=''
    echo $n "$rp $c"
    ;;
*)  dflt=`echo $gralibs | sed 's/\\\//g' | sed 's/  / /g'`
    echo "$rp"
    echo $n "[$dflt] $c"
    ;;
esac
set `echo "two_lines"`
. myread
case "$ans" in
    none) ans='';;
esac
gralibs=$ans

qno=`expr $qno + 1`
$cat <<EOM

========== QUESTION $qno ==========

Some Unix systems support "shared" libraries. Use of this facility results in
a much smaller Xtal executable at a small cost in load-time speed. Some System
V linkers will use shared libraries if "-lc_s" is entered as the final option.
Other systems may use shared libraries as the default. Enter any explicit
shared library options here. Enter any "special" library options here as well.
If no extra libraries are required enter "none".

EOM
case "$addlibs" in
'') dflt='none'
    ;;
*)  dflt="$addlibs"
    ;;
esac
    rp="Any additional libraries? [$dflt]"
$echo $n "$rp $c"
. myread
case "$ans" in
none) ans='';
esac
addlibs="$ans"

: determine where public executables go
case "$bin" in
'')
dflt=`./loc . /usr/local/bin /usr/lbin /usr/local /usr/bin /bin`
    ;;
*)  dflt="$bin"
    ;;
esac
qno=`expr $qno + 1`
cat <<EOQ

========== QUESTION $qno ==========

Xtal uses a variety of supplied database files (such as the error message file
"xerror" and the CIFIO files "cifmap" and "cifreq") which need to be placed
in a directory that is accessible by all users. This question has to do with
which directory these files should be placed in.
In addition, after you have run the test files and made sure that Xtal works
correctly, the final installation step will result in the Xtal executable and
the executable script for running Xtal being copied to the directory you
designate here. Enter a period "." if all of these files are to reside in the
current directory ($curdir).
If the directory you designate does not currently exist, you will have to
create it (using "mkdir ...") before the next stage of the installation
process.
(~name ok)

EOQ

srp="Where will the publically accessible Xtal files and executables reside?"
cont=true
while $test "$cont" ; do
    rp="$srp"
    $echo "$rp"
    $echo $n "[$dflt] $c"
set `echo "two_lines"`
    . myread
    case "$ans" in
        .) ans="$curdir";;
    esac
    bin="$ans"
    bin=`./filexp $bin`
    if test -d $bin; then
        cont=''
    else
        sdflt="$dflt"
        dflt=n
        rp="Directory $bin doesn't exist. Use that name anyway? [$dflt]"
        $echo $n "$rp $c"
set `echo "two_lines"`
        . myread
        dflt="$sdflt"
        case "$ans" in
        y*) cont='';;
        *)  echo " ";;
        esac
    fi
done

qno=`expr $qno + 1`
$cat <<EOQ

========== QUESTION $qno ==========

The default QX array size for Xtal is 250000 words. This is usually
adequate for small molecule calculations. If you plan to do macromolecular
calculations, the suggested size is 1000000 words.

EOQ
dflt="250000"
rp="Enter the QX array size (in words) for this installation. [$dflt]"
$echo $n "$rp $c"
. myread
memory="$ans"

cat <<EOQ

================
End of questions
================
EOQ
fi
cat <<EOM

All the requisite information has been obtained. The scripts and makefiles
needed to install the Xtal package will now be generated.

When this is complete, do the following:

(i)   Edit the supplied file XTAB to specify which programs and data files
      will be needed for the installation of Xtal at your site. Make sure
      that the unix RFP preprocessor is selected (normally "rfpunx.f").

(ii)  Enter the command "make select". This extracts all of the selected files
      from the Xtal library file XLIB. If these include the programs PIG
      and PLOTX, you will need to make some changes to these source files
      so that they are appropriate to the local plot and workstation types.
      See the Reference Manual for details.

(iii) Enter the command "make xtal". This should produce the executable file
      "xtal.x" in the current directory. It will also place the Xtal database
      files into the publically accessible directory specified in answer to
      a question above ($bin).
      NOTE: You must have sufficient system privileges to be able to write in
      this directory, or the "make xtal" step will fail.

EOM
echo $n "[Type carriage return to continue] $c"
read ans

cat <<EOM

(iv)  Execute selected test files by entering the command "xtal filename",
      where "filename" is the name preceding the ".d" of the test data files.
      Note that execution of the test file "exampl.d" includes test of the
      programs PIG and PLOTX. Edit these out if they are not installed.

(v)   If you decide at any point to add more routines, go back to (i).

(vi)  If you decide at any point to change the compiler options, either re-run
      this script (re-enter "sh Install") or edit the file "Makefile". It is
      also possible to edit XMACRO or any other file in the $SRC directory.
      If you do this, make sure that you return to the present directory
      before entering "make xtal" to rebuild the Xtal executable "xtal.x".

(vii) Finally, when you are confident that the test decks run correctly, enter
      the command "make public". This will place the Xtal executable "xtal.x"
      into the publically accessible area you specified in answer to a
      question above ($bin).
      NOTE: You must have sufficient system privileges to be able to write in
      this directory, or the "make public" step will fail.

EOM

file=$bin/Install.$$
touch $file >/dev/null 2>&1
if test  -f $file; then
    rm $file
else
    cat <<EOM

WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
You do not have write access to $bin.
You need to be able to write to this directory for the next stage in the
Xtal installation process.
WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING

EOM
fi

: Set up script to extract list of routines from XTAB
cat >extr_XTAB.imp <<EOS
$startsh
$awk  ' BEGIN {
del="."}
/^<yes>/ {
split(\$2,arr,del)
if ( arr[1] ~ /[a-z][a-z]/ && length(arr[1]) == 2) {
print arr[1]}
}' XTAB
EOS
chmod +x extr_XTAB.imp
$eunicefix extr_XTAB.imp
mv extr_XTAB.imp ..

: Set up script to edit XMACRO
cat >do_XMACRO.imp <<EOS
$startsh
$mv $SRC/XMACRO $SRC/XMACRO.\$\$
$awk 'BEGIN { FS = "("
colon = ":"
quote = "'"'"'"
slash = "/"
machine = "compiler"
memory = "memmax"
files["errfile"] = 1
files["profile"] = 2
files["prodict"] = 3
files["prorest"] = 4
files["cifmapp"] = 5
files["cifrequ"] = 6
}
/^macro:/ {
split(\$2,macro,colon)
if ( macro[1] == machine ) {
    print "macro:("machine":,UNX"COMP")#"
    next
}
if ( macro[1] == memory ) {
    print "macro:("memory":,"MEM")#"
    next
}
for ( element in files ) {
    if (macro[1] == element ) {
        split(\$0,array,quote)
        num = split(array[2],temp,slash)
        if ( num > 0 ) filename = temp[num]
        else           filename = array[2]
        print array[1] quote DIR slash filename quote array[3]
        next
    }
}
}
{ print \$0 }
    ' DIR=$bin MEM=$memory COMP=$mach_type $SRC/XMACRO.\$\$ > $SRC/XMACRO
$cmp $SRC/XMACRO $SRC/XMACRO.\$\$ > /dev/null 2>&1
if $test \$? -ne 0 ; then
    $rm $SRC/XMACRO.\$\$
else
    $mv $SRC/XMACRO.\$\$ $SRC/XMACRO
fi
EOS
chmod +x do_XMACRO.imp
$eunicefix do_XMACRO.imp
mv do_XMACRO.imp ..

: Set up script to edit aa
cat >edit_aa.imp <<EOS
$startsh
$cat >edit_aa.aw <<'EOA'
BEGIN {
FS=":"
EOA
./extr_XTAB.imp | $grep -v aa > junk.\$\$
./edit_aa_hp.imp < junk.\$\$ >> edit_aa.aw
$rm junk.\$\$
$cat >>edit_aa.aw <<'EOA'
}
{
if ( \$1 == "xxxx" || \$1 == "call" ) {
    MOD=substr(\$0,7,2)
    found="no"
    for ( WANT in name ) {
        if ( MOD == WANT ) {
            found="yes"
            print "call:"\$2
        }
    }
    if ( found == "no" ) {
        print "xxxx:"\$2
    }
}
else {
    print \$0
}
}
EOA
$mv $SRC/aa.r $SRC/aa.r.\$\$
$awk -f edit_aa.aw $SRC/aa.r.\$\$ > $SRC/aa.r
$rm edit_aa.aw
$cmp $SRC/aa.r $SRC/aa.r.\$\$ > /dev/null 2>&1
if $test \$? -ne 0 ; then
    $rm $SRC/aa.r.\$\$
else
    $mv $SRC/aa.r.\$\$ $SRC/aa.r
fi
EOS
chmod +x edit_aa.imp
$eunicefix edit_aa.imp
mv edit_aa.imp ..
$cat >edit_aa_hp.imp <<EOS
$startsh
i=0
while read module
do
MODULE=\`echo \$module | $tr '[a-z]' '[A-Z]'\`
i=\`$expr \$i + 1\`
$echo name['"'\$MODULE'"'] = \$i
done
EOS
chmod +x edit_aa_hp.imp
$eunicefix edit_aa_hp.imp
mv edit_aa_hp.imp ..

: Set up script to produce src/Makefile from aa.r
cat >make_mf.imp <<EOS
$startsh
if $test -f xtal.x; then
    $rm xtal.x
fi
$cat > $SRC/Makefile <<'EOM'
SHELL = $sh
OBJECTS = \\
EOM
$cat >extr_aa_aw << 'EOA'
BEGIN {
FS="("
del=","
}
/^call:/ {
split(\$2,arr,del)
print "\t"arr[1]".o \\\\"
}
EOA
$awk -f extr_aa_aw $SRC/aa.r | $tr '[A-Z]' '[a-z]' >> $SRC/Makefile
$rm extr_aa_aw
EOS
case "$mach_type" in
    hp|ibm) cat >>make_mf.imp <<EOS
$cat >> $SRC/Makefile <<'EOM'
	aa.o datim.o
EOM
EOS
            ;;
        lnx) cat >>make_mf.imp <<EOS
$cat >> $SRC/Makefile <<'EOM'
        aa.o datim.o bitws.o x11lib.o
EOM
EOS
            ;;
         *) cat >>make_mf.imp <<EOS
$cat >> $SRC/Makefile <<'EOM'
	aa.o
EOM
EOS
        ;;
esac
cat >>make_mf.imp <<EOS
$cat >>$SRC/Makefile <<'EOM'

.SUFFIXES:
.SUFFIXES: .o .r .c

.c.o:
	@\$(CC) \$(CFLAGS) -c \$<
.r.o:
	@\$(CP) \$< RFPRAT
	@\$(RAT)
	@\$(MV) RFPFTN RFPFTN.f
	\$(F77) \$(FFLAGS) -c RFPFTN.f
	@\$(MV) RFPFTN.o \$@
	@\$(RM) RFPFTN.f *COMN

xtal:	\$(XTAL_EXEC)

\$(XTAL_EXEC):	\$(OBJECTS)
		\$(LINK) \$(LDFLAGS) -o \$@ \$(OBJECTS) \$(LIBS)

\$(OBJECTS):	\$(MACROS)

clean:
	\$(RM) \$(OBJECTS)

EOM
EOS
case "$mach_type" in
    hp|ibm) cat >>make_mf.imp <<EOS
$cat >> $SRC/Makefile <<'EOM'
datim.o:	datim.c

datim.c:	aa.r
		@\$(CP) aa.r RFPRAT
		@\$(RAT) >/dev/null 2>&1
		@\$(RM) RFPFTN

EOM
EOS
            ;;
    lnx) cat >>make_mf.imp <<EOS
$cat >> $SRC/Makefile <<'EOM'
datim.o:	datim.c
bitws.o:	bitws.c

datim.c:	aa.r
		@\$(CP) aa.r RFPRAT
		@\$(RAT) >/dev/null 2>&1
		@\$(RM) RFPFTN

EOM
EOS
            ;;
esac
chmod +x make_mf.imp
$eunicefix make_mf.imp
$mv make_mf.imp ..

: Set up main makefile
cat >Makefile <<EOM
SHELL = $sh
CP = $cp
MV = $mv
RM = $rm -f
CHMOD = $chmod
F77 = $f77
FFLAGS = $fflags $optimize
MACROS = XMACRO
LINK = $f77
MAKE = $make
LDFLAGS = $ldflags
LIBS = $gralibs $addlibs
RAT = rfp.x
XTAL_EXEC = xtal.x
XTAL_SCRIPT = xtal
ECHO = $echo
AUXFILES = \\
	xerror \\
	profdb \\
	prodic \\
	prores \\
	cifmap \\
	cifreq
MY_MFLAGS = \\
	XTAL_EXEC="../\$(XTAL_EXEC)" \\
	ECHO="\$(ECHO)" \\
	CP="\$(CP)" \\
	RAT="../\$(RAT)" \\
	MV="\$(MV)" \\
	F77="\$(F77)" \\
	FFLAGS="\$(FFLAGS)" \\
	RM="\$(RM)" \\
	LINK="\$(LINK)" \\
	LDFLAGS="\$(LDFLAGS)" \\
	LIBS="\$(LIBS)" \\
	MACROS="\$(MACROS)"

xtal:		select dummy1.imp \$(AUXFILES) rfp.x
		@cd $SRC; \$(MAKE) $makeflags \$(MY_MFLAGS) \$@

select:		XTAB $SRC/xsel.x
		@cd $SRC; ./xsel.x
		@\$(CP) $SRC/*.d .
		@\$(CP) $SRC/*.l .
		@./do_XMACRO.imp
		@./edit_aa.imp
		@touch select

dummy1.imp:	$SRC/aa.r
		@./make_mf.imp
		@touch dummy1.imp

\$(AUXFILES):
		@if $test -f $SRC/\$@ ; then \$(CP) $SRC/\$@ $bin ; \\
		\$(CHMOD) 666 $bin/\$@ ; else $echo "no" >/dev/null ; fi

$SRC/xsel.x:	xsel.f
		@$sed '/OPEN/s#XTAB#../XTAB#' xsel.f | \\
$sed '/OPEN/s#XLIB#../XLIB#' > xseltmp.f
		@\$(F77) \$(FFLAGS) -o \$@ xseltmp.f
		@$(RM) xseltmp.f

rfp.x:		$SRC/rfpunx.f
		@\$(F77) \$(FFLAGS) -o \$@ $SRC/rfpunx.f

clean:
		cd $SRC; \$(MAKE) $makeflags \$(MY_MFLAGS) \$@

public:		xtal
EOM

case "$bin" in
"$curdir") ;;
*)         cat >>Makefile <<EOM
		\$(CP) \$(XTAL_EXEC) $bin
		@\$(CHMOD) 755 $bin/\$(XTAL_EXEC)
		\$(CP) \$(XTAL_SCRIPT) $bin
		@\$(CHMOD) 755 $bin/\$(XTAL_SCRIPT)

EOM
           ;;
esac
$mv Makefile ..

: Set up script to run Xtal
cat > xtal <<EOS
$startsh
xtal.x < \$1.d > \$1.lst
EOS
chmod +x xtal
$eunicefix xtal
mv xtal ..

cd ..
$rm -rf UU

: end of Install
