#!/bin/sh
version="Time-stamp: <2005-10-13 14:33:46 vonrhein>"
#
# Author: Clemens Vonrhein <vonrhein@GlobalPhasing.com>
#
#----------------------------------------------------------------------
#              BEGIN OF USER INPUT
#----------------------------------------------------------------------

#
# some info about the CCP4 versions this script is intended for
#
CCP4_versions="5.0.2 5.0.1 5.0 4.2.2 4.2.1 4.2"
CCP4_tarfiles="ccp4-5.0.2.tar.gz ccp4-5.0.1.tar.gz ccp4-5.0.tar.gz ccp4-4.2.2.tar.gz ccp4-4.2.1.tar.gz ccp4-4.2.tar.gz"
CCP4_md5sums="7888f73c0e92bc684f9da8bd75413e64 c2087efdd9c30ccfd39ac5e60d1fdfde 0a0c9950ed5ed0670387773c26a4cab6 5494bd30c02be678aa28e9d82f739e9d a2db4475b363274845a63b47acca1f73 3b3b9aa8fb4b8d42d05238c73992bad8"
CCP4_cksums="54010762 53991494 53865857 37071902 37054357 36840531"
CCP4_ftps="ftp://ftp.ccp4.ac.uk/ccp4/5.0.2/packed ftp://ftp.ccp4.ac.uk/ccp4/5.0.1/packed ftp://ftp.ccp4.ac.uk/ccp4/5.0/packed ftp://ftp.ccp4.ac.uk/ccp4/4.2.2/packed ftp://ftp.ccp4.ac.uk/ccp4/4.2.1/packed ftp://ftp.ccp4.ac.uk/ccp4/4.2/packed"
CCP4_http="http://www.ccp4.ac.uk"

#
# info for getting patches and files for the latest -cvX version
#
CV_http="http://www.globalphasing.com/people/vonrhein/ccp4"
CV_files="files-5.0.2.list files-5.0.1.list files-5.0.list files-4.2.2.list files-4.2.1.list files-4.2.list"

#
# info for BLT, Tcl and Tk
#
BLT_file="http://prdownloads.sourceforge.net/blt/BLT2.4y.tar.gz"
 BLT_dir="blt2.4y"
BLT_file="http://prdownloads.sourceforge.net/blt/BLT2.4z.tar.gz"
 BLT_dir="blt2.4z"

# maybe this works:
#BLT_file="http://gd.tuwien.ac.at/opsys/linux/sf/b/blt/BLT2.4y.tar.gz"
# BLT_dir="blt2.4y"
BLT_file="http://www.mirror.ac.uk/mirror/www.ibiblio.org/distfiles/BLT2.4z.tar.gz"
 BLT_dir="blt2.4z"
BLT_file="http://www.mirror.ac.uk/mirror/distro.ibiblio.org/pub/linux/distributions/gentoo/distfiles/BLT2.4z.tar.gz"
 BLT_dir="blt2.4z"

# this seems to be gone:
TCL_file="ftp://www.mirror.ac.uk/sites/ftp.scriptics.com/pub/tcl/tcl8_3/tcl8.3.4.tar.gz"
 TCL_dir="tcl8.3.4/unix"
 TK_file="ftp://www.mirror.ac.uk/sites/ftp.scriptics.com/pub/tcl/tcl8_3/tk8.3.4.tar.gz"
  TK_dir="tk8.3.4/unix"

# try this instead
TCL_file="http://programming.ccp14.ac.uk/ftp-mirror/programming/tcltk/pub/tcl/tcl8_4/tcl8.4.6-src.tar.gz"
 TCL_dir="tcl8.4.6/unix"
 TK_file="http://programming.ccp14.ac.uk/ftp-mirror/programming/tcltk/pub/tcl/tcl8_4/tk8.4.6-src.tar.gz"
  TK_dir="tk8.4.6/unix"

#
# to add new systems: search for string 'SYSTEM DEPENDENT' in this
#                     script. On top of that: a file
#
#                       ccp4-${CCP4_version/.cv/setup.$CSYSTEM
#
#                     is needed.
#
#----------------------------------------------------------------------
#               END OF USER INPUT
#----------------------------------------------------------------------

myself=`basename $0`
linesave=" ------------------------------------------------------------------------------ "
delim="##############################################################################"
line=$linesave
inote=0
iwarn=0
isec=0

em1=""
em2=""
em3=0
ul1=""
ul2=""
ul3=0
emul3=0
re1=""
re2=""
re3=0

type tput >/dev/null 2>&1
if [ $? -eq 0 ]; then
  tput -T vt100 longname >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    TERM=vt100
    export TERM

    em1=`tput bold`
    em2=`tput rmso`
    em3=7

    ul1=`tput smul`
    ul2=`tput rmul`
    ul3=7

    emul3=14

    re1=`tput smso`
    re2=`tput rmso`
    re3=7
  fi
fi

echo " " >&2
ShortVersion=`echo $version | cut -f2- -d':'`
echo " ${em1}`basename $0`   version ${ShortVersion} " >&2
echo " Clemens Vonrhein <vonrhein@GlobalPhasing.com>" >&2
echo " " >&2
echo " (C) Copyright 2002-2004 by Clemens Vonrhein   and" >&2
echo "                         Global Phasing Ltd." >&2
echo " " >&2
echo " Please make sure to always use the latest version of this script from" >&2
echo " " >&2
echo "   ${ul1}http://www.globalphasing.com/people/vonrhein/ccp4/${ul2} " >&2
echo " " >&2
echo " ${em2} " >&2

#----------------------------------------------------------------------
#               BEGIN OF SCRIPT
#----------------------------------------------------------------------

case `uname` in
  AIX) 
    myechon () {
      echo "$@\\c"
    }
    myunamem () {
      uname -p
    }
    ;;
  *)
    myechon () {
      echo -n "$@"
    }
    myunamem () {
      uname -m
    }
    ;;
esac
case `uname` in
  IRIX*) BDG_testl="l";;
      *) BDG_testl="L";;
esac

mkspace () {
  mkspace_tmp=""
  if [ $# -eq 1 ]; then
    imkspace=1
    while [ $imkspace -le $1 ]
    do
      mkspace_ws="${mkspace_ws} "
      imkspace=`expr $imkspace + 1`
    done
  fi
  echo "${mkspace_ws}"
}
askcontinue () {
  myechon " `mkspace $@`Continue [${re1}y${re2}]/n ? "
  read m
  [ "X$m" = "Xn" ] && error "terminating due to user request"
  echo " "
}
error () {
  echo " "
  echo "${em1}$line${em2} "
  line=$linesave
  message -$emul3 "${em1}${ul1}ERROR       :${ul2}${em2} " "$@"
  message "              " "---> Please fix this before re-running this script <---" \
          " " "Additional information might be available at:" " " \
          "${ul1}http://www.globalphasing.com/people/vonrhein/${ul2} " " " \
          "  - or - " " " \
          "${ul1}${CCP4_http}${ul2} "
  summary
  exit 1
}
warning () {
  iwarn=`expr $iwarn + 1`
  iwarntmp=`echo $iwarn | awk '{printf("%3.3d",$1)}'`
  message -$emul3 "${em1}${ul1}WARNING $iwarntmp :${ul2}${em2} " "$@"
  [ $force -eq 0 ] && askcontinue 14
}
note () {
  inote=`expr $inote + 1`
  inotetmp=`echo $inote | awk '{printf("%3.3d",$1)}'`
  echo "$line"
  line=$linesave
  message -$ul3 "${ul1}NOTE    $inotetmp :${ul2} " "$@"
}
message () {
  echo " "
  message_ws=""
  if [ $# -gt 1 ]; then
    case $1 in
      -[1-9]*) i=$1;shift;;
       *) i=0;;
    esac
    message_tmp=`echo "$1" | awk -v i=$i '{print length($0)+i}'`
    message_ws="`mkspace $message_tmp`"
    if [ $# -ge 2 ]; then
      echo " ${1}${2}"
      shift;shift
    else
      echo " ${1}"
      shift
    fi
  fi

  for message_tmp in "$@"
  do
    echo " ${message_ws}${message_tmp}"
  done
  echo " "
}
chkfile () {
  for file in $@
  do
    [ ! -f $file ] && error "file ${ul1}$file${ul2} not found"
  done
}
chkdir () {
  for dir in $@
  do
    [ ! -d $dir ] && error "directory ${ul1}$dir${ul2} not found"
  done
}
chkexe () {
  for exe in $@
  do
    type $exe > /dev/null 2>&1
    error_chk $? "executable $exe not found in path"
  done
}
chklink () {
  for link in $@
  do
    [ -$BDG_testl $link ] && [ ! -f $link ] && [ ! -d $link ] && error "link ${ul1}$link${ul2} doesn't point to file/directory"
    [ ! -$BDG_testl $link ] && error "link ${ul1}$link${ul2} is not a link"
  done
}
summary () {
  if [ $iwarn -gt 0 ]; then
    echo "${em1}$line${em2} "
    line=$linesave
    message -$em3 "${em1}SUMMARY     :${em2} a total of ${em1}$iwarn${em2} warnings were given"
  fi
}
get_file () {
  get_file_force=0
  case $1 in
    -f) shift;get_file_force=1;;
  esac
  for url in $@
  do
    if [ "X`hostname -d 2>/dev/null | tr '[A-Z]' '[a-z]'`" = "Xglobalphasing.com" ] && \
      [ -f /home/vonrhein/Docs/personal/ccp4-5.0.new/`basename $url` ]; then
      cp /home/vonrhein/Docs/personal/ccp4-5.0.new/`basename $url` .
    else
      get_ftpfile_type=`echo $url | cut -f1 -d':'`
      iget_ftpfile=1
      if [ $iget_ftpfile -eq 1 ] && [ "X$get_ftpfile_type" = "Xftp" ] && [ "X$try_ncftpget" = "Xyes" ]; then
        type ncftpget >/dev/null 2>&1
        if [ $? -eq 0 ]; then
          file=`basename $url`
          if [ ! -f $file ] || [ $get_file_force -eq 1 ]; then
            [ $get_file_force -eq 1 ] && rm -f $file
            ncftpget -t 6000 $url > $log 2>&1
            error_chk $? "during \"ncftpget -t 6000 $url\""
            iget_ftpfile=0
          fi
        fi
      fi
      if [ $iget_ftpfile -eq 1 ]; then
        type wget >/dev/null 2>&1
        if [ $? -eq 0 ]; then
          file=`basename $url`
          if [ ! -f $file ] || [ $get_file_force -eq 1 ]; then
            [ $get_file_force -eq 1 ] && rm -f $file
            wget_proxy_arg=""
            case $url in
              http*) wget_proxy_arg=$wget_http_proxy_arg;;
              ftp*) wget_proxy_arg=$wget_ftp_proxy_arg;;
            esac
            wget --timeout=6000 --cache=off $wget_proxy_arg $url > $log 2>&1
            error_chk $? "during \"wget --timeout=6000 $url\""
            iget_ftpfile=0
          fi
        fi
      fi
      if [ $iget_ftpfile -eq 1 ]; then
        type lynx >/dev/null 2>&1
        if [ $? -eq 0 ]; then
          file=`basename $url`
          if [ ! -f $file ] || [ $get_file_force -eq 1 ]; then
            [ $get_file_force -eq 1 ] && rm -f $file
            lynx_proxy_arg=""
            case $url in
              http*) lynx_proxy_arg=$lynx_http_proxy_arg;;
              ftp*) lynx_proxy_arg=$lynx_ftp_proxy_arg;;
            esac
            lynx -reload $lynx_proxy_arg -source $url > $file 2> $log
            error_chk $? "during \"lynx -source $url\""
            iget_ftpfile=0
          fi
        fi
      fi
      if [ $iget_ftpfile -eq 1 ] && [ "X$get_ftpfile_type" = "Xftp" ]; then
        host=`echo $url | cut -f3 -d'/'`
        file=`basename $url`
        dir=`echo $url | sed "s/ftp:\/\/$host\///g" | sed "s/\/${file}$//g"`
        ftp -i -n <<end_ip > $log 2>&1
open $host
user anonymous `whoami`$`hostname -s``domainname`
cd $dir
get $file
close
quit
end_ip
        error_chk $? "during \"ftp -i -n\""
        iget_ftpfile=0
      fi
    fi
  done
}
error_chk () {
  if [ $1 -ne 0 ]; then
    shift
    if [ "X$log" != "X" ] && [ -f $log ]; then
      echo " "
      echo " "
      echo "${em1}$linesave${em2} "
      echo "${em1} ERROR message:${em2} "
      cat $log | awk '{print "  ",$0}'
      echo " "
    fi
    error "$@"
  fi
}
in_path () {
  if [ $# -eq 1 ]; then
    in_path_out=""
    if [ "X`basename $1`" = "X$1" ]; then
      for in_path_d in `echo $PATH | sed "s/:/ /g"`
      do
        if [ -x $in_path_d/$1 ]; then
          in_path_out="$in_path_out $in_path_d/$1"
        fi
      done
    else
      in_path_out=$1
    fi
    echo $in_path_out
  fi
}

# for proxy-settings
wget_http_proxy_arg=""
wget_ftp_proxy_arg=""
lynx_http_proxy_arg=""
lynx_ftp_proxy_arg=""
try_ncftpget="yes"
if [ "X$http_proxy" != "X" ] || [ "X$ftp_proxy" ]; then
  cat <<end_ip

  The following variables can be used to describe your proxy settings:

    http_proxy          = URL of HTTP proxy server
    http_proxy_user     = (optional) user name
    http_proxy_passwd   = (optional) password

    ftp_proxy           = URL of FTP proxy server
    ftp_proxy_user      = (optional) user name
    ftp_proxy_passwd    = (optional) password

end_ip
  if [ "X$http_proxy" != "X" ]; then
    [ "X$http_proxy_user" = "X" ] && warning "http_proxy set but ${em1}NOT${em2} http_proxy_user"
    [ "X$http_proxy_passwd" = "X" ] && warning "http_proxy set but ${em1}NOT${em2} http_proxy_passwd"
    [ "X$http_proxy_user" != "X" ] && [ "X$http_proxy_passwd" != "X" ] && \
      wget_http_proxy_arg="--proxy-user=\"${http_proxy_user}\" --proxy-passwd=\"${http_proxy_passwd}\"" && \
      lynx_http_proxy_arg="-pauth=${http_proxy_user}:${http_proxy_passwd}" && \
      try_ncftpget="no"
  fi
  if [ "X$ftp_proxy" != "X" ]; then
    [ "X$ftp_proxy_user" = "X" ] && warning "ftp_proxy set but ${em1}NOT${em2} ftp_proxy_user"
    [ "X$ftp_proxy_passwd" = "X" ] && warning "ftp_proxy set but ${em1}NOT${em2} ftp_proxy_passwd"
    [ "X$ftp_proxy_user" != "X" ] && [ "X$ftp_proxy_passwd" != "X" ] && \
      wget_ftp_proxy_arg="--proxy-user=\"${ftp_proxy_user}\" --proxy-passwd=\"${ftp_proxy_passwd}\"" && \
      lynx_ftp_proxy_arg="-pauth=${http_proxy_user}:${http_proxy_passwd}" && \
      try_ncftpget="no"
  fi
fi

########################################################################

usage () {
  echo " "
  echo " USAGE: $0 [-v <version>] [-c] [-f|-F] [-h]"
  echo " "
  echo "        -c           : continue previous run (configuration/compilation/...)"
  echo "        -f           : force running through all steps"
  echo "        -F           : just keep going ... "
  echo "        -h           : this message"
  echo "        -v <version> : install a specific version of CCP4 - possible choices are"

  echo $CCP4_versions | awk '{for(i=1;i<=NF;i++){
    n++
    if(n==1){
      print "                        ",$i,"(default)"
    }else{
      print "                        ",$i
    }
  }}'
  echo " "
}

use_version=`echo $CCP4_versions | awk '{print $1}'`
force=0
cont=0
while [ $# -gt 0 ]
do
  case $1 in
    -c) cont=1;;
    -f) force=2;;
    -F) force=1;;
    -h) usage;exit 0;;
    -v) use_version=$2;shift;;
    *) usage;error "unknown command line argument \"$1\""
  esac
  shift;
done

cdir=`pwd`
log=$cdir/$$.log
if [ "X$CCP4_MASTER" != "X" ]; then
  touch $CCP4_MASTER/$$.log >/dev/null 2>&1
  [ $? -ne 0 ] && warning "unable to create files in \$CCP4_MASTER=$CCP4_MASTER - maybe you want to reset \$CCP4_MASTER?"
  if [ ! -f $cdir/$$.log ]; then
    unset CCP4_MASTER
  else
    cdir=$CCP4_MASTER
  fi
  rm -f $CCP4_MASTER/$$.log
fi
#
# allow user to change the value of $cdir - to get rid of automount prefixes etc.
#
touch $log
if [ $? -ne 0 ]; then
  error "unable to create files in $cdir"
fi
echo "$$" > $log
if [ "X$CCP4_MASTER" = "X" ] || [ $force -eq 0 ]; then
  echo " "
  echo " Please make sure to give the correct value below (e.g"
  echo " strip automount prefixes off) - especially in a multi-OS/"
  echo " multi-machines setup. The default will probably be ok."
  echo " "
  myechon " ${em1}CCP4_MASTER directory${em2} [$cdir] ${em1}>${em2} "
  read m
  if [ "X$m" != "X" ] && [ -d $m ] && [ -f ${m}/$$.log ] && [ `cat ${m}/$$.log` -eq $$ ]; then
    cdir=$m
  elif [ "X$m" != "X" ]; then
    warning "unable to accept your input - keeping current value"
  fi
fi
rm $log

# -----------------------------------------------------------------
#
# !!!!!!!!!!!!!!!!!!!!!!!! SYSTEM DEPENDENT !!!!!!!!!!!!!!!!!!!!!!!
#
# set possible Fortran/C compiler combinations on various platforms
#
if [ "X$compilers" = "X" ]; then
  case `uname -s` in
    IRIX*)
      compilers="f77:cc \
                 f90:cc \
                 g77;-fno-second-underscore:gcc \
                 g77-3;-fno-second-underscore:gcc-3|gcc3 \
                 g773;-fno-second-underscore:gcc-3|gcc3"
      compilers="f77:cc \
                 f90:cc"
      ;;
    OSF1)
      compilers="f77:cc \
                 f90:cc \
                 g77;-fno-second-underscore:gcc \
                 g77-3;-fno-second-underscore:gcc-3|gcc3 \
                 g773;-fno-second-underscore:gcc-3|gcc3"
      compilers="f77:cc \
                 f90:cc"
      ;;
    AIX)
      compilers="xlf;-qextname:cc \
                 xlf90;-qfixed%-qextname:cc"
      ;;
    Darwin)
      compilers="g77;-fno-second-underscore:gcc \
                 g95;-fno-second-underscore:gcc \
                 f95:gcc \
                 xlf;-qextname:xlc \
                 xlf90;-qfixed%-qextname:xlc"
      ;;
    Linux)
      case `myunamem` in
        alpha) 
          compilers="fort:ccc \
                     g77;-fno-second-underscore:gcc \
                     g77-3;-fno-second-underscore:gcc-3|gcc3 \
                     g773;-fno-second-underscore:gcc-3|gcc3"
          warning "not yet tested for CCP4 version(s) $CCP4_versions"
          ;;
        i?86)
          compilers="ifc;-Vaxlib:icc|gcc|gcc3|gcc-3 \
                     ifort;-Vaxlib:icc|gcc|gcc3|gcc-3 \
                     pgf90:pgcc|gcc|gcc3|gcc-3 \
                     pgf77:pgcc|gcc|gcc3|gcc-3 \
                     g77;-fno-second-underscore:gcc \
                     g77-3;-fno-second-underscore:gcc-3|gcc3 \
                     g773;-fno-second-underscore:gcc-3|gcc3 \
                     lf95;--staticlink:gcc|gcc3|gcc-3"
          ;;
        ia64)
          compilers="efc;-Vaxlib:ecc|gcc|gcc3|gcc-3 \
                     ifort;-Vaxlib:icc|gcc|gcc3|gcc-3 \
                     g77;-fno-second-underscore:gcc \
                     g773;-fno-second-underscore:gcc3"
          ;;
        x86_64)
          compilers="g77;-fno-second-underscore:gcc \
                     ifort;-Vaxlib:icc|gcc|gcc3|gcc-3 \
                     pgf90:pgcc|gcc|gcc3|gcc-3 \
                     pgf77:pgcc|gcc|gcc3|gcc-3 \
                     pathf90;-fno-second-underscore:pathcc|gcc|gcc3|gcc-3 \
                     g773;-fno-second-underscore:gcc3"
          ;;
        *) error "unknown Linux architecture `myunamem`"
          ;;
      esac
      ;;
    *)
      error "this script is not (yet) configured for system `uname -s`"
      ;;
  esac
fi

FoundCorrectVersion=0
iCCP4=0
for CCP4_version in $CCP4_versions
do
  iCCP4=`expr $iCCP4 + 1`
  CCP4_tarfile=`echo $CCP4_tarfiles | awk -v i=$iCCP4 '{print $i}'`
  CCP4_md5sum=`echo $CCP4_md5sums | awk -v i=$iCCP4 '{print $i}'`
  CCP4_cksum=`echo $CCP4_cksums | awk -v i=$iCCP4 '{print $i}'`
  CCP4_ftp=`echo $CCP4_ftps | awk -v i=$iCCP4 '{print $i}'`

  if [ "X$CCP4_version" = "X$use_version" ]; then
    FoundCorrectVersion=1
    note "installing CCP4 ${CCP4_version}-cvX on `uname -s` (`myunamem`)"

    # -----------------------------------------------------------------
    # get the CCP4 distribution
    #
    getit=1
    if [ -f ${CCP4_tarfile} ]; then
      type md5sum > /dev/null 2>&1
      if [ $? -eq 0 ]; then
        tmp=`md5sum ${CCP4_tarfile} | awk '{print $1}'`
        if [ "X$tmp" != "X$CCP4_md5sum" ]; then
          warning "the file ${CCP4_tarfile} doesn't seem to be correct:" " " \
                  "MD5SUM  = \"$tmp\"" " " \
                  "(expected \"$CCP4_md5sum\")"
          getit=1
        fi
        getit=0
      else
        type cksum > /dev/null 2>&1
        if [ $? -eq 0 ]; then
          tmp=`cksum ${CCP4_tarfile} | awk '{print $2}'`
          if [ $tmp -ne $CCP4_cksum ]; then
            warning "the file ${CCP4_tarfile} doesn't seem to be correct:" " " \
                    "CKSUM   = \"$tmp\"" " " \
                    "(expected \"$CCP4_cksum\")"
            getit=1
          fi
          getit=0
        fi
      fi
    fi
    if [ $getit -eq 1 ]; then
      isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
      myechon " ${em1}${isec}.${em2} getting ${CCP4_tarfile} ... "
      get_file ${CCP4_ftp}/${CCP4_tarfile} || (echo " "; cat $log ; error "getting ${CCP4_ftp}/${CCP4_tarfile}")
      echo "done" && rm -f $log
      break
    else
      break
    fi
  fi
done
if [ $FoundCorrectVersion -eq 0 ]; then
  warning "unable to find the version you asked for - please check!"
  usage
  error "stopping"
fi
CV_file=`echo $CV_files | awk -v i=$iCCP4 '{print $i}'`
CCP4_version_1=`echo $CCP4_version | awk '{i=split($1,a,".");if(i>=1){print a[1]}else{print 0}}'`
CCP4_version_2=`echo $CCP4_version | awk '{i=split($1,a,".");if(i>=2){print a[2]}else{print 0}}'`
CCP4_version_3=`echo $CCP4_version | awk '{i=split($1,a,".");if(i>=3){print a[3]}else{print 0}}'`
#
# -----------------------------------------------------------------
# unpack it
#
chkexe gunzip tar xmkmf
subdir="ccp4-${CCP4_version}"

if [ ! -d $subdir ] || [ $getit -eq 1 ]; then
  if [ $getit -eq 1 ] && [ -d $subdir ]; then
    warning "we're going to overwrite content of subdirectory $subdir"
  fi
  isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
  myechon " ${em1}${isec}.${em2} unpacking ${CCP4_tarfile} ... "
  gunzip -c ${CCP4_tarfile} 2>$log | tar -xf - 2>>$log || \
    (echo " "; cat $log ; error "unpacking ${CCP4_ftp}/${CCP4_tarfile}")
  echo "done" && rm -f $log
fi

cd $cdir/$subdir 2>/dev/null || error "unable to cd into $subdir"

if [ ! -d .cv ]; then
  mkdir $cdir/$subdir/.cv 2>/dev/null || \
    error "unable to create directory $subdir/.cv"
fi

cd $cdir/$subdir/.cv 2>/dev/null || error "unable to cd into $subdir/.cv"

# -----------------------------------------------------------------
# get cv file(s)
#
isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
myechon " ${em1}${isec}.${em2} getting ${CV_file} ... "
get_file -f ${CV_http}/${CV_file}
if [ $? -ne 0 ] || [ ! -f ${CV_file} ]; then
  echo " "
  cat $log && rm -f $log
  error "getting ${CV_http}/${CV_file}"
fi
echo "done" && rm -f $log

n_getfile=0
n_testfile=`cat ${CV_file} | awk '{if(NF==3)print}' | wc -l`
i_testfile=1
while [ $i_testfile -le $n_testfile ]
do
  file=`awk -v i=$i_testfile 'BEGIN{n=0}{n++;if(n==i){print $1}}' ${CV_file}`
  md5sum=`awk -v i=$i_testfile 'BEGIN{n=0}{n++;if(n==i){if(NF>=2){print $2}}}' ${CV_file}`
  chksum=`awk -v i=$i_testfile 'BEGIN{n=0}{n++;if(n==i){if(NF>=2){print $3}}}' ${CV_file}`
  gile=`basename $file`
  getit=1
  if [ -f $gile ]; then
    isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
    myechon " ${em1}${isec}.${em2} checking $file ... "
    getit=0
    type md5sum > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      tmp=`md5sum $gile | awk '{print $1}'`
      if [ "X$tmp" != "X$md5sum" ]; then
        getit=1
      fi
    else
      type cksum > /dev/null 2>&1
      if [ $? -eq 0 ]; then
        tmp=`cksum $gile | awk '{print $2}'`
        if [ "X$tmp" != "X$chksum" ]; then
          getit=1
        fi
      else
        getit=1
      fi
    fi
    echo "done"
  fi
  if [ ! -f `basename $file` ] || \
     [ $getit -eq 1 ] || \
     [ "X`basename $file | cut -c-7`" = "Xversion" ]; then
    if [ "X`basename $file`" != "X$myself" ]; then
      isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
      myechon " ${em1}${isec}.${em2} getting $file ... "
      get_file -f ${CV_http}/$file
      if [ $? -ne 0 ] || [ ! -f $file ]; then
        echo " "
        cat $log && rm -f $log
        error "getting $file"
      fi
      echo "done" && rm -f $log
      n_getfile=`expr $n_getfile + 1`
    else
      error "file $file has changed - this won't work!"
    fi
  fi
  i_testfile=`expr $i_testfile + 1`
done

cd $cdir/$subdir
if [ -f .cv/version-${CCP4_version} ]; then
  chkfile .cv/version-${CCP4_version}
  CV_version=`cat .cv/version-${CCP4_version}`
  chkfile .cv/ccp4-${CCP4_version}-cv${CV_version}.patch
else
  chkfile .cv/version
  CV_version=`cat .cv/version`
  chkfile .cv/ccp4-${CCP4_version}-cv${CV_version}.patch
fi

chkfile .cv/ccp4.setup-sh .cv/ccp4.setup-csh
[ -f include/ccp4.setup-sh ] && \
  [ `grep -c CSYSTEM include/ccp4.setup-sh` -eq 0 ] && \
  [ ! -f include/ccp4.setup-sh.dist ] && \
  mv include/ccp4.setup-sh include/ccp4.setup-sh.dist
[ -f include/ccp4.setup-csh ] && \
  [ `grep -c CSYSTEM include/ccp4.setup-csh` -eq 0 ] && \
  [ ! -f include/ccp4.setup-csh.dist ] && \
  mv include/ccp4.setup-csh include/ccp4.setup-csh.dist

[  ! -f include/ccp4.setup-sh ] && sed "s%CV_CCP4_MASTER%$cdir%g" .cv/ccp4.setup-sh | sed "s%CV_CCP4%$subdir%g" > include/ccp4.setup-sh
[  ! -f include/ccp4.setup-csh ] && sed "s%CV_CCP4_MASTER%$cdir%g" .cv/ccp4.setup-csh | sed "s%CV_CCP4%$subdir%g" > include/ccp4.setup-csh

# -----------------------------------------------------------------
# patch CCP4 distribution
#
if [ -f .cv/.version-${CCP4_version} ]; then
  . .cv/.version-${CCP4_version}
elif [ -f .cv/.version ]; then
  . .cv/.version
else
  patched=0
fi

n_patched=0
prev=-1
next=`expr $patched + 1`
while [ $next -le ${CV_version} ]
do
  if [ $prev -eq -1 ]; then
    echo " "
  fi
  prev=`expr $next - 1`
  patchfile=ccp4-${CCP4_version}-cv${next}.patch
  chkfile .cv/$patchfile
  isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
  if [ $next -gt 1 ]; then
    myechon " ${em1}${isec}.${em2} patching CCP4 ${CCP4_version}-cv${prev} to become ${CCP4_version}-cv${next} ... "
  else
    myechon " ${em1}${isec}.${em2} patching CCP4 ${CCP4_version} to become ${CCP4_version}-cv${next} ... "
  fi
  patch -p1 < .cv/$patchfile > $log 2>&1
  error_chk $? "during patching"
  echo "done"
  n_patched=`expr $n_patched + 1`
  echo "patched=${next}" >> .cv/.version-${CCP4_version}
  next=`expr $next + 1`
done
echo " "

cd $cdir/$subdir/.cv

# -----------------------------------------------------------------
# check for working Fortran/C compiler combination
#
chkfile hw.f hw_main.f hw_sub.c hw.c

note "looking for working Fortran/C compiler"
ic=0
for compiler in $compilers
do
  FCs=`echo $compiler | cut -f1 -d':' | sed "s/|/ /g"`
  CCs=`echo $compiler | cut -f2 -d':' | sed "s/|/ /g"`
  for FCx in $FCs
  do
    FC=`echo $FCx | cut -f1 -d';'`
    FCy=`echo $FCx | sed "s/\;/ /g" | sed "s/\%/ /g"`
    type $FC >/dev/null 2>&1
    if [ $? -eq 0 ]; then
      for FC in `in_path $FC`
      do
        if [ `echo $FCy | grep -c $FC` -eq 1 ]; then
          pFC=""
        else
          pFC=`dirname $FC`
        fi
        isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
        myechon " ${em1}${isec}.${em2} testing Fortran compiler $FC ... "
        $pFC/$FCy -o hw hw.f > $log 2>&1
        if [ $? -eq 0 ]; then
          ./hw > $log 2>&1
          if [ $? -eq 0 ] && [ `grep -c "Hello world" $log` -eq 1 ]; then
            echo "${em1}working${em2} "
            for CCx in $CCs
            do
              CC=`echo $CCx | cut -f1 -d';'`
              CCy=`echo $CCx | sed "s/\;/ /g"`
              type $CC >/dev/null 2>&1
              if [ $? -eq 0 ]; then
                for CC in `in_path $CC`
                do
                  if [ `echo $CCy | grep -c $CC` -eq 1 ]; then
                    pCC=""
                  else
                    pCC=`dirname $CC`
                  fi
                  isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
                  myechon " ${em1}${isec}.${em2} testing C compiler $CC ... "
                  $pCC/$CCy -o hw hw.c > $log 2>&1
                  if [ $? -eq 0 ]; then
                    ./hw > $log 2>&1
                    if [ $? -eq 0 ] && [ `grep -c "Hello world" $log` -eq 1 ]; then
                      echo "${em1}working${em2} "
                      isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
                      myechon " ${em1}${isec}.${em2} ${em1}->${em2} testing Fortan and C compiler ${ul1}$FC${ul2} + ${ul1}$CC${ul2} together ... "
                      rm -f hw_main.o hw_sub.o hw
                      $pFC/$FCy -c hw_main.f >$log 2>&1 && \
                      $pCC/$CCy -c hw_sub.c >$log 2>&1 && \
                      $pFC/$FCy -o hw hw_main.o hw_sub.o >$log 2>&1 && \
                      ./hw > $log 2>&1
                      if [ $? -eq 0 ] && [ `grep -c "Hello world" $log` -eq 1 ]; then
                        echo "${em1}working${em2} "
                        ic=`expr $ic + 1`
                        eval "FCCC_$ic=\"$pFC/$FCx $pCC/$CCx\""
                      else
                        echo "not working (\"$FCy\" and \"$CCy\")"
                      fi
                    else
                      echo "${ul1}not${ul2} working"
                      note "during ./hw:"
                      ./hw 2>&1 | awk '{print "     ",$0}'
                      echo " "
                    fi
                  else
                    echo "${ul1}not${ul2} working"
                    note "during $pCC/$CCy -o hw hw.c:"
                    $pCC/$CCy -o hw hw.c 2>&1 | awk '{print "     ",$0}'
                    echo " "
                  fi
                done
              else
                isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
                echo " ${em1}${isec}.${em2} C compiler $CC ... not found!"
              fi
            done
          else
            echo "${ul1}not${ul2} working"
            note "during ./hw:"
            ./hw 2>&1 | awk '{print "     ",$0}'
            echo " "
          fi
        else
          echo "${ul1}not${ul2} working"
          note "during $pFC/$FCy -o hw hw.f:"
          $pFC/$FCy -o hw hw.f 2>&1 | awk '{print "     ",$0}'
          echo " "
        fi
      done
    else
      isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
      echo " ${em1}${isec}.${em2} Fortran compiler $FC ... not found!"
    fi
  done
done
rm -f hw hw_main.o hw_sub.o work.pcl work.pc
# -----------------------------------------------------------------
# present menu to decide which compiler to use
#
if [ $ic -gt 0 ]; then
  echo " "
  if [ $ic -gt 1 ]; then
    i=0
    while [ $i -lt 1 ] || [ $i -gt $ic ]
    do
      note "found more than one (apparently) working compiler" "combination"
      i=1
      while [ $i -le $ic ]
      do
        eval "FCCC=\$FCCC_$i"
        FCx=`echo $FCCC   | awk '{print $1}'`
        CCx=`echo $FCCC   | awk '{print $2}'`
        FC=`echo $FCx | cut -f1 -d';'`
        CC=`echo $CCx | cut -f1 -d';'`
        echo "     ${em1}[${i}]${em2} "`echo $FC $CC | awk '{print $1," + ",$2}'`
        i=`expr $i + 1`
      done
      echo " "
      myechon " please select one of them ${em1}>${em2} "
      read i
      if [ "X$i" = "X" ]; then
        i=0
      fi
    done
    eval "FCCC=\$FCCC_$i"
    FCx=`echo $FCCC   | awk '{print $1}'`
    CCx=`echo $FCCC   | awk '{print $2}'`
  else
    FCx=`echo $FCCC_1 | awk '{print $1}'`
    CCx=`echo $FCCC_1 | awk '{print $2}'`
  fi
else
  error "couldn't find a working Fortran/C compiler combination"
fi
FC=`echo $FCx | cut -f1 -d';'`
FCx=`echo $FCx | sed "s/\;/ /g" | sed "s/\%/ /g"`
CC=`echo $CCx | cut -f1 -d';'`
CCx=`echo $CCx | sed "s/\;/ /g" | sed "s/\%/ /g"`
note "using Fortran compiler ${ul1}$FC${ul2} and C compiler ${ul1}$CC${ul2} "

CCbase=`echo $CC | awk '{print $1}'`
CCbase=`basename $CCbase`
FCbase=`echo $FC | awk '{print $1}'`
FCbase=`basename $FCbase`
# -----------------------------------------------------------------
#
# !!!!!!!!!!!!!!!!!!!!!!!! SYSTEM DEPENDENT !!!!!!!!!!!!!!!!!!!!!!!
#
# set CSYSTEM based on compiler selection
#
case `uname -s` in
  IRIX*)
    case `basename $FC` in 
      g77*) CSYSTEM=irixn32-g77;target="irix --with-shared-lib";;
       f77) CSYSTEM=irixn32-f77;target="irix --with-shared-lib";;
       f90) CSYSTEM=irixn32-f90;target="irix --with-shared-lib";;
         *) error "unknown Fortran cmopiler $FC on system `uname -s`";;
    esac
    ;;
  OSF1)
    case `basename $FC` in 
      g77*) CSYSTEM=alpha-g77;target="osf1 --with-shared-lib";;
       f77) CSYSTEM=alpha-f77;target="osf1 --with-shared-lib";;
       f90) CSYSTEM=alpha-f90;target="osf1 --with-shared-lib";;
         *) error "unknown Fortran cmopiler $FC on system `uname -s`";;
    esac
    ;;
  AIX)
    case `basename $FC` in 
        xlf) CSYSTEM=aix-xlf;target="aix --with-shared-lib";;
      xlf90) CSYSTEM=aix-xlf90;target="aix --with-shared-lib";;
        *) error "unknown Fortran cmopiler $FC on system `uname -s`";;
    esac
    ;;
  Darwin)
    case `basename $FC` in
      g77*) CSYSTEM=Darwin-g77;target="Darwin";;
      f95*) CSYSTEM=Darwin-f95;target="Darwin";;
      g95*) CSYSTEM=Darwin-g95;target="Darwin";;
      xlf*) CSYSTEM=Darwin-xlf;target="Darwin_ibm_compilers";;
         *) error "unknown Fortran compiler $FC on system `uname -s`";;
    esac
    ;;
  Linux)
    case `myunamem` in
      alpha) 
        case `basename $FC` in 
          g77*) CSYSTEM=alinux-g77;target="linux --with-shared-lib";;
          fort) CSYSTEM=alinux-fort;target="linux_compaq_compilers --with-shared-lib";;
             *) error "unknown Fortran cmopiler $FC on system `uname -s` (`myunamem`)";;
        esac
        ;;
      i?86)
        case `basename $FC` in 
           g77*) CSYSTEM=linux-g77;target="linux --with-shared-lib";;
            ifc) CSYSTEM=linux-ifc;target="linux_intel_compilers --with-shared-lib";;
          ifort) CSYSTEM=linux-ifort;target="linux_intel_compilers --with-shared-lib";;
          pgf77) CSYSTEM=linux-pgf77;target="linux --with-shared-lib";;
          pgf90) CSYSTEM=linux-pgf90;target="linux --with-shared-lib";;
           lf95) CSYSTEM=linux-lf95;target="linux --with-shared-lib";;
              *) error "unknown Fortran comopiler $FC on system `uname -s` (`myunamem`)";;
        esac
        ;;
      x86_64)
        case `basename $FC` in 
             g77*) CSYSTEM=linuxx64-g77;target="linux";;
            ifort) CSYSTEM=linuxx64-ifort;target="linux_intel_compilers --with-shared-lib";;
            pgf77) CSYSTEM=linuxx64-pgf77;target="linux --with-shared-lib";;
            pgf90) CSYSTEM=linuxx64-pgf90;target="linux --with-shared-lib";;
          pathf90) CSYSTEM=linuxx64-pathf90;target="linux --with-shared-lib";;
              *) error "unknown Fortran compiler $FC on system `uname -s` (`myunamem`)";;
        esac
        ;;
      ia64)
        case `basename $FC` in 
           g77*)  CSYSTEM=linuxa64-g77;target="linux";;
           efc)   CSYSTEM=linuxa64-efc;target="ia64_linux_intel --with-shared-lib";;
           ifort) CSYSTEM=linuxa64-ifort;target="ia64_linux_intel --with-shared-lib";;
              *) error "unknown Fortran compiler $FC on system `uname -s` (`myunamem`)";;
        esac
        ;;
      *) error "unknown Linux architecture `myunamem`"
        ;;
    esac
    ;;
  *) 
    error "this script is not (yet) configured for system `uname -s`"
    ;;
esac

cd $cdir/$subdir

if [ `echo $target | grep -c with-shared-lib` -ne 0 ]; then
  note "we can produce static (portable) or shared (smaller) binaries."
  myechon " Do you want to compile static binaries n/[y] ${em1}>${em2} "
  read m
  echo " "
  if [ "X$m" = "Xn" ]; then
    StaticOrShared="shared"
    DirExtension=""
  else
    StaticOrShared="static"
    target=`echo $target | sed "s/--with-shared-lib//g"`
    DirExtension=".static"
  fi
else
  StaticOrShared="static"
  target=`echo $target | sed "s/--with-shared-lib//g"`
  DirExtension=".static"
fi

[ $CCP4_version_1 -ge 5 ] && target="--disable-pdb_extract $target"
# -----------------------------------------------------------------
# set (necessary?) CCP4 variables for building
#
cat <<end_ip > $cdir/$subdir/.cv/ccp4.setup-compile-sh
           FC="$FCx"
           CC="$CCx"
         CCP4=$cdir/$subdir
     CCP4_SCR=/tmp
  BINSORT_SCR=\$CCP4_SCR
         CBIN=\$CCP4/bin/$CSYSTEM${DirExtension}
         CLIB=\$CCP4/lib/$CSYSTEM${DirExtension}
        CLIBS=\$CCP4/lib/src
     CCP4_LIB=\$CLIB
    CCP4_OPEN=UNKNOWN
  BINSORT_MEM=204800
     MMCIFDIC=\$CLIB/cif_mmdic.lib
    MOLREPLIB=\$CCP4/lib/data/monomers/
    CLIBD_MON=\$CCP4/lib/data/monomers/
PUBLIC_FONT84=\$CLIB/font84.dat
         CETC=\$CCP4/etc
        CINCL=\$CCP4/include
        CLIBD=\$CCP4/lib/data
         CDOC=\$CCP4/doc
        CHTML=\$CCP4/html
  LD_RUN_PATH="\$CLIB:\$CCP4/lib/src:\$CCP4/lib/ccif"
export FC CC CCP4 CCP4_SCR BINSORT_SCR CBIN CLIB CCP4_OPEN BINSORT_MEM \\
       MMCIFDIC MOLREPLIB CLIBD_MON PUBLIC_FONT84 CETC CINCL CLIBD \\
       CCP4_LIB LD_RUN_PATH CLIBS CDOC CHTML
end_ip
cat <<end_ip > $cdir/$subdir/.cv/ccp4.setup-compile-csh
setenv            FC "$FCx"
setenv            CC "$CCx"
setenv          CCP4 $cdir/$subdir
setenv      CCP4_SCR /tmp
setenv   BINSORT_SCR \$CCP4_SCR
setenv          CBIN \$CCP4/bin/$CSYSTEM${DirExtension}
setenv          CLIB \$CCP4/lib/$CSYSTEM${DirExtension}
setenv         CLIBS \$CCP4/lib/src
setenv      CCP4_LIB \$CLIB
setenv     CCP4_OPEN UNKNOWN
setenv   BINSORT_MEM 204800
setenv      MMCIFDIC \$CLIB/cif_mmdic.lib
setenv     MOLREPLIB \$CCP4/lib/data/monomers/
setenv     CLIBD_MON \$CCP4/lib/data/monomers/
setenv PUBLIC_FONT84 \$CLIB/font84.dat
setenv          CETC \$CCP4/etc
setenv         CINCL \$CCP4/include
setenv         CLIBD \$CCP4/lib/data
setenv          CDOC \$CCP4/doc
setenv         CHTML \$CCP4/html
setenv   LD_RUN_PATH "\${CLIB}:\${CCP4}/lib/src:\${CCP4}/lib/ccif"
end_ip
. $cdir/$subdir/.cv/ccp4.setup-compile-sh
# -----------------------------------------------------------------
# create some necessary directories
#
if [ ! -d $CBIN ]; then
  mkdir -p $CBIN || error "unable to create directory $CBIN"
fi
if [ ! -d $CLIB ]; then
  mkdir -p $CLIB || error "unable to create directory $CLIB"
fi
chkfile .cv/setup.$CSYSTEM
. .cv/setup.$CSYSTEM

# CCP4 version specific settings
[ $CCP4_version_1 -ge 5 ] && makeflags="includedir=$CCP4/include"
[ $CCP4_version_1 -ge 5 ] && realclean="distclean" || realclean="realclean"

logext="log_${CSYSTEM}_`hostname -s`"

Lmake=`expr $n_getfile + $n_patched + $force`

if [ $Lmake -gt 0 ] || [ ! -x $CBIN/sfall ]; then
  [ $cont -eq 0 ] && rm -f make.$logext
  # -----------------------------------------------------------------
  # clean up
  #
  if [ -f Makefile ] && [ $cont -eq 0 ]; then
    isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
    myechon " ${em1}${isec}.${em2} cleaning up CCP4 ${CCP4_version}-cv${CV_version} [$subdir/make.$logext] ... "
    make $realclean -k >> make.$logext 2>&1
    if [ $? -ne 0 ]; then
      echo " "
      warning "unable to do a $realclean - please have a look at $subdir/make.$logext"
    else
      echo "done"
    fi
  fi

  # -----------------------------------------------------------------
  # configure CCP4
  #
  if [ ! -f config.status ] && [ $cont -eq 0 ]; then
    isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
    myechon " ${em1}${isec}.${em2} configuring CCP4 ${CCP4_version}-cv${CV_version} [$subdir/configure.$logext] ... "
    echo `whoami` `date` >> .agree2ccp4
    echo `whoami` `date` >> .agree2ccp4v5
    ./configure --srcdir=$CCP4 --bindir=$CBIN --libdir=$CLIB \
                --with-x --with-netlib-lapack --with-warnings $target > configure.$logext 2>&1 </dev/null
    if [ $? -ne 0 ]; then
      echo "FAILED"
      note "please have a look at $subdir/configure.$logext"
      error "during configure step"
    else
      echo "done"
    fi

    # fix config.status file
    [ -f config.status ] && sed "s/\\$/\\\\$/g" config.status > $$.config.status && mv $$.config.status config.status
  fi

  # -----------------------------------------------------------------
  #
  # some fixes for the libtool part in x-windows/libjwc/libjwc_f (the
  # configuration tools can't really deal with Fortran compilers)
  #
  case $CSYSTEM in
    *lf95) note "need to fix x-windows/libjwc/libjwc_f/libtool" && \
             sed "s/pic_flag=\" -fPIC\"/pic_flag=\" \"/g" $CCP4/x-windows/libjwc/libjwc_f/libtool > $$ && \
             mv $$ $CCP4/x-windows/libjwc/libjwc_f/libtool && chmod +w $CCP4/x-windows/libjwc/libjwc_f/libtool
      ;;
    *ifc|*ifort)
      case $CCbase in
        gcc*) note "need to fix x-windows/libjwc/libjwc_f/Makefile" && \
                awk '{print}/^F77LD = /{print "F77LD = $(CC)"}' $CCP4/x-windows/libjwc/libjwc_f/Makefile > $$ && \
                mv $$ $CCP4/x-windows/libjwc/libjwc_f/Makefile && chmod +w $CCP4/x-windows/libjwc/libjwc_f/Makefile
         ;;
      esac
      ;;
  esac
  #
  # some fixes for the libtool part in x-windows/xdl_view/src
  #
  case $CSYSTEM in
    *ifc|*ifort)
      case $CCbase in
        icc|ecc) note "need to fix x-windows/xdl_view/src/libtool" && \
               awk '{print}/^wl=/{print "wl=\"-Qoption,ld,\""}' $CCP4/x-windows/xdl_view/src/libtool > $$ && \
               mv $$ $CCP4/x-windows/xdl_view/src/libtool && chmod +x $CCP4/x-windows/xdl_view/src/libtool
             note "need to fix x-windows/libjwc/libjwc_f/libtool" && \
               awk '{print}/^wl=/{print "wl=\"-Qoption,ld,\""}' $CCP4/x-windows/libjwc/libjwc_f/libtool > $$ && \
               mv $$ $CCP4/x-windows/libjwc/libjwc_f/libtool && chmod +x $CCP4/x-windows/libjwc/libjwc_f/libtool
             note "need to fix x-windows/libjwc/libjwc_c/libtool" && \
               awk '{print}/^wl=/{print "wl=\"-Qoption,ld,\""}' $CCP4/x-windows/libjwc/libjwc_c/libtool > $$ && \
               mv $$ $CCP4/x-windows/libjwc/libjwc_c/libtool && chmod +x $CCP4/x-windows/libjwc/libjwc_c/libtool
      esac
      ;;
  esac
  #
  # fixes for Mosflm configuration
  #
  sed "s%$CCP4/lib %$CLIB %g" $CCP4/x-windows/Mosflm/mosflm/Makefile > $$ && \
    mv $$ $CCP4/x-windows/Mosflm/mosflm/Makefile
  case $CC in
    *pgcc) sed -e "s%O = lo%O = o%g" -e "s%A = la%A = a%g" $CCP4/x-windows/Mosflm/jpg/Makefile > $$ && \
           mv $$ $CCP4/x-windows/Mosflm/jpg/Makefile;;
  esac
  if [ -f /usr/include/ncurses.h ]; then
    if [ $CCP4_version_1 -ge 5 ]; then
      sed "s%CFLAGS = -O0 %CFLAGS = -O0 -DHAVE_NCURSES -I/usr/include %g" $CCP4/x-windows/Mosflm/mosflm/Makefile > $$ && \
        mv $$ $CCP4/x-windows/Mosflm/mosflm/Makefile
    else
      sed "s% chelp.c% -DHAVE_NCURSES -I/usr/include chelp.c%g" $CCP4/x-windows/Mosflm/mosflm/Makefile > $$ && \
        mv $$ $CCP4/x-windows/Mosflm/mosflm/Makefile
    fi
  fi
  # -----------------------------------------------------------------
  # compile it
  #

  cat <<end_ip > $$.csh
unlimit
limit
end_ip
  csh $$.csh > $$.out 2>&1
  d_=`grep "^datasize" $$.out | awk '{print $2}'`
  s_=`grep "^stacksize" $$.out | awk '{print $2}'`
  ulimit -s $s_ > $$.out 2>&1
  ulimit -d $d_ > $$.out 2>&1
  rm -f $$.csh $$.out

  isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
  myechon " ${em1}${isec}.${em2} compiling   CCP4 ${CCP4_version}-cv${CV_version} [$subdir/make.$logext] ... "
  make $makeflags >> make.$logext 2>&1
  if [ $? -ne 0 ]; then
    echo "FAILED"
    note "please have a look at $subdir/make.$logext"
    error "during compilation step"
  else
    echo "done"
  fi

  # -----------------------------------------------------------------
  # install it
  #
  isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
  myechon " ${em1}${isec}.${em2} installing  CCP4 ${CCP4_version}-cv${CV_version} [$subdir/make.$logext] ... "
  make $makeflags install >> make.$logext 2>&1
  if [ $? -ne 0 ]; then
    echo "FAILED"
    note "please have a look at $subdir/make.$logext"
    error "during installation step"
  else
    echo "done"
  fi

  # -----------------------------------------------------------------
  # compile additional RasMol binaries
  #
  pdir=`pwd`
  cd $CCP4/x-windows/RasMol/src
  make clean >> $pdir/make.$logext 2>&1 
  make DEPTHDEF=-DSIXTEENBIT >> $pdir/make.$logext 2>&1 && \
    cp rasmol $CBIN/rasmol_16bit && \
    chmod 0755 $CBIN/rasmol_16bit
  make clean >> $pdir/make.$logext 2>&1 
  make DEPTHDEF=-DTHIRTYTWOBIT  >> $pdir/make.$logext 2>&1 && \
    cp rasmol $CBIN/rasmol_32bit && \
    chmod 0755 $CBIN/rasmol_32bit
  cd $pdir

  # -----------------------------------------------------------------
  # add this to list of possible binary setups - used by ccp4.setup-sh
  # and ccp4.setup-csh
  #
  if [ ! -f $cdir/$subdir/include/ccp4.setup-cv ] || \
     [ `grep -c "^${CSYSTEM}$" $cdir/$subdir/include/ccp4.setup-cv` -eq 0 ]; then
    if [ ! -f $cdir/$subdir/include/ccp4.setup-cv ]; then
      echo "# list of possible binary setups" > $cdir/$subdir/include/ccp4.setup-cv
      echo "CSYSTEMS=\" \"" >> $cdir/$subdir/include/ccp4.setup-cv
    fi
    echo "CSYSTEMS=\"\$CSYSTEMS $CSYSTEM\"" >> $cdir/$subdir/include/ccp4.setup-cv
  fi

  # -----------------------------------------------------------------
  # save some files (especially Makefiles)
  #
  d=`date +%Y%m%d_%H:%M`
  for f in `find . -name Makefile -print && \
            find . -name config.log -print && \
            find . -name config.status -print && \
            find . -name "ccp4.setup-compile-*sh" -print && \
            find . -name libtool -print`
  do
    cp -p $f ${f}_${CSYSTEM}_`hostname -s`
    cp -p $f ${f}_${CSYSTEM}_`hostname -s`_${d}
  done

  # -----------------------------------------------------------------
  # clean up
  #
  isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
  myechon " ${em1}${isec}.${em2} cleaning up CCP4 ${CCP4_version}-cv${CV_version} [$subdir/make.$logext] ... "
  make $realclean -k >> make.$logext 2>&1
  if [ $? -ne 0 ]; then
    echo " "
    warning "unable to do a $realclean - please have a look at $subdir/make.$logext"
  else
    echo "done"
  fi
fi

# -----------------------------------------------------------------
# deal with CCP4i required Tcl/Tk BLT stuff
#
type bltwish >/dev/null 2>&1
if [ $? -eq 0 ]; then
  bltwish=`type bltwish | awk '{print $NF}'`
  if [ ! -x $bltwish ]; then
    unset bltwish
  fi
fi
type tclsh >/dev/null 2>&1
if [ $? -eq 0 ]; then
  tclsh=`type tclsh | awk '{print $NF}'`
  if [ ! -x $tclsh ]; then
    unset tclsh
  fi
fi
type wish >/dev/null 2>&1
if [ $? -eq 0 ]; then
  wish=`type wish | awk '{print $NF}'`
  if [ ! -x $wish ]; then
    unset wish
  fi
fi

rm -f $log

if [ "X$tclsh" != "X" ] && \
   [ "X$wish" != "X" ] && \
   [ "X$bltwish" != "X" ] && \
   [ $force -gt 1 ]; then
  do_link="yes"
else
  do_link="no"
fi

case `uname` in
  AIX) doshared="--disable-shared";;
    *) doshared="";;
esac

DSYSTEM=`echo $CSYSTEM | cut -f1 -d'-'`

if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/bltwish ] || \
   [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/tclsh ] || \
   [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/wish ]; then
  if [ $force -eq 0 ]; then
    note "we can try installing the BLT and Tcl/Tk tools needed for CCP4i"
    myechon " Do you want to continue [n]/y ${em1}>${em2} "
    read m
    echo " "
  else
    m=n
  fi
  if [ "X$m" = "Xy" ]; then
    unset COPTIM
    unset FOPTIM

    if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/bltwish ] || \
       [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/tclsh ] || \
       [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/wish ]; then

      if [ -d $cdir/$subdir/local/$DSYSTEM/lib ]; then
        if [ "X$LD_LIBRARY_PATH" = "X" ]; then
          LD_LIBRARY_PATH=$cdir/$subdir/local/$DSYSTEM/lib
        else
          LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$cdir/$subdir/local/$DSYSTEM/lib
        fi
        export LD_LIBRARY_PATH
      fi

      isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
      echo " ${em1}${isec}.${em2} getting and installing Tcl/Tk and BLT ... "

      #
      # first Tcl
      #
      if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/tclsh ]; then
        if [ "X$do_link" = "Xyes" ]; then
          mkdir -p $cdir/$subdir/local/$DSYSTEM/bin
          ln -s $tclsh $cdir/$subdir/local/$DSYSTEM/bin/tclsh
          note "using $tclsh as $subdir/local/$DSYSTEM/bin/tclsh"
        fi
      fi
      # still not there
      if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/tclsh ]; then
        echo " "
        mkdir -p $cdir/$subdir/local/src $cdir/$subdir/local/lib $cdir/$subdir/local/$DSYSTEM
        if [ ! -f $cdir/`basename $TCL_file` ]; then
          cd $cdir
          isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
          myechon " ${em1}${isec}.${em2} getting `basename $TCL_file` ... "
          get_file $TCL_file
          echo "done"
        fi
        cd $cdir/$subdir/local/src
        gunzip -c $cdir/`basename $TCL_file` | tar -xf -
        if [ $? -eq 0 ]; then
          cd $TCL_dir
          isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
          myechon " ${em1}${isec}.${em2} configuring, and compiling in $TCL_dir ... "
          ./configure --prefix=$cdir/$subdir/local \
                      --exec-prefix=$cdir/$subdir/local/$DSYSTEM $doshared > configure.$logext 2>&1
          make > make.$logext 2>&1
          make install >> make.$logext 2>&1
          for f in `find . -name Makefile -print ; find . -name config.log -print ; find . -name config.status -print ; find . -name tclConfig.sh -print`
          do
            cp -p $f ${f}_${DSYSTEM}_${d}
          done
          make distclean >> make.$logext 2>&1
          echo "done"
          tclsh=`ls -tr $cdir/$subdir/local/$DSYSTEM/bin/tclsh* | tail -1`
          tclsh=`basename $tclsh`
          if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/tclsh ]; then
            ln -s $tclsh $cdir/$subdir/local/$DSYSTEM/bin/tclsh
          fi
          ls -lL $cdir/$subdir/local/$DSYSTEM/bin/tclsh* | awk '{print "  ",$0}'
        fi
      fi
      #
      # now Tk
      #
      if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/wish ]; then
        if [ "X$do_link" = "Xyes" ]; then
          mkdir -p $cdir/$subdir/local/$DSYSTEM/bin
          ln -s $wish $cdir/$subdir/local/$DSYSTEM/bin/wish
          note "using $wish as $subdir/local/$DSYSTEM/bin/wish"
        fi
      fi
      # still not there
      if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/wish ]; then
        echo " "
        mkdir -p $cdir/$subdir/local/src $cdir/$subdir/local/lib $cdir/$subdir/local/$DSYSTEM
        if [ ! -f $cdir/`basename $TK_file` ]; then
          cd $cdir
          isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
          myechon " ${em1}${isec}.${em2} getting `basename $TK_file` ... "
          get_file $TK_file
          echo "done"
        fi
        cd $cdir/$subdir/local/src
        gunzip -c $cdir/`basename $TK_file` | tar -xf -
        if [ $? -eq 0 ]; then
          cd $TK_dir
          isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
          myechon " ${em1}${isec}.${em2} configuring, and compiling in $TK_dir ... "
          ./configure --prefix=$cdir/$subdir/local \
                      --exec-prefix=$cdir/$subdir/local/$DSYSTEM \
                      --with-tcl=$cdir/$subdir/local/$DSYSTEM/lib $doshared > configure.$logext 2>&1
          make > make.$logext 2>&1
          make install >> make.$logext 2>&1
          for f in `find . -name Makefile -print ; find . -name config.log -print ; find . -name config.status -print`
          do
            cp -p $f ${f}_${DSYSTEM}_${d}
          done
          make distclean >> make.$logext 2>&1
          echo "done"
          wish=`ls -tr $cdir/$subdir/local/$DSYSTEM/bin/wish* | tail -1`
          wish=`basename $wish`
          if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/wish ]; then
            ln -s $wish $cdir/$subdir/local/$DSYSTEM/bin/wish
          fi
          ls -lL $cdir/$subdir/local/$DSYSTEM/bin/wish* | awk '{print "  ",$0}'
        fi
      fi

      #
      # finally Blt
      #
      if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/bltwish ]; then
        if [ "X$do_link" = "Xyes" ]; then
          mkdir -p $cdir/$subdir/local/$DSYSTEM/bin
          ln -s $bltwish $cdir/$subdir/local/$DSYSTEM/bin/bltwish
          note "using $bltwish as $subdir/local/$DSYSTEM/bin/bltwish"
        fi
      fi
      # still not there
      if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/bltwish ]; then
        echo " "
        mkdir -p $cdir/$subdir/local/src $cdir/$subdir/local/lib $cdir/$subdir/local/$DSYSTEM
        if [ ! -f $cdir/`basename $BLT_file` ]; then
          cd $cdir
          isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
          myechon " ${em1}${isec}.${em2} getting `basename $BLT_file` ... "
          get_file $BLT_file
          echo "done"
          file $cdir/`basename $BLT_file` 2>/dev/null | grep -c compressed >/dev/null
          if [ $? -ne 0 ]; then
            rm -f $cdir/`basename $BLT_file`
            warning "unable to get file $cdir/`basename $BLT_file` - BLT will not be installed"
          fi
        fi
        if [ -f $cdir/`basename $BLT_file` ]; then
          cd $cdir/$subdir/local/src
          gunzip -c $cdir/`basename $BLT_file` | tar -xf -
          if [ $? -eq 0 ]; then
            cd $BLT_dir
            isec=`echo $isec | awk '{printf("%2.2d",$1+1)}'`
            myechon " ${em1}${isec}.${em2} configuring, and compiling in $BLT_dir ... "
            ./configure --prefix=$cdir/$subdir/local \
                        --exec-prefix=$cdir/$subdir/local/$DSYSTEM \
                        --with-tcl=$cdir/$subdir/local/$DSYSTEM/lib \
                        --with-tk=$cdir/$subdir/local/$DSYSTEM/lib $doshared > configure.$logext 2>&1
            make > make.$logext 2>&1
            cd src/shared
            make bltsh24 >> ../../make.$logext 2>&1
            make libBLTlite24.so >> ../../make.$logext 2>&1
            cd ../../
            make install >> make.$logext 2>&1
            for f in `find . -name Makefile -print && find . -name config.log -print && find . -name config.status -print`
            do
              cp -p $f ${f}_${DSYSTEM}_${d}
            done
            make distclean >> make.$logext 2>&1
            echo "done"
            bltwish=`ls -tr $cdir/$subdir/local/$DSYSTEM/bin/bltwish* | tail -1`
            bltwish=`basename $bltwish`
            if [ ! -x $cdir/$subdir/local/$DSYSTEM/bin/bltwish ]; then
              ln -s $bltwish $cdir/$subdir/local/$DSYSTEM/bin/bltwish
            fi
            ls -lL $cdir/$subdir/local/$DSYSTEM/bin/bltwish* | awk '{print "  ",$0}'
          fi
        fi
      fi

    fi
  fi
fi

summary
rm -f $log
#----------------------------------------------------------------------
#               END OF SCRIPT
#----------------------------------------------------------------------
