#!/bin/bash 
#
#   configure -- Build configuration script for Embedthis Products
#
#   Copyright (c) Embedthis Software LLC, 2003-2009. All Rights Reserved.
#
#   This script creates the buildConfig.h, buildConfig.make and buildConfig.sh 
#   configuration files. buildConfig.h is included in every C/C++ source file, 
#   buildConfig.make is included by all makefiles and buildConfig.sh is included 
#   by the bld program and some other scripts.
#
#   The initial default settings are derrived from configuration files in the build directory. 
#
###############################################################################
#
#   Prefix for configuration files generated by configure
#
CONFIG=build/buildConfig

#
#   This programs version
#

CONFIGURE_VERSION=3.5.0

#
#   Default settings
#
BLD_DEFAULTS=standard

#
#   O/S has cygpath (Windows)
#
HAS_CYGPATH=0

#
#   Use Microsoft Visual Studio Compiler (over cygwin cc)
#
HOST_HAS_MSCL=0
BUILD_HAS_MSCL=0

#
#   GCC uses -mtune
#
HOST_HAS_MTUNE=0
BUILD_HAS_MTUNE=0

#
#   GCC supports -fnostack-protector
#
HOST_HAS_STACK_PROTECTOR=0
BUILD_HAS_STACK_PROTECTOR=0

#
#   Product name to configure
#
PRODUCT=

###############################################################################
#
#   Check the software installation and O/S
#

checkSetup() {

    #
    #   Windows path conversion utility
    #
    type -p cygpath >/dev/null 2>&1
    if [ $? = 0 ] ; then
        HAS_CYGPATH=1
    else
        HAS_CYGPATH=0
    fi

    #
    #   Ensure we can write to key directories
    #
    for d in . build build/bin bin obj lib
    do
        if [ ! -d $d ]
        then
            echo "Missing required directory \"$d\"" 1>&2
            echo "Create this directory and retry" 1>&2
            exit 255
        fi
        echo >$d/.test 2>/dev/null
        if [ $? != 0 ]
        then
            echo "Can't write to $d" 1>&2
            echo "You do not have write permission for the $d directory." 1>&2
            echo "Log in as root or modify the permissions of this directory" 1>&2
            echo "and all its files." 1>&2
            exit 255
        fi
        rm -f $d/.test
    done

    if [ ! -f ./configure -o ! -d build ]
    then
        echo "configure: You must be in the top source directory." 1>&2
        exit 255
    fi

    #
    #   Convert paths to be absolute with a drive spec on windows
    #
    BLD_TOP=`canonPath .`
    BLD_TOOLS_DIR=${BLD_TOP}/build/bin
    BLD_BIN_DIR=${BLD_TOP}/bin

    if [ "$BLD_HOST_OS" = "WIN" ] ; then
        BLD_LIB_DIR=${BLD_BIN_DIR}
        BLD_MOD_DIR=${BLD_BIN_DIR}
    else
        BLD_LIB_DIR=${BLD_TOP}/lib
        BLD_MOD_DIR=${BLD_TOP}/lib
    fi

    #
    #   Sleuth the product. By convention products put a configure.PRODUCT file
    #   under the build directory.
    #
    PRODUCT_LIST=`echo build/configure.* | sed 's/[^. ]*\.//g'`
    if [ "${PRODUCT_LIST%\*}" != "${PRODUCT_LIST}" ]
    then
        echo "Can't find required file: build/configure.*" 1>&2
        echo "Install this file and retry." 1>&2
        exit 255
        
    fi
}


#
#   Link a file. If that fails, copy.
#
linkFile()
{
    source=$1
    dir=`dirname $2`
    base=`basename $2`

    rm -f $2
    if [ "$base" != "$2" ]
    then
        source=`echo $source | sed -e "s^${dir}/^^"`
    fi
    ln -s $source $2 2>/dev/null
    if [ $? != 0 ]
    then
        cp $1 $2
    fi
}


#
#   Set the system configuration. This is called for the host and build configurations.
#
#   Usage: setSystemConfiguration cpu-vendor-os OS UNIX CPU CPU_ARCH WIN DIST
#   The upper case parameters are output parameters.
#
setSystemConfiguration() {

    local system os unix cpu cpuArch windows distribution mode dist rel version

    mode=$1

    system=$1
    os=$2
    unix=$3
    cpu=$4
    cpuArch=$5
    cpuModel=$6
    windows=$7
    distribution=$8
    distributionVersion=$9

    #
    #   Parse the host system configuration
    #
    parseSystem $system $cpu unused $os

    case $os in
    WIN)
        eval ${unix}=0
        eval ${windows}=1
        ;;
    CYGWIN)
        eval ${unix}=1
        eval ${windows}=1
        ;;
    FREEBSD)
        eval ${unix}=1
        eval ${windows}=0
        ;;
    LINUX)
        eval ${unix}=1
        eval ${windows}=0
        ;;
    SOLARIS*)
        eval ${unix}=1
        eval ${os}=SOLARIS
        eval ${windows}=0
        ;;
    MACOSX)
        eval ${unix}=1
        eval ${windows}=0
        ;;
    VXWORKS)
        eval ${unix}=0
        eval ${windows}=0
        ;;
    *)
        eval ${unix}=0
        eval ${windows}=0
        ;;
    esac

    #
    #   Determine the CPU family
    #
    case ${cpu} in
    arm*|strongarm*)
        eval ${cpuArch}=MPR_CPU_ARM
        ;;
    m68k**)
        eval ${cpuArch}=MPR_CPU_68K
        ;;
    mips*)
        eval ${cpuArch}=MPR_CPU_MIPS
        ;;
    ppc*|powerpc*)
        eval ${cpuArch}=MPR_CPU_PPC
        ;;
    sparc*|sparclite)
        eval ${cpuArch}=MPR_CPU_SPARC
        ;;
    x86_64*|amd64)
        eval ${cpuArch}=MPR_CPU_IX64
        ;;
    x86*|i?86*)
        eval ${cpuArch}=MPR_CPU_IX86
        ;;
    xscale*)
        eval ${cpuArch}=MPR_CPU_XSCALE
        ;;
    simnt|sim)
        eval ${cpuArch}=MPR_CPU_SIMNT
        ;;
    simsparc)
        eval ${cpuArch}=MPR_CPU_SIMSPARC
        ;;
    sh*)
        eval ${cpuArch}=MPR_CPU_SH4
        ;;
    universal)
        eval ${cpuArch}=MPR_CPU_UNIVERSAL
        ;;
    *)
        eval ${cpuArch}=MPR_CPU_UNKNOWN
        echo "configure: CPU architecture unknown. Porting $BLD_PRODUCT is required. " 1>&2
        exit 2
        ;;
    esac

    eval ${cpuModel}=`echo ${cpu} | sed 's/[a-zA-Z-]*//'`

    #
    #   Determine the O/S distribution. This is quite a bit of spelunking.
    #
    #   /etc/debian_version
    #   /etc/redhat-release
    #   /etc/fedora-release
    #   /etc/gentoo-release
    #   /etc/SuSE-release
    #   /etc/slackware-release, /etc/slackware-version
    #   /etc/debian-release, /etc/debian-version
    #   /etc/release # Solars
    #   /etc/yellowdog-release
    #   /etc/mandrake-release
    dist="unknown"
    version="Unknown"

    if [ $os = WIN -o $os = CYGWIN ] ; then

        # Microsoft Windows XP [Version 5.1.2600]
        # Microsoft Windows [Version 6.0.6000]

        rel=`cmd /c ver | tail -1`
        version=`echo $rel | sed 's/.*Version //;s/]//' | awk '{ print $1 }'`
        version=${version%%.*}
        #  if [ "$version" = 6 ] ; then
        #      dist=vista
        #  elif [ "$version" = 5 ] ; then
        #      dist=xp
        #  fi
        dist=MS

    elif [ $os = LINUX ] ; then
        if [ -f /etc/redhat-release ] ; then 

            case `cat /etc/redhat-release` in
            Fedora*)
                # Fedora Core release 4 (Stentz)
                # Fedora Core release 6 (Zod)
                # Fedora Core release 5.9 (FC6 Test3)
                version=`cat /etc/redhat-release | awk '{ print $4 }'` 
                dist="fedora"
                ;;
            "Red Hat Linux"*)
                # Red Hat Linux release 9 (Shrike)
                version=`cat /etc/redhat-release | awk '{ print $5 }'` 
                dist="rhl"
                ;;
            "Red Hat Enterprise"*)
                # Red Hat Enterprise Linux ES release 3 (Taroon Update 7)
                # Red Hat Enterprise Linux ES release 4 (Nahant Update 4)
                version=`cat /etc/redhat-release | awk '{ print $7 }'` 
                dist="rhel"
                ;;
            esac
        fi
        if [ -f /etc/SuSE-release ] ; then
            dist=suse
            # version=`cat /proc/version | awk '{ print $3 }'`
            # version=`cat /etc/issue | awk '{ print $2 }'`
            # kernelVersion=`cat /proc/version | awk '{ print $3 }'`
            version=`cat /etc/SuSE-release | head -1 | awk '{ print $2 }'`
        fi
        if [ -f /etc/gentoo-release ] ; then
            dist=suse
            # version=`cat /proc/version | awk '{ print $3 }'`
            # version=`cat /etc/issue | awk '{ print $2 }'`
            # kernelVersion=`cat /proc/version | awk '{ print $3 }'`
            version=`cat /etc/gentoo-release | head -1 | awk '{ print $5 }'`
        fi
        if [ -f /etc/debian_version ] ; then
            cat /proc/version | grep -i ubuntu >/dev/null
            if [ $? = 0 ] ; then
                dist=ubuntu
            else
                dist=debian
            fi
            # kernelVersion=`cat /proc/version | awk '{ print $3 }'`
            if [ -f /etc/lsb-release ] ; then
                version=`cat /etc/lsb-release | grep RELEASE | sed 's/.*=//'`
            elif [ -f /etc/issue ] ; then
                version=`cat /etc/issue | awk '{ print $2 }'`
            fi
        fi

    elif [ $BLD_HOST_OS = MACOSX ] ; then
        version=`sw_vers | grep ProductVersion | awk '{ print $2 }'`
        #dist=`sw_vers | grep ProductName | awk '{ print $2 }'`
        dist="Apple"

    elif [ $os = MACOSX ] ; then
        version=`sw_vers | grep ProductVersion | awk '{ print $2 }'`
        #dist=`sw_vers | grep ProductName | awk '{ print $2 }'`
        dist="Apple"


    elif [ $os = VXWORKS ] ; then

        dist="vxworks"
        #
        #   Need to wait until we've found the vxworks toolkit before
        #   determining the version
        #
    fi

    eval ${distribution}=\"${dist}\"
    eval ${distributionVersion}=\"${version}\"
}


#
#   Prompt the user to select from a set of options.
#   Usage: ans=`prompt "prompt" "default" "option1" "option2" ...`
#   Returns the selection or default if <ENTER> is pressed
#
prompt() {
    echo -e "\n${1}:" 1>&2 ; shift
    local default=$1 ; shift
    local count=1
    local index=1
    local o ans
    for o in $*
    do
        echo "    $count. $o" 1>&2
        [ "$o" = "$default" ] && index=$count
        eval option_${count}=$o
        count=`expr $count + 1`
    done
    echo -n "Enter selection [$index] : " 1>&2
    read ans
    if [ "$ans" = "" ]
    then echo $default
    else
        eval echo $`echo option_${ans}`
    fi
}


#
#   Ensure users have set required environment variables
#
checkEnv() {

    #
    #   Warn about a search path set to the root directory.
    #
    if [ "$SEARCH_PATH" = "/" -o "$SEARCH_PATH" = "." -o "$SEARCH_PATH" = "c:/" ] ; then
        echo "Can't set SEARCH_PATH to \"/\" or \".\""
        exit 255
    fi

    #
    #   If the user is overriding CC but doesn't set CXX, set it to the same
    #
    if [ "$CC" != "" -a "$CXX" = "" ] ; then
        CXX="$CC"
    fi
    if [ "$LD" != "" -a "$LDXX" = "" ] ; then
        LDXX="$CC"
    fi
    if [ -f "${BLD_TOP}/.embedthis" ] ; then
        BLD_EMBEDTHIS=1
    else
        BLD_EMBEDTHIS=0
    fi
}


#
#   Final checks on completion.
#
postCheck() {

    if [ "$BLD_HOST_OS" = "LINUX" -o "$BLD_HOST_OS" = "SOLARIS" -o "$BLD_HOST_OS" = "FREEBSD" ]
    then
        if [ "`echo $LD_LIBRARY_PATH | grep bin`" = "" ]
        then
            if [ $quiet = 0 -a ! -f ${BLD_TOP}/.embedthis ]
            then
            echo "  # If you wish to debug natively in the build tree,"
            echo "  # you will need to set the LD_LIBRARY_PATH environment variable to include "
            echo "  # the \"bin\" directory. Try:"
            echo -e "  #\n  #    export LD_LIBRARY_PATH=`pwd`/bin"
            echo -e "  #\n  # See \"INSTALL.TXT\" for details."
            echo -e "  #"
            fi
        fi
    fi
    for f in bld config.guess config.sub makedep priv
    do
        chmod +x "${BLD_TOP}/build/bin/$f"
    done
}


#
#   Post generation. Prepare for make by updating a key bootstrap file.
#
postGen() {
    #
    #   Stop make regenerating dependencies if Embedthis debug build
    #
    if [ -f "${BLD_TOP}/.embedthis" -a "$BLD_TYPE" = "DEBUG" ] ; then
        touch build/src/.makedep
    fi
}


#
#   Create the buildConfig header
#
createConfigHeader()
{
    NAME=$1
    FILE=$2

    rm -f $NAME
    if [ "$NAME" = $CONFIG.h ]
    then
        cat >$FILE <<!EOF_CONFIG_HEADER_H
/*  
 *  ${NAME} -- Build configuration file.
 *  
 *  WARNING: DO NOT EDIT. This file is generated by configure.
 *
 *  Use "./configure --help" to learn how to use the configure script to 
 *  customize the configuration. 
 */ 

!EOF_CONFIG_HEADER_H
    elif [ "$NAME" = $CONFIG.sh ]
    then
        cat >$FILE <<!EOF_CONFIG_HEADER_SH
#   
#   ${NAME} -- Build configuration file.
#   
#   WARNING: DO NOT EDIT. This file is generated by configure.
#   
#   Use "./configure --help" to learn how to use the configure script to 
#   customize the configuration.
#   
################################################################################

!EOF_CONFIG_HEADER_SH
    else
        cat >$FILE <<!EOF_CONFIG_HEADER_MAKE
#   
#   ${NAME} -- Build configuration file.
#   
#   WARNING: DO NOT EDIT. This file is generated by configure.
#   
#   Use "./configure --help" to learn how to use the configure script to 
#   customize the configuration.
#   
################################################################################

!EOF_CONFIG_HEADER_MAKE
    fi
}


#
#   Usage: parseSystem in-String out-cpu out-vendor out-os
#
parseSystem() {

    system=`eval echo \\$$1`
    cpu=${system%%-*}
    vendor=${system##${cpu}-}
    vendor=${vendor%%-*}
    kernel=${system##${cpu}-${vendor}-}
    os=${kernel##*-}
    kernel=${kernel%%-*}

    if [ "$kernel" != "" ]
    then
        os=$kernel
    fi

    os=`echo $os | tr '[:lower:]' '[:upper:]'`

    case "${os}" in
    CYGWIN*)
        os=CYGWIN
        ;;
    FREEBSD*)
        os=FREEBSD
        ;;
    SOLARIS*)
        os=SOLARIS
        ;;
    DARWIN*)
        os=MACOSX
        ;;
    esac

    eval ${2}=$cpu
    eval ${3}=$vendor
    eval ${4}=$os

    lowOS=`echo $os | tr '[:upper:]' '[:lower:]'`
    eval ${1}="${cpu}-${vendor}-${lowOS}"

    [ "$verbose" -gt 2 ] && echo System set to "${cpu}-${vendor}-${lowOS}"
}


#
#   Convert a path to a canonical form: absolute (Windows: with drive spec)
#
canonPath() {

    dir="$1"
    if [ "$dir" = "" ] ; then
        echo "$dir"
        return
    fi
    if [ $HAS_CYGPATH = 1 ] ; then
        #
        #   These conversions will ensure we get a drive spec and that we have
        #    forward slashes instead of back slashes
        #
        d=`cygpath -am "${dir}"`
        d=`cygpath -u "${d}"`
        cygpath -am "${d}"
        return
    fi

    if [ "${dir##..}" != "${dir}" ] ; then
        cd .. ; echo `pwd`${dir##..} ; cd - >/dev/null 2>&1
    elif [ "${dir##.}" != "${dir}" ] ; then
        echo `pwd`${dir##.}
    elif [ "${dir##/}" != "${dir}" ] ; then
        # Absolute
        echo "$dir"
    else
        # Relative
        echo `pwd`${dir}
    fi
}


#
#   Convert a path to a form relative to $BLD_TOP. Used because gnu make on 
#   windows can't handle drive specs in dependencies.
#
relativePath() {

    local base home dir i d c oldd parents
    local count ccount seg commonDir commonLevels

    home="$PWD"

    dir="$1"

    if [ "BLD_HOST_OS" = "WIN" ] ; then
        dir=`canonPath "$dir" | tr '[A-Z]' '[a-z]'`
        cwd=`canonPath "$PWD" | tr '[A-Z]' '[a-z]'`
    else
        dir=`canonPath "$dir"`
        cwd=`canonPath "$PWD"`
    fi

    if [ "$dir" = "$cwd" ] ; then
        echo "\${BLD_TOP}"
		return
    fi
    if [ "$dir" != "${dir/BLD_TOP/}" ] ; then
        echo "$dir"
        return
    fi

    #
    #   Find longest common dir portion
    #
    declare -a dseg
    d="$dir"
    i=0
    while [ "$d" != "${d##*/}" ] ; do
        seg=${d%%/*}                    # Extract first path segment
        dseg[$i]="${seg}"
        d=${d#*/}                       # Strip first path segment
        i=$((i + 1))
    done
    dseg[$i]="${d}"
    
    declare -a cseg
    c="$cwd"
    i=0
    while [ "$c" != "${c##*/}" ] ; do
        seg=${c%%/*}                    # Extract first path segment
        cseg[$i]="${seg}"
        c=${c#*/}                       # Strip first path segment
        i=$((i + 1))
    done
    cseg[$i]="${c}"
    
    count=${#dseg[*]}
    ccount=${#cseg[*]}

    if [ $count -gt $ccount ] ; then
        count=$ccount
    fi

    if [ "${BLD_HOST_OS}" = "WIN" ] ; then
        if [ "${dseg[0]}" != "${cseg[0]}" ] ; then
            echo "Path ${dir} on different drive" >/dev/tty
            echo "to the current drive" >/dev/tty
            echo "This configuration is not supported. Aborting." >/dev/tty
            exit 255
        fi
    fi

    #
    #   Find common parent dirs
    #
    commonDir=""
    i=0
    while [ $i -lt $count ] ; do
        [ "${dseg[$i]}" != "${cseg[$i]}" ] && break
        commonDir="$commonDir/${dseg[$i]}"
        i=$((i + 1))
    done
    commonDir="${commonDir#/*}"
    commonLevels=$i

    #
    #   Find how many levels up to common parent for cwd
    #
    parents=""
    i=$commonLevels
    while [ $i -lt ${#cseg[*]} ] ; do
        parents="../$parents"
        i=$((i + 1))
    done

    base=`echo $dir | sed "s!^$commonDir!!"`
    echo "\${BLD_TOP}/${parents}$base" | sed 's!\/\/!\/!g'
}


#
#   Remove an old prefix from a path and prepend a new prefix
#
remapDir() {

    dir="$1"
    oldPath="$2"
    newPath="$3"

    if [ $HAS_CYGPATH = 1 ] ; then
        dir=`cygpath -m "$dir"`
        oldPath=`cygpath -m "$oldPath"`
        newPath=`cygpath -m "$newPath"`
    fi

    if [ "${dir##$oldPath}" != "$dir" ]
    then
        echo "${newPath}${dir##$oldPath}"
    else
        echo "${dir}"
    fi
}


#
#   Probe for a tool. Search in SEARCH_PATH, then TOOL_SEARCH_PATH, then PATH
#
#       usage: probleTool tool varName cmd searchPath mode required
#
probeTool() 
{
    local OLD_PATH tool searchPath path varName cmd searchPath item mode required

    #
    #   Note: varName is of the form BLD_[HOST|BUILD]_TOOL
    #
    tool=${1}
    varName=${2}
    cmd="${3}"
    searchPath="${4}"
    mode="${5}"
    required="${6}"

    OLD_PATH=$PATH

    eval ${varName}=\"\"
    item=Tool

    [ "$verbose" != 0 ] && echo "probeTool: tool: $tool cmd: \"$cmd\" mode: $mode"

    if [ "$cmd" = "true" ] ; then
        eval ${varName}=\"$cmd\"
        return 1
    fi

    if [ "$cmd" = "" -a "$required" = 1 ] ; then
        echo "Probing for tool $tool but BLD_${mode}_${tool} ${mode} is undefined"
        exit 255
    fi

    #
    #   Test the default tool setting (if it has a qualified path only)
    #   default will either be the tool name or a full path 
    #
    if [ "${cmd}" != "${cmd#*/*}" ] 
    then
        if [ -f "$cmd" ] ; then
            [ "$verbose" != 0 ] && echo "$item $tool found with absolute path at $cmd"
            eval ${varName}=\"$cmd\"
            return 1
        fi
    fi

    #
    #   Try the cmd relative to the override search path
    #
    if [ "$SEARCH_PATH" != "" ] ; then
        [ "$verbose" != 0 ] && echo -e "\nProbing for $cmd in override path $SEARCH_PATH\n"
        PATH="$SEARCH_PATH"
        path=`type -p "$cmd" 2>/dev/null`
        status=$?
        PATH=$OLD_PATH
        if [ "$status" = 0 -a -x "$path" ] 
        then
            [ "$verbose" != 0 ] && echo "$item $tool found in override search paths at $path"
            eval ${varName}=\"$path\"
            return 1
        else
            if [ "$verbose" != 0 ] ; then
                echo -e "\n$item $tool not found in override search paths: $SEARCH_PATH"
            fi
        fi
    fi


    #
    #   Now look in the tool search paths. Must append PATH so we can still find unix utils.
    #
    #
    [ "$verbose" != 0 ] && echo -e "\nProbing for $cmd in search path $searchPath\n"
    PATH="$searchPath"
    path=`type -p "$cmd" 2>/dev/null`
    status=$?
    PATH=$OLD_PATH
    if [ "$status" = 0 -a -x "$path" ] 
    then
        [ "$verbose" != 0 ] && echo "$item $tool found in search paths at $path"
        eval ${varName}=\"$path\"
        return 1
    else
        if [ "$verbose" != 0 ] ; then
            echo -e "\n$item $tool not found in search paths: $searchPath"
        fi
    fi


    #
    #   Lastly, try the cmd relative to the current user environment
    #
    [ "$verbose" != 0 ] && echo -e "\nProbing for $cmd in user PATH $PATH\n"
    path=`type -p "$cmd" 2>/dev/null`
    status=$?
    if [ "$status" = 0 -a -x "$path" ] 
    then
        #
        #   Special case to avoid /usr/bin/link when using MS VS cl
        #
        if [ "$HAS_MSCL" = 0 -o "$path" != "/usr/bin/link" ] ; then
            [ "$verbose" != 0 ] && echo "$item $tool found in environment at $path"
            eval ${varName}=\"$path\"
            return 1
        fi
    else
        if [ "$verbose" != 0 ] ; then
            echo "$item $cmd not found in environment"
        fi
    fi


    if [ "$required" = 1 ] ; then
        echo -e "\nCan't find $tool command $cmd" 1>&2
        if [ "$verbose" = 1 ] ; then
            echo "tool $tool"
            echo "varName $varName"
            echo "cmd $cmd"
            echo searchPath $searchPath
        fi
        MISSING_TOOLS="$MISSING_TOOLS $tool"
    fi

    return 0
}


#
#   Probe for an SDK
#
#       usage: probleSdk sdk varName dir searchPath required
#
probeSdk() 
{
    local sdk searchPath path dir searchPath varName probe d file status

    sdk=${1}
    varName=${2}
    dir="${3}"
    searchPath="${4}"
    required="${5}"

    [ "$verbose" != 0 ] && echo -e "\nprobeSdk: Probing to discover $varName $dir"

    eval probe=\$${sdk}_PROBE

    #
    #   Test the tool setting (if it has a qualified path only)
    #
    if [ "${dir}" != "${dir#*/*}" ] 
    then
        if [ -f "${dir}/$probe" ]
        then
            [ "$verbose" != 0 ] && echo "SDK $sdk found with absolute path"
            path="${dir}"
        fi
    fi

    #
    #   Try the sdk relative to the override search path
    #
    if [ "$path" = "" -a "$SEARCH_PATH" != "" ] ; then
        SAVE_IFS=$IFS
        IFS=":"
        for d in $SEARCH_PATH
        do
            [ "${d}" = "/" ] && d=
            for file in ${d}/${probe}
            do
                [ "$verbose" != 0 ] && echo "probeSdk probe for \"$probe\" at \"$d\""
                if [ -f "${file}" ] ; then
                    # echo $file | sed "s!/${probe}!!"
                    [ "${d}" = "" ] && d=/
                    [ "$verbose" != 0 ] && echo "SDK $sdk found at $d in SEARCH_PATH"
                    path="$d"
                    break
                fi
            done

            if [ "$path" = "" ] ; then
                #
                #   Now search up to 3 levels under the directory
                #
                [ "$verbose" != 0 ] && echo "probeSdk probe directory $d for $probe"
                file=`find "${d}" -maxdepth 4 -type f | grep -i "${probe}" | tail -1` 
                if [ $? = 0 -a "$file" != "" ] ; then
                    if [ -f "${file}" ] ; then
                        [ "${d}" = "" ] && d=/
                        [ "$verbose" != 0 ] && echo "SDK $sdk found at $d under SEARCH_PATH"
                        path="$d"
                        break
                    else
                        echo -e "\nInternal error. Cannot find \"$file\""
                    fi
                fi
            fi
            [ "${path}" != "" ] && break
        done
        IFS="$SAVE_IFS"
    fi

    #
    #   Now look in the extra tool search paths
    #
    if [ "$path" = "" ] ; then
        SAVE_IFS=$IFS
        IFS=":"
        for d in $searchPath 
        do
            [ "${d}" = "/" ] && d=
            for file in ${d}/${probe}
            do
                [ "$verbose" != 0 ] && echo "probeSdk probe for \"$probe\" at \"$d\""
                if [ -f "${file}" ] ; then
                    # echo $file | sed "s!/${probe}!!"
                    [ "${d}" = "" ] && d=/
                    [ "$verbose" != 0 ] && echo "SDK $sdk found at $d in SDK_SEARCH_PATH"
                    path="$d"
                    break
                fi
            done

            if [ "$path" = "" ] ; then
                #
                #   Now search up to 3 levels under the directory
                #
                [ "$verbose" != 0 ] && echo "probeSdk probe directory $d for $probe"
                file=`find "${d}" -maxdepth 4 -type f | grep -i "${probe}" | tail -1` 
                status=$?
                if [ $status = 0 -a "$file" != "" ] ; then
                    if [ -f "${file}" ] ; then
                        [ "${d}" = "" ] && d=/
                        [ "$verbose" != 0 ] && echo "SDK $sdk found at $d under SDK_SEARCH_PATH"
                        path="$d"
                        break
                    else
                        echo "Cannot find $file"
                    fi
                fi
            fi
            [ "${path}" != "" ] && break
        done
        IFS="$SAVE_IFS"
    fi

    if [ "$path" != "" ] ; then
        [ "$verbose" != 0 ] && echo "SDK $sdk found in extra search paths at $path"
        eval ${varName}=\"$path\"
        eval ${varName}_FULL_PATH=\"$file\"
        eval ${varName}_WITHOUT_PROBE=\"`echo $file | sed "s!/${probe}!!"`\"
        return
    fi

    if [ "$required" = 1 ] ; then
        echo -e "\nCan't find SDK $sdk\n" 1>&2
    fi

    if [ "$verbose" = 1 ] ; then
        echo "sdk $sdk"
        echo "varName $varName"
        echo "dir $dir"
        echo searchPath $searchPath
    fi

    if [ "$required" = 1 ] ; then
        MISSING_SDKS="$MISSING_SDKS $sdk"
    fi
}


probePackage()
{
    local searchPath dir d path

    searchPath="${1}"
    dir="${2}"

    SAVE_IFS=$IFS
    IFS=":"
    for d in $searchPath 
    do
        [ "${d}" = "/" ] && d=
        for path in ${d}/${dir}
        do
            if [ -x "${path}" ] ; then
                echo ${path}
                return
            fi
        done
    done
    IFS="$SAVE_IFS"
}


#
#   Convert the search path into a normal PATH style with ":" separators
#
convertPath() 
{
    if [ "$1" != "" ] ; then

        [ "$verbose" != 0 ] && echo "ConvertPath expanding $1" >/dev/tty

        echo $1 | sed "s/[  ]'/=/g" | tr "=" "\n" | sed "s/'//g" |
        sed "s/ /?/g" | while read x
        do
            # [ "$verbose" != 0 ] && echo -e "\nConvert: \"$x\" => \n    \"`eval ls -d1 "$x" 2>/dev/null | sort`\"" >/dev/tty
            eval ls -d1 "$x" 2>/dev/null | sort
        done | tr '\n' :
    fi
}


#
#   Find all required sdks and tools
#
findToolsAndSdks()
{
    [ "$verbose" != 0 ] && echo SEARCH_PATH was $SEARCH_PATH
    SEARCH_PATH=`convertPath "$SEARCH_PATH"`
    if [ "$SEARCH_PATH" = "." ] ; then
        SEARCH_PATH=
    fi
    [ "$verbose" != 0 ] && echo -e "Override search path is \"$SEARCH_PATH\"\n"


    #
    #   Search for BUILD sdks and tools
    #
    findSdks  BUILD "$BLD_REQUIRED_BUILD_SDKS" "$BLD_OPTIONAL_BUILD_SDKS" "$SDK_SEARCH_PATH"

    BUILD_TOOL_SEARCH_PATH=`convertPath "$BUILD_TOOL_SEARCH_PATH"`
    [ "$verbose" != 0 ] && echo -e "\nBuild tool search path is $BUILD_TOOL_SEARCH_PATH"

    findTools BUILD "$BLD_REQUIRED_BUILD_TOOLS" "$BLD_OPTIONAL_BUILD_TOOLS" "$BUILD_TOOL_SEARCH_PATH"

    #
    #   Seach for HOST sdks and tools. Search for SDKs first as they will be added to the 
    #   tool search paths
    #
    findSdks  HOST "$BLD_REQUIRED_SDKS" "$BLD_OPTIONAL_SDKS" "$SDK_SEARCH_PATH"

    TOOL_SEARCH_PATH=`convertPath "$TOOL_SEARCH_PATH"`
    [ "$verbose" != 0 ] && echo -e "\nTool search path is $TOOL_SEARCH_PATH"

    findTools HOST "$BLD_REQUIRED_TOOLS" "$BLD_OPTIONAL_TOOLS" "$TOOL_SEARCH_PATH"

    findPackages

    #
    #   Report
    #
    if [ "$MISSING_SDKS" != "" ]
    then
        echo -e "\nMissing required SDKs: $MISSING_SDKS." 1>&2
        echo -e "\nAborting configure." 1>&2
        echo -e "\nCheck your PATH environment and if required, edit the SDK search paths in" 1>&2
        echo -e "build/tools.config. Alternatively, you can define SEARCH_PATH to contain extra" 1>&2
        echo -e "directories to search. Then run configure again.\n" 1>&2
        exit 255
    fi

    if [ "$MISSING_TOOLS" != "" ]
    then
        echo -e "\nMissing required tools: $MISSING_TOOLS." 1>&2
        echo -e "\nAborting configure." 1>&2
        echo -e "\nCheck your PATH environment and if required, edit the tool search paths in" 1>&2
        echo -e "build/tools.config. Alternatively, you can define SEARCH_PATH to contain extra" 1>&2
        echo -e "directories to search. Then run configure again.\n" 1>&2
        exit 255
    fi
}


#
#   findSdks mode required optional searchPath
#
findSdks()
{
    local mode sdk dir varName searchPath

    mode=$1
    required="$2"
    optional="$3"
    searchPath="$4"

    if [ "$optional" != "" ] ; then
        [ $quiet = 0 ] && echo -en "  # Search for optional $mode SDKs: "
        for sdk in $optional
        do
            varName=BLD_${mode}_${sdk}
            eval dir=\$${varName}
            [ $mode = HOST ] && echo -n `basename "$sdk"` ""
            probeSdk "$sdk" "$varName" "${dir}" "$searchPath" 0
        done
        echo
    fi

    if [ "$required" != "" ] ; then
        [ $quiet = 0 ] && echo -en "  # Search for required $mode SDKs: "
        for sdk in $required
        do
            varName=BLD_${mode}_${sdk}
            eval dir=\$${varName}
            [ $mode = HOST ] && echo -n `basename "$sdk"` ""
            probeSdk "$sdk" "$varName" "${dir}" "$searchPath" 1
        done
        echo
    fi
}


#
#   findTools mode required optional searchPath
#
findTools()
{
    local mode required optional

    mode=$1
    required="$2"
    optional="$3"
    searchPath="$4"

    #
    #   Search for optional tools
    #   Not a failure if the optional tools can't be found
    #
    if [ "$optional" != "" ] ; then
        echo -n "  # Search for optional $mode tools: "
        for tool in $optional 
        do
            varName=BLD_${mode}_${tool}
            eval cmd=\$${varName}
            [ "$cmd" = "" ] && continue
            echo -n "$tool " 
            probeTool "$tool" "$varName" "${cmd}" "$searchPath" $mode 0
        done
        echo
    fi

    if [ "$required" != "" ] ; then
        echo -en "  # Search for required $mode tools: "
        for tool in $required 
        do
            varName=BLD_${mode}_${tool}
            eval cmd=\$${varName}

            [ "$cmd" = "" ] && continue
            echo -n "$tool "
            probeTool "$tool" "$varName" "${cmd}" "$searchPath" $mode 1
        done
        echo
    fi
}


#
#   Test various compiler options
#
checkCompilerOptions()
{
    local   kind file cc cpu file hasGcc hasStackProtector hasMtune

    kind=$1

    if [ "$kind" = HOST ] ; then
        os=$BLD_HOST_OS
        cc=$BLD_HOST_CC
        cpu=$BLD_HOST_CPU
        hasStackProtector=HOST_HAS_STACK_PROTECTOR
        hasMtune=HOST_HAS_MTUNE
    else
        os=$BLD_BUILD_OS
        cc=$BLD_BUILD_CC
        cpu=$BLD_BUILD_CPU
        hasStackProtector=BUILD_HAS_STACK_PROTECTOR
        hasMtune=BUILD_HAS_MTUNE
    fi

    if [ $os = CYGWIN -o $os = FREEBSD -o $os = LINUX -o $os = VXWORKS -o $os = MACOSX ] ; then
        hasGcc=1
    else 
        hasGcc=0
    fi

    #
    #   Check for old gcc compilers that can't handle -mtune
    #
    if [ $hasGcc = 1 ] ; then
        file=/tmp/t$$.c
        >${file}
        if [ "$verbose" != 0 ] ; then
            echo -e "  # Checking for compiler -mtune support\n"
            echo "${cc}" -mtune=${cpu} -c $file 
            echo
        fi
        "${cc}" -mtune=${cpu} -c $file >/dev/null 2>&1
        if [ $? = 0 ] ; then
            eval $hasMtune=1
        fi

        if [ "$verbose" != 0 ] ; then
            echo -e "  # Checking for compiler -fno-stack-protector support\n"
            echo "${cc}" -fno-stack-protector -c $file 
            echo
        fi
        "${cc}" -fno-stack-protector -c $file >/dev/null 2>&1
        if [ $? = 0 ] ; then
            eval $hasStackProtector=1
        fi
        rm -f t$$.o ${file}
    fi
}


#
#   Check tool settings and set environment vars by defining variables in buildConfig.*. 
#   Make will interpret these settings and set the PATH, INCLUDE and LIB directories as required.
#
setToolsEnv()
{
    local   file cc version file kind os cc cpu bldPath bldInclude bldLib winSdk VS VS_DOS WIN_SDK cldir

    kind=$1

    if [ "$kind" = HOST ] ; then
        os=$BLD_HOST_OS
        cc=$BLD_HOST_CC
        cpu=$BLD_HOST_CPU
		winSdk=$BLD_HOST_WINSDK
    else
        os=$BLD_BUILD_OS
        cc=$BLD_BUILD_CC
        cpu=$BLD_BUILD_CPU
		winSdk=$BLD_BUILD_WINSDK
    fi

    #
    #   If using VS then set necessary MS VS CL environment variables and define INCLUDE LIB and PATH in buildConfig.*
    #
    if [ $os = WIN -a "$cc" != "" ] ; then

        #
        #   Get the top level Visual Studio installation directory
        #
        VS=`dirname "${cc%/cl*}"`
        cldir=`basename "${cc%/cl*}"`
        VS=`dirname "$VS"`
        VS_DOS=`cygpath -m "$VS"`
		WIN_SDK=`cygpath -m "$winSdk"`

        if [ "${cc%VC98*}" != "${cc}" ] ; then
            #
            #   Visual Studio 6 defines. 
            #
            bldPath="$VS/Common/MSDev98/bin:$VS/VC98/BIN:$VS/Common/IDE:$VS/Common/Tools/WinNT:$VS/Common/Tools"
            bldInclude="$VS_DOS/VC98/ATLMFC/INCLUDE;$VS_DOS/VC98/INCLUDE;$VS_DOS/VC98/MFC/INCLUDE"
            bldLib="$VS_DOS/VC98/LIB;$VS_DOS/VC98/MFC/LIB"
            version=12

        elif [ "${cc%Visual Studio .NET 2003*}" != "${cc}" ] ; then
            #
            #   Visual Studio .NET 2003
            #
            bldPath="$VS/Common7/IDE:$VS/Vc7/BIN:$VS/Common7/Tools:$VS/Common7/Tools/bin:$VS/Vc7/PlatformSDK/bin"
            bldInclude="$VS_DOS/Vc7/ATLMFC/INCLUDE;$VS_DOS/Vc7/INCLUDE;$VS_DOS/Vc7/PlatformSDK/include"
            bldLib="$VS_DOS/Vc7/ATLMFC/LIB;$VS_DOS/Vc7/LIB;$VS_DOS/Vc7/PlatformSDK/lib"
            version=13

        elif [ "${cc%Visual Studio 8*}" != "${cc}" -a "$cldir" != AMD64 ] ; then
            #
            #   Visual Studio 2005
            #
            bldPath="$VS/Common7/IDE:$VS/VC/BIN:$VS/Common7/Tools:$VS/Common7/Tools/bin:$VS/VC/PlatformSDK/bin:$VS/SDK/v2.0/bin:$VS/VC/VCPackages"
            bldInclude="$VS_DOS/VC/ATLMFC/INCLUDE;$VS_DOS/VC/INCLUDE;$VS_DOS/VC/PlatformSDK/include;$VS_DOS/SDK/v2.0/include"
            bldLib="$VS_DOS/VC/ATLMFC/LIB;$VS_DOS/VC/LIB;$VS_DOS/VC/PlatformSDK/lib;$VS_DOS/SDK/v2.0/lib;$VS_DOS/PlatformSDK/include/mfc"
            version=14

        elif [ "${cc%Visual Studio 9*}" != "${cc}" -a "$cldir" != AMD64 ] ; then
            #
            #   Visual Studio 2009
            #
            bldPath="$VS/Common7/IDE:$VS/VC/BIN:$VS/Common7/Tools:$VS/SDK/v2.0/bin:$VS/VC/VCPackages"
            bldInclude="$VS_DOS/VC/INCLUDE"
            bldLib="$VS_DOS/VC/LIB"
            version=15

			#
			#	Add the Windows SDK
			#
            bldPath="$bldPath:$BLD_HOST_WINSDK/bin"
            bldInclude="$bldInclude;$WIN_SDK/include"
            bldLib="$bldLib;$WIN_SDK/LIB"

        elif [ "${cc%PlatformSDK*}" != "${cc}" ] ; then
            #
            #   Platform Compiler (need to go up 3 more dirs)
            #
			VS=`dirname "$VS"`
			VS=`dirname "$VS"`
			VS=`dirname "$VS"`
			VS_DOS=`cygpath -m "$VS"`
            bldPath="$VS/PlatformSDK/bin/x86/AMD64"
            bldInclude="$VS_DOS/PlatformSDK/include/crt"
            bldLib="$VS_DOS/PlatformSDK/LIB/AMD64"
            version=15

			#
			#	Add the Windows SDK
			#
            bldPath="$bldPath:$BLD_HOST_WINSDK/bin"
            bldInclude="$bldInclude;$WIN_SDK/include"
            bldLib="$bldLib;$WIN_SDK/LIB"

		else
			echo "Microsoft CL Compiler not found"
			exit 255
        fi
        eval ${kind}_MSCL_VERSION="$version"
        eval ${kind}_HAS_MSCL=1
    fi

    if [ "$os" = VXWORKS ] ; then
        if [ "$bldPath" = "" ] ; then
            bldPath="`dirname $cc`"
        else
            bldPath="$bldPath:`dirname $cc`"
        fi
    fi

    if [ "$kind" = HOST ] ; then
        BLD_HOST_PATH="$bldPath"
        BLD_HOST_INCLUDE_PATH="$bldInclude"
        BLD_HOST_LIB_PATH="$bldLib"
    else
        BLD_BUILD_PATH="$bldPath"
        BLD_BUILD_INCLUDE_PATH="$bldInclude"
        BLD_BUILD_LIB_PATH="$bldLib"
    fi
}


#
#   Return a unique set of words without changing the order
#
unique() {
    local result
    set -f 
    for word in $*
    do 
        case " $result " in 
        *\ $word\ *) ;; 
        *) result=${result:+"$result "}$word 
        ;; 
        esac 
    done 
    echo $result 
    set +f
}


#
#   Output the --help usage message
#
standardHelp()
{
    cat <<!EOF_HELP

usage: configure [OPTIONS]...

Installation directories:
  When doing a "make install" the --prefix and --binDir are used. The other
  directory options are not yet fully supported.

  --prefix=PATH            Set the default base installation directory for 
                           the product.
                           Default is /etc/${BLD_PRODUCT} on Unix, /${BLD_PRODUCT} on Windows.
  --binDir=PATH            Set the directory for binaries.
                           "make install" will install tools to this location.
  --docDir=PATH            Set the directory for the documentation.
  --manDir=PATH            Set the directory for the manual pages (UNIX only).
  --samDir=PATH            Set the directory for the samples.
  --incDir=PATH            Set the directory for include headers.
  --libDir=PATH            Set the directory for development libraries.
  --srcDir=PATH            Set the directory for source files.

System Types:
  --build=BUILD            Configure for building on BUILD [Default is guessed].
                             BUILD format is cpu-vendor-os.
  --host=HOST              Cross-compile for ${BLD_PRODUCT} to run on HOST
                             [Default is set to BUILD]. HOST format is
                             cpu-vendor-os.
                            
                           WARNING: WindRiver calls the build system the host system
                           and the host system, they call the target.

General Features:
  --buildNumber=NUMBER     Set the build number part of the version (1.0.0.X).
  --defaults=FILE          Set the file name of the defaults master in conf
  --help                   Display this message.
  --cygwin                 Use the cygwin compiler in preference if a Microsoft
                           Visual Studio compiler is also installed.
  --name=NAME              Set the full product name (BLD_NAME define).
  --product=NAME           Set the one word (no spaces) name of the product.
  --quiet, -q, --silent    Run quietly.
  --setLibVersion=X.X.X    Set the shared library version number.
  --setVersion=X.X.X       Set the product version number.
  --tool \"TOOL PATH\"     Set a build tool path. Build tools are CC, JDK, ANT,
                           WTK, BREW, TORNADO. Not all these tools are required.
  --type=BUILD             Set the build type to (DEBUG|RELEASE).
  --tune=KIND              Set the tune kind to (SIZE|BALANCED|SPEED).

Optional Build Features: (See more features below)
  --disable-FEATURE        Do not include the FEATURE.
  --enable-FEATURE         Include the FEATURE.

  --enable-assert          Build with assert checking.
  --disable-assert         Do not build with assert checking.

  --enable-doc             Build the documentation.
  --disable-doc            Do not build the documentation.

  --enable-floating-point  Build with floating point support in JavaScript.
  --disable-floating-point Do not include floating point support.

  --enable-legacy-api      Build with legacy API support for backwards
                           compatibility. 
  --disable-legacy-api     Do not build with legacy API support.

  --enable-log             Build with error logging.
  --disable-log            Do not build with error logging.

  --enable-mmu             Build for systems with virutal memory (MMU)
  --disable-mmu            Build for systems without virutal memory (no MMU)

  --enable-multi-thread    Build multi-threaded.
  --disable-multi-thread   Build single threaded.

  --enable-rom-fs          Build with the ability to load files from ROM.
  --disable-rom-fs         Do not build the ability to load files from ROM.

  --enable-samples         Build the samples
  --disable-samples        Do not build the samples

  --enable-shared          Build an ${BLD_PRODUCT} shared library and program. [default]
                           Use either --enable-shared or --enable-static but not both.
  --disable-shared         Do not build an ${BLD_PRODUCT} shared library and program.

  --enable-static          Build a static ${BLD_PRODUCT} library and program. [default]
  --disable-static         Do not build a static ${BLD_PRODUCT} library and program.

  --enable-test            Build all unit tests.
  --disable-test           Do not build unit tests.

Environment Variables:

Some important environment variables that may be defined to control
building for the destination host. Note that environment variables will have
no effect when passed into makefiles, they must be passed via configure.

  ANT                      Builder for java command.
  AR                       Archiver command
  BREW                     Brew SDK directory.
  CC                       C/C++ compiler command.
  DOXYGEN                  Doxygen documentation generation command.
  JAVAC                    Java compiler command.
  JDK                      Java SDK directory.
  JAR                      Java archive tool
  LD                       Linker command.
  MUNCH                    The vxworks munch.bat command.
  MT                       The windows manifest command.
  RANLIB                   The ranlib command.
  NM                       The nm command.
  STRIP                    The strip command.
  VXWORKS                  Wind River VxWorks SDK directory.
  WTK                      Sun Java Wireless Toolkit directory.

  CFLAGS                   Compiler flags for compilation
  DFLAGS                   Compiler preprocessor defines for compilation
  IFLAGS                   Preprocessor and include flags.
  JFLAGS                   Java flags
  LDFLAGS                  Linker flags. For example: use -L<dir> to specify
                           where to find libraries in non-standard directories.

These variables are for native compilation of tools needed by the build
process.
  BUILD_CC                 C/C++ compiler to use for native /local compilation
                           and linking on the build system.
  BUILD_LD                 Linker to use for native /local linking on the
                           build system.
  BUILD_MT                 Windows manifest command.

Tool search paths are defined by PATH, SEARCH_PATH and by the paths in 
build/tools.config.
!EOF_HELP
}


#
#   Create a buildConfig.* file. NAME is the first arg.
#
createConfig()
{
    local enabled 

    NAME=$1

    rm -f $NAME
    createConfigHeader $NAME $NAME

    BLD_HOST_CPU_UPPER=`echo $BLD_HOST_CPU | tr '[a-z]' '[A-Z]'`
    BLD_BUILD_CPU_UPPER=`echo $BLD_BUILD_CPU | tr '[a-z]' '[A-Z]'`

    if [ "${BLD_HOST_SYSTEM}" != "${BLD_BUILD_SYSTEM}" ] ; then
        BLD_CROSS=1
    else 
        BLD_CROSS=0
    fi

    [ $NAME = $CONFIG.sh -o $NAME = $CONFIG.h ] && IFQUOTE='"'

    cat >>$NAME <<!EOF_CONFIG1
#
#   Key Product Settigns
#
BLD_PRODUCT="$BLD_PRODUCT"
BLD_NAME="$BLD_NAME"
BLD_VERSION="$BLD_VERSION"
BLD_NUMBER="$BLD_NUMBER"
BLD_TYPE="$BLD_TYPE"
BLD_TUNE=$BLD_TUNE
BLD_DEFAULTS="$BLD_DEFAULTS"
BLD_PACKAGES="$BLD_PACKAGES"
BLD_EMBEDTHIS=$BLD_EMBEDTHIS

BLD_REQUIRED_TOOLS="$BLD_REQUIRED_TOOLS"
BLD_OPTIONAL_TOOLS="$BLD_OPTIONAL_TOOLS"
BLD_REQUIRED_SDKS="$BLD_REQUIRED_SDKS"
BLD_OPTIONAL_SDKS="$BLD_OPTIONAL_SDKS"

BLD_REQUIRED_BUILD_TOOLS="$BLD_REQUIRED_BUILD_TOOLS"
BLD_OPTIONAL_BUILD_TOOLS="$BLD_OPTIONAL_BUILD_TOOLS"
BLD_REQUIRED_BUILD_SDKS="$BLD_REQUIRED_BUILD_SDKS"
BLD_OPTIONAL_BUILD_SDKS="$BLD_OPTIONAL_BUILD_SDKS"

#
#   Other Product Settings
#
BLD_COMPANY="$BLD_COMPANY"
BLD_DEBUG=$BLD_DEBUG
BLD_DIRS="$BLD_DIRS"
BLD_CLEAN_INSTALL="$BLD_CLEAN_INSTALL"
BLD_LICENSE="$BLD_LICENSE"
BLD_COMMERCIAL="$BLD_COMMERCIAL"

#
#   Host and Build System Settings.
#
BLD_HOST_SYSTEM="$BLD_HOST_SYSTEM"
BLD_BUILD_SYSTEM="$BLD_BUILD_SYSTEM"
BLD_CROSS="$BLD_CROSS"

#
#   Host System Settings 
#
BLD_HOST_OS=${IFQUOTE}$BLD_HOST_OS${IFQUOTE}
BLD_HOST_CPU_ARCH=$BLD_HOST_CPU_ARCH
BLD_HOST_CPU="$BLD_HOST_CPU"
BLD_HOST_CPU_UPPER="$BLD_HOST_CPU_UPPER"
BLD_HOST_CPU_MODEL="$BLD_HOST_CPU_MODEL"
BLD_HOST_DIST="$BLD_HOST_DIST"
BLD_HOST_DIST_VER="$BLD_HOST_DIST_VER"
BLD_HOST_UNIX=$BLD_HOST_UNIX
BLD_HOST_WIN=$BLD_HOST_WIN
!EOF_CONFIG1

if [ "$BLD_HOST_OS" = VXWORKS ] ; then
    echo "BLD_BUILD_CPU_VX=$BLD_BUILD_CPU_VX" >>$NAME
    echo "BLD_BUILD_SYSTEM_VX=$BLD_BUILD_SYSTEM_VX" >>$NAME
fi

    cat >>$NAME <<!EOF_CONFIG2

#
#   Build System Settings for Build Tools
#
BLD_BUILD_OS=${IFQUOTE}$BLD_BUILD_OS${IFQUOTE}
BLD_BUILD_CPU_ARCH=$BLD_BUILD_CPU_ARCH
BLD_BUILD_CPU=$BLD_BUILD_CPU
BLD_BUILD_CPU_UPPER=$BLD_BUILD_CPU_UPPER
BLD_BUILD_CPU_MODEL=$BLD_BUILD_CPU_MODEL
BLD_BUILD_UNIX=$BLD_BUILD_UNIX
BLD_BUILD_WIN=$BLD_BUILD_WIN

#
#   System and Installation Directories
#
BLD_ROOT_PREFIX="$BLD_ROOT_PREFIX"
BLD_PREFIX="$BLD_PREFIX"
BLD_BIN_PREFIX="$BLD_BIN_PREFIX"
BLD_DOC_PREFIX="$BLD_DOC_PREFIX"
BLD_INC_PREFIX="$BLD_INC_PREFIX"
BLD_LIB_PREFIX="$BLD_LIB_PREFIX"
BLD_MAN_PREFIX="$BLD_MAN_PREFIX"
BLD_SAM_PREFIX="$BLD_SAM_PREFIX"
BLD_SRC_PREFIX="$BLD_SRC_PREFIX"

#
#   Compiler options
#
BLD_HOST_CC_MTUNE=$HOST_HAS_MTUNE
BLD_HOST_CC_STACK_PROTECTOR=$HOST_HAS_STACK_PROTECTOR
BLD_HOST_CC_MSCL=$HOST_HAS_MSCL
BLD_HOST_CC_CL_VERSION=$HOST_MSCL_VERSION

BLD_BUILD_CC_MTUNE=$BUILD_HAS_MTUNE
BLD_BUILD_CC_STACK_PROTECTOR=$BUILD_HAS_STACK_PROTECTOR
BLD_BUILD_CC_MSCL=$BUILD_HAS_MSCL
BLD_BUILD_CC_CL_VERSION=$BUILD_MSCL_VERSION

#
#   Other misc options
#
!EOF_CONFIG2

    createFeatureConfig $NAME

    cat >>$NAME <<!EOF_CONFIG2a
################################################################################
#
#   Programs for building
#
!EOF_CONFIG2a

    for t in $BLD_REQUIRED_TOOLS $BLD_REQUIRED_SDKS $BLD_OPTIONAL_TOOLS $BLD_OPTIONAL_SDKS
    do
        eval value=\$BLD_HOST_${t}
        echo BLD_HOST_${t}=\"$value\" >>$NAME

        if [ $HAS_CYGPATH = 1 ]
        then
            if [ "$value" != "" ] ; then
                value=`cygpath -m "$value"`
                echo BLD_HOST_${t}_DOSPATH=\"$value\" >>$NAME
            else
                echo BLD_HOST_${t}_DOSPATH=\"$value\" >>$NAME
            fi
        fi
    done
    echo >>$NAME


    for t in $BLD_REQUIRED_BUILD_TOOLS $BLD_REQUIRED_BUILD_SDKS $BLD_OPTIONAL_BUILD_TOOLS \
        $BLD_OPTIONAL_BUILD_SDKS
    do
        eval value=\$BLD_BUILD_${t}
        echo BLD_BUILD_${t}=\"$value\" >>$NAME

        if [ $HAS_CYGPATH = 1 ]
        then
            if [ "$value" != "" ] ; then
                value=`cygpath -m "$value"`
                echo BLD_BUILD_${t}_DOSPATH=\"$value\" >>$NAME
            else
                echo BLD_BUILD_${t}_DOSPATH=\"$value\" >>$NAME
            fi
        fi
    done
    echo >>$NAME


    cat >>$NAME <<!EOF_CONFIG2b

#
#   Build flags
#
!EOF_CONFIG2b

    for t in $BLD_REQUIRED_FLAGS
    do
        eval value=\$BLD_BUILD_${t}FLAGS
        eval value=\"$value\"
        echo BLD_BUILD_${t}FLAGS=\"$value\" >>$NAME

        eval value=\$BLD_HOST_${t}FLAGS
        eval value=\"$value\"
        echo BLD_HOST_${t}FLAGS=\"$value\" >>$NAME
    done

    cat >>$NAME <<!EOF_CONFIG2c

#
#   Native file extensions
#
BLD_BUILD_ARCH="$BLD_BUILD_ARCH"
BLD_BUILD_EXE="$BLD_BUILD_EXE"
BLD_BUILD_OBJ="$BLD_BUILD_OBJ"
BLD_BUILD_PIOBJ="$BLD_BUILD_PIOBJ"
BLD_BUILD_CLASS="$BLD_BUILD_CLASS"
BLD_BUILD_SHLIB="$BLD_BUILD_SHLIB"
BLD_BUILD_SHOBJ="$BLD_BUILD_SHOBJ"

#
#   File extensions for the host
#
BLD_HOST_ARCH="$BLD_HOST_ARCH"
BLD_HOST_EXE="$BLD_HOST_EXE"
BLD_HOST_OBJ="$BLD_HOST_OBJ"
BLD_HOST_PIOBJ="$BLD_HOST_PIOBJ"
BLD_HOST_CLASS="$BLD_HOST_CLASS"
BLD_HOST_SHLIB="$BLD_HOST_SHLIB"
BLD_HOST_SHOBJ="$BLD_HOST_SHOBJ"

#
#   Output directories
#   
!EOF_CONFIG2c

    echo 'BLD_TOOLS_DIR="${BLD_TOP}/build/bin"' >>$NAME
    echo 'BLD_BIN_DIR="${BLD_TOP}/bin"' >>$NAME
    if [ "$BLD_HOST_OS" = "WIN" ] ; then
        echo 'BLD_LIB_DIR="${BLD_TOP}/bin"' >>$NAME
        echo 'BLD_MOD_DIR="${BLD_TOP}/bin"' >>$NAME
    else
        echo 'BLD_LIB_DIR="${BLD_TOP}/lib"' >>$NAME
        echo 'BLD_MOD_DIR="${BLD_TOP}/lib"' >>$NAME
    fi
    echo 'BLD_INC_DIR="${BLD_TOP}/src/include"' >>$NAME
    echo 'BLD_EXP_OBJ_DIR="${BLD_TOP}/obj"' >>$NAME

    echo >>$NAME
    echo BLD_ABS_BIN_DIR=\"`canonPath ${BLD_BIN_DIR}`\" >>$NAME
    if [ "$BLD_HOST_OS" = "WIN" ] ; then
        echo BLD_ABS_LIB_DIR=\"`canonPath ${BLD_BIN_DIR}`\" >>$NAME
        echo BLD_ABS_MOD_DIR=\"`canonPath ${BLD_BIN_DIR}`\" >>$NAME
    else
        echo BLD_ABS_LIB_DIR=\"`canonPath ${BLD_LIB_DIR}`\" >>$NAME
        echo BLD_ABS_MOD_DIR=\"`canonPath ${BLD_MOD_DIR}`\" >>$NAME
    fi
    echo BLD_ABS_INC_DIR=\"`canonPath ${BLD_TOP}/src/include`\" >>$NAME
    echo BLD_ABS_EXP_DIR=\"`canonPath ${BLD_TOP}/obj`\" >>$NAME

    echo >>$NAME

    cat >>$NAME <<!EOF_CONFIG2d
#
#   Select Native or cross development flags
#   If BUILD_NATIVE is set to 0, then switch to doing a cross without recursing.
#
!EOF_CONFIG2d

    if [ $NAME = $CONFIG.make ] ; then
        echo 'BUILD_NATIVE ?= 1' >>$NAME
        if [ "${BLD_CROSS}" = 1 ] ; then
            echo 'BUILD_CROSS ?= 1' >>$NAME
        fi
        echo '' >>$NAME

        echo 'BUILD_HOST_TARGETS:=0' >>$NAME
        echo 'ifeq ($(BLD_CROSS),0)' >>$NAME
        echo 'BUILD_HOST_TARGETS:=1' >>$NAME
        echo 'endif' >>$NAME
        echo 'ifneq ($(BUILDING_CROSS),1)' >>$NAME
        echo 'BUILD_HOST_TARGETS:=1' >>$NAME
        echo 'endif' >>$NAME
        echo '' >>$NAME

        echo 'ifneq ($(BUILDING_CROSS),1)' >>$NAME

    elif [ $NAME = $CONFIG.sh ] ; then
        echo ': ${BUILD_NATIVE:=1}' >>$NAME
        if [ "${BLD_CROSS}" = 1 ] ; then
            echo ': ${BUILD_CROSS:=1}' >>$NAME
        fi
        echo -e 'if [ "${BUILDING_CROSS}" != 1 ] ; then' >>$NAME
    else
        echo -e ' #if !BUILDING_CROSS' >>$NAME
    fi

    if [ $NAME != $CONFIG.xh ]
    then
        cat >>$NAME <<!EOF_CONFIG3a
    #
    #   Native build settings
    #
    $BLD_BUILD_OS=1
    BLD_OS=${IFQUOTE}$BLD_BUILD_OS${IFQUOTE}
    BLD_CPU_ARCH=$BLD_BUILD_CPU_ARCH
    BLD_CPU="$BLD_BUILD_CPU"
    BLD_CPU_UPPER="$BLD_BUILD_CPU_UPPER"
    BLD_CPU_MODEL="$BLD_BUILD_CPU_MODEL"
    BLD_DIST="$BLD_BUILD_DIST"
    BLD_DIST_VER="$BLD_BUILD_DIST_VER"
    BLD_UNIX_LIKE=$BLD_BUILD_UNIX
    BLD_WIN_LIKE=$BLD_BUILD_WIN

    #
    #   Build programs for building tools to run natively on the build system
    #
!EOF_CONFIG3a

        for t in $BLD_REQUIRED_BUILD_TOOLS $BLD_REQUIRED_BUILD_SDKS $BLD_OPTIONAL_BUILD_TOOLS $BLD_OPTIONAL_BUILD_SDKS
        do
            eval value=\$BLD_BUILD_${t}
            echo "    BLD_${t}=\"$value\"" >>$NAME
        done

        cat >>$NAME <<!EOF_CONFIG3b

    #
    #   Build flags 
    #
!EOF_CONFIG3b

        for t in $BLD_REQUIRED_FLAGS
        do
            eval value=\$BLD_BUILD_${t}FLAGS
            echo "    BLD_${t}FLAGS=\"$value\"" >>$NAME
        done

        cat >>$NAME <<!EOF_CONFIG3c

    #
    #   File extensions
    #
    BLD_ARCH="$BLD_BUILD_ARCH"
    BLD_EXE="$BLD_BUILD_EXE"
    BLD_CLASS="$BLD_BUILD_CLASS"
    BLD_SHLIB="$BLD_BUILD_SHLIB"
    BLD_SHOBJ="$BLD_BUILD_SHOBJ"

    #
    #   Compiler options
    #
    BLD_CC_MTUNE="$BUILD_HAS_MTUNE"
    BLD_CC_STACK_PROTECTOR="$BUILD_HAS_STACK_PROTECTOR"
    BLD_CC_MSCL="$BUILD_HAS_MSCL"
    BLD_CC_CL_VERSION="$BUILD_MSCL_VERSION"

!EOF_CONFIG3c
        if [ "${BLD_FEATURE_STATIC}" = "0" ] ; then
            echo "    BLD_LIB=\"${BLD_BUILD_SHOBJ}\"" >>$NAME
            echo "    BLD_OBJ=\"$BLD_BUILD_PIOBJ\"" >>$NAME
            echo "    BLD_PIOBJ=\"$BLD_BUILD_PIOBJ\"" >>$NAME
        else
            echo "    BLD_LIB=\"${BLD_BUILD_ARCH}\"" >>$NAME
            echo "    BLD_OBJ=\"$BLD_BUILD_OBJ\"" >>$NAME
            echo "    BLD_PIOBJ=\"$BLD_BUILD_PIOBJ\"" >>$NAME
        fi
    fi

    #
    #   Set necessary INCLUDE and LIB environment variables for MS VS CL
    #
    if [ $NAME != $CONFIG.h ] ; then
        echo -e "\n    #\n    #   Setup tool environment variables\n    #" >>$NAME
        if [ "$BLD_BUILD_OS" = WIN ]
        then
            for var in INCLUDE LIB 
            do
                eval value=\"\$BLD_BUILD_${var}_PATH\"
                if [ "${NAME}" = "$CONFIG.sh" ]
                then
                    echo "    export" $var=\"${value}\;\$$var\" >>$NAME
                else
                    echo "    export" $var:=${value}\;\$$var >>$NAME
                fi
                echo >>$NAME
            done
        fi

        top="$BLD_TOP"
        if [ $HAS_CYGPATH = 1 ] ; then
            top=`cygpath "${top}"`
        fi

        if [ "${BLD_HOST_OS}" = "LINUX" ] ; then
            SYS_DIR=":/sbin:/usr/sbin:"
        fi
        if [ "${NAME}" = "$CONFIG.sh" ] ; then
            echo "    export PATH=\"\${PATH}:${top}/bin:${top}/lib:${top}/lib:${top}/build/bin${SYS_DIR}:${BLD_BUILD_PATH}\"" >>$NAME
        else
            echo "    export PATH:=${top}/bin:${top}/lib:${top}/lib:${top}/build/bin${SYS_DIR}:${BLD_BUILD_PATH}:\$(PATH)" >>$NAME
        fi
    fi

    if [ $NAME = $CONFIG.h ]
    then
        echo -e '\n #else' >>$NAME
    else
        echo -e '\nelse' >>$NAME
    fi


    if [ $NAME != $CONFIG.xh ]
    then
        cat >>$NAME <<!EOF_CONFIG4a
    #
    #   Host (target) system
    #
    $BLD_HOST_OS=1
    BLD_OS=${IFQUOTE}$BLD_HOST_OS${IFQUOTE}
    BLD_CPU_ARCH=$BLD_HOST_CPU_ARCH
    BLD_CPU="$BLD_HOST_CPU"
    BLD_CPU_UPPER="$BLD_HOST_CPU_UPPER"
    BLD_CPU_MODEL="$BLD_HOST_CPU_MODEL"
    BLD_DIST="$BLD_HOST_DIST"
    BLD_DIST_VER="$BLD_HOST_DIST_VER"
    BLD_UNIX_LIKE=$BLD_HOST_UNIX
    BLD_WIN_LIKE=$BLD_HOST_WIN

    #
    #   Build programs on the host system
    #
!EOF_CONFIG4a

        for t in $BLD_REQUIRED_TOOLS $BLD_REQUIRED_SDKS $BLD_OPTIONAL_TOOLS $BLD_OPTIONAL_SDKS
        do
            eval value=\$BLD_HOST_${t}
            echo "    BLD_${t}=\"$value\"" >>$NAME
        done

        cat >>$NAME <<!EOF_CONFIG4b

    #
    #   Build flags for the host
    #
!EOF_CONFIG4b
        for t in $BLD_REQUIRED_FLAGS
        do
            eval value=\$BLD_HOST_${t}FLAGS
            eval value=\"$value\"
            echo "    BLD_${t}FLAGS=\"$value\"" >>$NAME
        done

        cat >>$NAME <<!EOF_CONFIG4c

    #
    #   File extensions
    #
    BLD_ARCH="$BLD_HOST_ARCH"
    BLD_EXE="$BLD_HOST_EXE"
    BLD_CLASS="$BLD_HOST_CLASS"
    BLD_SHLIB="$BLD_HOST_SHLIB"
    BLD_SHOBJ="$BLD_HOST_SHOBJ"

    #
    #   Compiler options
    #
    BLD_CC_MTUNE="$HOST_HAS_MTUNE"
    BLD_CC_STACK_PROTECTOR="$HOST_HAS_STACK_PROTECTOR"
    BLD_CC_MSCL="$HOST_HAS_MSCL"
    BLD_CC_CL_VERSION="$HOST_MSCL_VERSION"

!EOF_CONFIG4c

    if [ "${BLD_FEATURE_STATIC}" = "0" ] ; then
        echo "    BLD_LIB=\"${BLD_HOST_SHOBJ}\"" >>$NAME
        echo "    BLD_OBJ=\"$BLD_HOST_PIOBJ\"" >>$NAME
        echo "    BLD_PIOBJ=\"$BLD_HOST_PIOBJ\"" >>$NAME
    else
        echo "    BLD_LIB=\"${BLD_HOST_ARCH}\"" >>$NAME
        echo "    BLD_OBJ=\"$BLD_HOST_OBJ\"" >>$NAME
        echo "    BLD_PIOBJ=\"$BLD_HOST_PIOBJ\"" >>$NAME
    fi

    if [ $NAME != $CONFIG.h ] ; then
        if [ $NAME = $CONFIG.sh ] ; then
            echo -e "\n    #\n    #    Bend output directories\n     #">>$NAME
            echo '    BLD_BIN_DIR="${BLD_BIN_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_LIB_DIR="${BLD_LIB_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_MOD_DIR="${BLD_MOD_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_OBJ_DIR="${BLD_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_EXP_OBJ_DIR="${BLD_EXP_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME

            echo '    BLD_ABS_BIN_DIR="${BLD_ABS_BIN_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_LIB_DIR="${BLD_ABS_LIB_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_MOD_DIR="${BLD_ABS_MOD_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_OBJ_DIR="${BLD_ABS_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_EXP_OBJ_DIR="${BLD_ABS_EXP_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME

        elif [ $NAME = $CONFIG.make ] ; then
            echo -e "\n    #\n    #   Bend output directories\n    #">>$NAME
            echo '    BLD_BIN_DIR := "${BLD_BIN_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_LIB_DIR := "${BLD_LIB_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_MOD_DIR := "${BLD_MOD_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_OBJ_DIR := "${BLD_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_EXP_OBJ_DIR := "${BLD_EXP_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME

            echo '    BLD_ABS_BIN_DIR := "${BLD_ABS_BIN_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_LIB_DIR := "${BLD_ABS_LIB_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_MOD_DIR := "${BLD_ABS_MOD_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_OBJ_DIR := "${BLD_ABS_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
            echo '    BLD_ABS_EXP_OBJ_DIR := "${BLD_ABS_EXP_OBJ_DIR}/${BLD_HOST_SYSTEM}"' >>$NAME
        fi

        #
        #   Set necessary INCLUDE and LIB environment variables for MS VS CL
        #
        echo -e "\n    #\n    #   Setup tool environment variables\n    #" >>$NAME
        if [ "$BLD_HOST_OS" = WIN ]
        then
            for var in INCLUDE LIB 
            do
                eval value=\"\$BLD_HOST_${var}_PATH\"
                if [ "${NAME}" = "$CONFIG.sh" ]
                then
                    echo "    export" $var=\"${value}\;\$$var\" >>$NAME
                else
                    echo "    export" $var:=${value}\;\$$var >>$NAME
                fi
                echo >>$NAME
            done
        fi

        top="$BLD_TOP"
        if [ $HAS_CYGPATH = 1 ] ; then
            top=`cygpath "${top}"`
        fi

        if [ "${BLD_HOST_OS}" = "LINUX" ] ; then
            SYS_DIR=":/sbin:/usr/sbin:"
        fi
        if [ "${NAME}" = "$CONFIG.sh" ] ; then
            echo "    export PATH=\"\${PATH}:${top}/bin:${top}/lib:${top}/lib:${top}/build/bin${SYS_DIR}:${BLD_HOST_PATH}\"" >>$NAME
        else
            echo "    export PATH:=\$(PATH):${top}/bin:${top}/lib:${top}/lib:${top}/build/bin${SYS_DIR}:${BLD_HOST_PATH}" >>$NAME
        fi
    fi
    echo >>$NAME


    [ $NAME = $CONFIG.make ] && echo -e 'endif\n' >>$NAME
    [ $NAME = $CONFIG.sh ] && echo -e 'fi\n' >>$NAME
    [ $NAME = $CONFIG.h ] && echo -e ' #endif' >>$NAME
fi

if [ $NAME = $CONFIG.make ] ; then
    echo 'EXPORT_OBJECTS ?= 1' >>$NAME
    echo 'ifeq ($(EXPORT_OBJECTS),1)' >>$NAME
    echo '  BLD_OBJ_DIR := $(BLD_EXP_OBJ_DIR)' >>$NAME
    echo 'else' >>$NAME
    echo '  BLD_OBJ_DIR := .' >>$NAME
    echo 'endif' >>$NAME
    echo '' >>$NAME

elif [ $NAME = $CONFIG.sh ] ; then
    echo 'if [ "${EXPORT_OBJECTS}" = 1 ] ; then' >>$NAME
    echo '  BLD_OBJ_DIR=${BLD_EXP_OBJ_DIR}' >>$NAME
    echo 'else' >>$NAME
    echo '  BLD_OBJ_DIR=.' >>$NAME
    echo 'fi' >>$NAME
    echo '' >>$NAME
fi

if [ "$BLD_HOST_OS" = VXWORKS ] ; then
    if [ "${NAME}" = "$CONFIG.sh" ] ; then
        echo export WIND_HOME=\"${WIND_HOME}\" >>$NAME
        echo export WIND_BASE=\"${WIND_BASE}\" >>$NAME
        echo export WIND_HOST_TYPE=\"${WIND_HOST_TYPE}\" >>$NAME
    else
        echo export WIND_HOME=${WIND_HOME} >>$NAME
        echo export WIND_BASE=${WIND_BASE} >>$NAME
        echo export WIND_HOST_TYPE=${WIND_HOST_TYPE} >>$NAME
    fi
    echo >>$NAME
fi

for p in $BLD_PACKAGES
do
    p=`echo ${p} | tr '[a-z]' '[A-Z]'`
    eval enabled="\$BLD_FEATURE_${p}"
    if [ "$enabled" != 1 ] ; then 
        echo -e "#\n#   ${p}\n#" >>$NAME
        echo -e "BLD_FEATURE_${p}=0\n" >>$NAME
        continue
    fi
    eval module=$`echo BLD_FEATURE_${p}`
    eval dir=$`echo BLD_${p}_DIR`
    eval libpaths=$`echo BLD_${p}_LIBPATHS`
    eval depLibpaths=$`echo BLD_${p}_DEP_LIBPATHS`
    eval impLibpath=$`echo BLD_${p}_IMP_LIBPATH`

    if [ "$dir" != "" ] ; then
        dir=`relativePath "$dir"`
    fi

    if [ "$impLibpath" != "" ] ; then
        impLibpath=`relativePath "$impLibpath"`
    fi

    eval impLibs=$`echo BLD_${p}_IMP_LIBS`
    eval depLibs=$`echo BLD_${p}_DEP_LIBS`
    eval libs=$`echo BLD_${p}_LIBS`
    eval libName=$`echo BLD_${p}_LIBNAME`
    eval iflags=$`echo BLD_${p}_IFLAGS`
    eval cflags=$`echo BLD_${p}_CFLAGS`
    eval dflags=$`echo BLD_${p}_DFLAGS`
    eval jflags=$`echo BLD_${p}_JFLAGS`
    eval ldflags=$`echo BLD_${p}_LDFLAGS`
    eval extra=$`echo BLD_${p}_EXTRA`

    echo -e "#\n#   ${p}\n#" >>$NAME
    echo BLD_FEATURE_${p}=${module} >>$NAME

    impLibs=`echo $impLibs | sed 's/^ //'`
    depLibs=`echo $depLibs | sed 's/^ //'`
    depLibs=`unique $depLibs`
    depLibpaths=`unique $depLibpaths`
    libs=`unique $libs`
    libpaths=`unique $libpaths`

    if [ "$dir" = "" ] ; then
        echo BLD_${p}_INBUILT=1 >>$NAME
    else
        echo BLD_${p}_INBUILT=0 >>$NAME
        eval echo BLD_${p}_DIR=\'${dir}\' | sed 's/=/="/;s/$/"/' >>$NAME
    fi
    if [ "$impLibpath" != "" ] ; then
        eval echo BLD_${p}_IMP_LIBPATH=\'${impLibpath}\' | sed 's/=/="/;s/$/"/' >>$NAME
    fi
    if [ "$impLibs" != "" ] ; then
        echo BLD_${p}_IMP_LIBS=\'${impLibs}\' >>$NAME
    fi
    if [ "$depLibpaths" != "" ] ; then
        eval echo BLD_${p}_DEP_LIBPATHS=\'${depLibpaths}\' | sed 's/=/="/;s/$/"/' >>$NAME
    fi
    if [ "$depLibs" != "" ] ; then
        echo BLD_${p}_DEP_LIBS=\'${depLibs}\' >>$NAME
    fi
    if [ "$libpaths" != "" ] ; then
        eval echo BLD_${p}_LIBPATHS=\'${libpaths}\' | sed 's/=/="/;s/$/"/' >>$NAME
    fi
    if [ "$libs" != "" ] ; then
        echo BLD_${p}_LIBS=\'${libs}\' >>$NAME
    fi
    if [ "$iflags" != "" ] ; then
        echo BLD_${p}_IFLAGS=\'${iflags}\' >>$NAME
    fi
    if [ "$cflags" != "" ] ; then
        echo BLD_${p}_CFLAGS=\'${cflags}\' >>$NAME
    fi
    if [ "$dflags" != "" ] ; then
        echo BLD_${p}_DFLAGS=\'${dflags}\' >>$NAME
    fi
    if [ "$jflags" != "" ] ; then
        echo BLD_${p}_JFLAGS=\'${jflags}\' >>$NAME
    fi
    if [ "$ldflags" != "" ] ; then
        echo BLD_${p}_LDFLAGS=\'${ldflags}\' >>$NAME
    fi
    if [ "$extra" != "" ] ; then
        echo BLD_${p}_EXTRA=\'${extra}\' >>$NAME
    fi
    echo >>$NAME
done
}


#
#   Add a reference for an external package
#
addExternalPackage() {
    local pkg path f upperPkg lowerPkg

    pkg="$1"
    path="$2"

    upperPkg=`echo ${pkg} | tr '[a-z]' '[A-Z]'`
    lowerPkg=`echo ${pkg} | tr '[A-Z]' '[a-z]'`

    if [ "${BLD_PACKAGES/${lowerPkg}/}" = "$BLD_PACKAGES" ] ; then
        BLD_PACKAGES="$lowerPkg $BLD_PACKAGES"
    fi
    eval "BLD_${pkg}"=1

    f="${BLD_TOP}/build/packages/${lowerPkg}"
    if [ ! -f "${f}" ] ; then
        echo "Can't find required package description file: $pkg"
        MISSING_PACKAGES="$PACKAGES $tool"
        exit 255
    else
        eval "BLD_FEATURE_${upperPkg}"=1
        eval "BLD_${upperPkg}_DIR"="$path"
    fi
}


#
#   Read the package description file
#
findPackages() {
    local f pkg upperPkg enabled

    for pkg in $BLD_PACKAGES
    do
        f="${BLD_TOP}/build/packages/${pkg}"
        upperPkg=`echo ${pkg} | tr '[a-z]' '[A-Z]'`
        eval enabled=\$BLD_FEATURE_${upperPkg}
        if [ -f "${f}" -a "$enabled" != 0 ] ; then
            eval "BLD_FEATURE_${upperPkg}"=1
            . "${f}"
        fi
    done
}


#
#   Unset all BLD_* variables
#
unsetAll()
{
    f=/tmp/unset$$
    rm -f ${f}
    >$f

    for t in $BLD_REQUIRED_TOOLS $BLD_REQUIRED_SDKS $BLD_OPTIONAL_TOOLS $BLD_OPTIONAL_SDKS
    do
        echo unset BLD_${t} >>$f
        echo unset BLD_HOST_${t} >>$f
    done

    for t in $BLD_REQUIRED_BUILD_TOOLS $BLD_REQUIRED_BUILD_SDKS $BLD_OPTIONAL_BUILD_TOOLS $BLD_OPTIONAL_BUILD_SDKS
    do
        echo unset BLD_${t} >>$f
        echo unset BLD_BUILD_${t} >>$f
    done

    for t in $BLD_REQUIRED_FLAGS
    do
        echo unset BLD_${t}FLAGS >>$f
    done

    . /tmp/unset$$

    rm -f /tmp/unset$$
}


#
#   Save explicit user overrides in variables prefixed with _USER_
#
saveExplicitArgs() {

    >/tmp/configure$$
    env | grep 'BLD_' | while read v 
    do
        echo _USER_${v%%=*}=\"${v#*=}\" >>/tmp/configure$$
    done

    echo "_USER_PATH=\"$PATH\"" >>/tmp/configure$$

    . /tmp/configure$$

    rm -f /tmp/configure$$
}


#
#   Restore explicit user overrides
#
restoreExplicitArgs() {

    >/tmp/configure$$
    set | grep "^_USER_" | while read v ; do
        v="${v#_USER_}"
        echo ${v%%=*}=${v#*=} >>/tmp/configure$$
    done
    . /tmp/configure$$
    rm -f /tmp/configure$$

}


#
#   Try to determine some information about the O/S. We have a chick end egg
#   situation in VxWorks in that until we probe for tools, we don't know the
#   O/S version. For Windows, test if there is a microsoft cl compiler installed. 
#   If so, then switch the OS from CYGWIN to WIN and use the microsoft compiler. 
#   Only do this if the HOST_OS is cygwin and the user has not specified --cygwin.
#
sleuthOsInfo()
{
    local CL tryMsCl searchPath version rereadConfig

    [ "$verbose" != 0 ] && echo -e "\nSDK_SEARCH_PATH was $SDK_SEARCH_PATH"
    SDK_SEARCH_PATH=`convertPath "$SDK_SEARCH_PATH"`
    [ "$verbose" != 0 ] && echo -e "SDK search path is \"$SDK_SEARCH_PATH\"\n"

    #
    #   Just for VxWorks, compute the vxworks build system string
    #
    if [ "$BLD_HOST_OS" = VXWORKS ] ; then
        case $BLD_BUILD_OS in
        WIN|CYGWIN)
            BLD_BUILD_SYSTEM_VX=x86-win32
            ;;
        LINUX)
            BLD_BUILD_SYSTEM_VX=x86-linux
            ;;
        SOLARIS*)
            BLD_BUILD_SYSTEM_VX=solaris2
            ;;
        *)
            echo "$BLD_BUILD_OS is an not a supported O/S for VxWorks cross compilation"
            exit 255
            ;;
        esac
        WIND_HOST_TYPE="$BLD_BUILD_SYSTEM_VX"

        #
        #   Must probe early for the VxWorks SDK so we can determine the dist version
        #
        BLD_HOST_DIST_VER=$version

        [ $quiet = 0 ]  && echo -e "  # Find VxWorks installation ..."
        probeSdk VXWORKS BLD_HOST_VXWORKS "${BLD_HOST_VXWORKS}" "$SDK_SEARCH_PATH" 1

        if [ $HAS_CYGPATH = 1 ] ; then
            WIND_HOME=`cygpath -m "$BLD_HOST_VXWORKS"`
        else
            WIND_HOME="$BLD_HOST_VXWORKS"
        fi

        WIND_HOME=`cygpath -m $WIND_HOME`

        version=`dirname "$BLD_HOST_VXWORKS_FULL_PATH"`/version.h
        if [ -f "$version" ] ; then
            if grep 'RUNTIME_VERSION' $version >/dev/null 2>&1 ; then
                version=`grep '^#define.RUNTIME_VERSION' "$version" | awk '{ print $3 }'`
                WIND_BASE="$BLD_HOST_VXWORKS_WITHOUT_PROBE"
                if [ $HAS_CYGPATH = 1 ] ; then
                    WIND_BASE=`cygpath -m $WIND_BASE`
                fi
            else
                version=`grep '^#define.VXWORKS_VERSION' "$version" | awk '{ print $3 }'`
                WIND_BASE="$WIND_HOME"
            fi
            version=`echo $version | sed 's/"//g'`
        else
            echo "Cant find version.h at $version"
            exit 255
        fi
        WIND_BASE=`cygpath -m $WIND_BASE`
        BLD_HOST_DIST_VER=$version
        export WIND_BASE WIND_HOME
    fi

	tryMsCl=0
	if [ "$FORCE_CYGWIN_CC" != 1 ] ; then
		if [ "$BLD_HOST_OS" = "CYGWIN" -o "$BLD_HOST_OS" = "WIN" -o \
			"$BLD_BUILD_OS" = "CYGWIN" -o "$BLD_BUILD_OS" = "WIN" ] ; then
            tryMsCl=1
        fi
	fi

	if [ $tryMsCl = 1 ] ; then
		[ $quiet = 0 ]  && echo -e "  # Check for compiler ..."
		CL=cl
		searchPath=`convertPath "$TOOL_SEARCH_PATH"`
		probeTool "cl" "CL" "$CL" "$searchPath" BUILD 1
		if [ "$CL" != "" -a "$CL" != "cl" ] ; then
			HAS_MSCL=1
		fi
	fi

	rereadConfig=0
	if [ "$HAS_MSCL" = 1 ] ; then
		#
		#   Found VS cl.exe, so switch OS to WIN
		#
		if [ "$BLD_HOST_OS" = "CYGWIN" -o "$BLD_HOST_OS" = "WIN" ] ; then
			BLD_HOST_SYSTEM="${BLD_HOST_SYSTEM/cygwin/win}"
			setSystemConfiguration BLD_HOST_SYSTEM \
				BLD_HOST_OS BLD_HOST_UNIX BLD_HOST_CPU BLD_HOST_CPU_ARCH \
				BLD_HOST_CPU_MODEL BLD_HOST_WIN BLD_HOST_DIST BLD_HOST_DIST_VER
			rereadConfig=1
        fi

		if [ "$BLD_BUILD_OS" = "CYGWIN" -o "$BLD_BUILD_OS" = "WIN" ] ; then
			BLD_BUILD_SYSTEM="${BLD_BUILD_SYSTEM/cygwin/win}"
			setSystemConfiguration BLD_BUILD_SYSTEM BLD_BUILD_OS \
				BLD_BUILD_UNIX BLD_BUILD_CPU BLD_BUILD_CPU_ARCH \
				BLD_BUILD_CPU_MODEL BLD_BUILD_WIN BLD_BUILD_DIST BLD_BUILD_DIST_VER
			rereadConfig=1
        fi
    fi
	if [ $rereadConfig = 1 ] ; then
		. $BASE
	fi

    #
    #   Add MT as a required tool if using VS 2005 or later for host compilations
    #
    if [ "${CL%Visual Studio 8*}" != "${CL}" ] ; then
        BLD_REQUIRED_TOOLS="$BLD_REQUIRED_TOOLS MT"
        BLD_REQUIRED_BUILD_TOOLS="$BLD_REQUIRED_TOOLS MT"
    elif [ "${CL%Visual Studio 9*}" != "${CL}" ] ; then
        BLD_REQUIRED_TOOLS="$BLD_REQUIRED_TOOLS MT"
        BLD_REQUIRED_BUILD_TOOLS="$BLD_REQUIRED_BUILD_TOOLS MT"
    fi
    if [ "${BLD_HOST_CC%Visual Studio 8*}" != "${BLD_HOST_CC}" ] ; then
        BLD_REQUIRED_TOOLS="$BLD_REQUIRED_TOOLS MT"
    elif [ "${BLD_HOST_CC%Visual Studio 9*}" != "${BLD_HOST_CC}" ] ; then
        BLD_REQUIRED_TOOLS="$BLD_REQUIRED_TOOLS MT"
    fi
}


#
#   Trace information about configured tools and SDKs
#
traceTools() {
    local mode set title found

    mode="$1"
    set="$2"
    title="$3"

    found=0
    for require in $set
    do
        tool=BLD_${mode}_${require}
        eval value=\$${tool}
        if [ "$value" != "" ] ; then
            found=1
        fi
    done

    if [ "$found" = "0" ] ; then
        return
    fi

    echo "  # "
    echo "  # Using ${title}:"
    echo "  # "

    for require in $set
    do
        tool=BLD_${mode}_${require}
        eval value=\$${tool}
        if [ "$value" != "" ] ; then
            printf "  #   %-9s %s\n" "${require}:" "$value"
        fi
    done
}


#
#   Get next command line argument. Uses globals _INDEX, _SWITCH, _ARG.
#
getSwitch()
{
    local i sw arg

    : =${_INDEX:=1}

    _ARG=
    _EQUALS_ARG=
    _SWITCH=

    if [ "${!_INDEX##--}" = "${!_INDEX}" ] ; then
		#
		#	Not a switch
		#
		_INDEX=$((_INDEX + 1))
		return
	fi

	#
	#	Extract the value when the format is: --switch=value
	#
    _SWITCH=${!_INDEX%%=*}
    _EQUALS_ARG=${!_INDEX##*=}
    _INDEX=$((_INDEX + 1))
    if [ "$_EQUALS_ARG" != "$_SWITCH" ] ; then
		_ARG="$_EQUALS_ARG"
	fi
}


###############################################################################
#
#   Main
#
quiet=0
help=0
verbose=0

checkSetup

#
#   Clean past build settings, args and cache
#
rm -f $CONFIG.args
unsetAll

CMD_LINE="$@"


#
#   Pre-parse some switches
#
argc=$#
_INDEX=1
while [ $_INDEX -le $argc ] ; do

    getSwitch "$@"

    case "${_SWITCH}" in
    --build)
        build_system_set=1
        system=`bash build/bin/config.sub ${_ARG}`
        if [ $? != 0 -o "$system" = "" ]
        then
            echo "configure: Can't recognize build system: $_ARG"  1>&2
            exit 2
        fi
        BLD_BUILD_SYSTEM=${system}
        ;;
    --defaults)
        BLD_DEFAULTS=${_ARG}
        if [ ! -f "build/${BLD_DEFAULTS}.defaults" ] ; then
            echo "configure: Can't find build/${BLD_DEFAULTS}.defaults" 1>&2
            exit 2
        fi
        unsetAll
        ;;
    --help)
        help=1
        ;;
    --host)
        host_system_set=1
        system=`bash build/bin/config.sub ${_ARG}`
        if [ $? != 0 -o "$system" = "" ]
        then
            echo "configure: Can't recognize host system configuration: $_ARG"  1>&2
            exit 2
        fi
        BLD_HOST_SYSTEM=${system}
        ;;
    --cygwin)
        FORCE_CYGWIN_CC=1
        ;;
    --product)
        BLD_PRODUCT=${_ARG}
        ;;
    --quiet|-q)
        quiet=1
        ;;
    --tool)
        tool=${_ARG%% *}
        tool=`echo $tool | tr '[a-z]' '[A-Z]'`_PATH
        path=${_ARG#* }
        eval export ${tool}=\"${path}\"
        ;;
    --verbose|-v)
        verbose=1
        ;;
    *)
        ;;
    esac
done

if [ $quiet = 0 ] ; then
    echo -e "\n  #\n  # Running Embedthis Configure $CONFIGURE_VERSION"
    echo -e "  # "
    echo -e "  # Initializing configure ..."
    echo -e "  # Parsing args ..."
fi

#
#   Set the system configuration
#
[ "$BLD_HOST_SYSTEM" = "" ] && BLD_HOST_SYSTEM=`bash build/bin/config.guess`
[ "$BLD_BUILD_SYSTEM" = "" ] && BLD_BUILD_SYSTEM=`bash build/bin/config.guess`
setSystemConfiguration BLD_HOST_SYSTEM \
    BLD_HOST_OS BLD_HOST_UNIX BLD_HOST_CPU BLD_HOST_CPU_ARCH \
    BLD_HOST_CPU_MODEL BLD_HOST_WIN BLD_HOST_DIST BLD_HOST_DIST_VER
setSystemConfiguration BLD_BUILD_SYSTEM BLD_BUILD_OS BLD_BUILD_UNIX \
    BLD_BUILD_CPU BLD_BUILD_CPU_ARCH BLD_BUILD_CPU_MODEL \
    BLD_BUILD_WIN BLD_BUILD_DIST BLD_BUILD_DIST_VER
BASE="build/$BLD_DEFAULTS.defaults"

saveExplicitArgs

#
#   Read the base configuration 
#
. $BASE
[ $quiet = 0 ]  && echo -e "  # Reading standard product configuration build/product.config ..."
[ $quiet = 0 ]  && echo -e "  # Reading build configuration build/$BLD_DEFAULTS.defaults ..."

if [ "$help" = 1 ] ; then
    . build/configure.${BLD_PRODUCT}
    standardHelp
    help
    exit 0
fi

#
#   Load the tools configuartion
#
. build/tools.config

sleuthOsInfo

restoreExplicitArgs

#
#   Read the per-product configuration file
#
. build/configure.${BLD_PRODUCT}

[ "$verbose" != 0 ] && echo -e "\nParse command line args ..."

#
#   Parse all command line args
#
argc=$#
_INDEX=1

while [ $_INDEX -le $argc ] ; do

    getSwitch $@

    case "${_SWITCH}" in
    --binDir)
        BLD_BIN_PREFIX=`canonPath ${_ARG}`
        ;;
    --build)
        # Done above
        ;;
    --buildNumber)
        BLD_NUMBER=${_ARG}
        ;;
    --cygwin)
        # Done above
        ;;
    --defaults)
        # Done above
        ;;
    --disable-assert)
        BLD_FEATURE_ASSERT=0
        ;;
    --disable-doc)
        BLD_FEATURE_DOC=0
        BLD_OPTIONAL_TOOLS=`echo $BLD_OPTIONAL_TOOLS | sed 's/DOXYGEN//'`
        ;;
    --disable-floating-point)
        BLD_FEATURE_FLOATING_POINT=0
        ;;
    --disable-legacy-api)
        BLD_FEATURE_LEGACY_API=0
        ;;
    --disable-log)
        BLD_FEATURE_LOG=0
        ;;
    --disable-mmu)
        BLD_FEATURE_MMU=0
        ;;
    --disable-multi-thread|--disable-multithread)
        BLD_FEATURE_MULTITHREAD=0
        ;;
    --disable-rom-fs|--disable-rom|--disable-romfs)
        BLD_FEATURE_ROMFS=0
        ;;
    --disable-run-as-service)
        BLD_FEATURE_RUN_AS_SERVICE=0
        ;;
    --disable-samples)
        BLD_FEATURE_SAMPLES=0
        ;;
    --disable-shared)
        BLD_FEATURE_STATIC=1
        ;;
    --disable-static)
        BLD_FEATURE_STATIC=0
        ;;
    --disable-test)
        BLD_FEATURE_TEST=0
        ;;
    --enable-assert)
        BLD_FEATURE_ASSERT=1
        ;;
    --enable-doc)
        BLD_FEATURE_DOC=1
        BLD_OPTIONAL_TOOLS=`echo $BLD_OPTIONAL_TOOLS | sed 's/DOXYGEN//'`
        BLD_OPTIONAL_TOOLS=`echo $BLD_OPTIONAL_TOOLS DOXYGEN`
        ;;
    --enable-floating-point)
        BLD_FEATURE_FLOATING_POINT=1
        ;;
    --enable-legacy-api)
        BLD_FEATURE_LEGACY_API=1
        ;;
    --enable-log)
        BLD_FEATURE_LOG=1
        ;;
    --enable-mmu)
        BLD_FEATURE_MMU=1
        ;;
    --enable-multi-thread|--enable-multithread)
        BLD_FEATURE_MULTITHREAD=1
        ;;
    --enable-rom-fs|--enable-rom|--enable-romfs)
        BLD_FEATURE_ROMFS=1
        ;;
    --enable-run-as-service)
        BLD_FEATURE_RUN_AS_SERVICE=1
        ;;
    --enable-samples)
        BLD_FEATURE_SAMPLES=1
        ;;
    --enable-shared|--shared)
        BLD_FEATURE_STATIC=0
        ;;
    --enable-static|--static)
        BLD_FEATURE_STATIC=1
        ;;
    --enable-test)
        BLD_FEATURE_TEST=1
        ;;
    --host)
        # Done above
        ;;
    --docDir)
        BLD_DOC_PREFIX=`canonPath ${_ARG}`
        ;;
    --incDir)
        BLD_INC_PREFIX=`canonPath ${_ARG}`
        ;;
    --libDir)
        BLD_LIB_PREFIX=`canonPath ${_ARG}`
        ;;
    --manDir)
        BLD_MAN_PREFIX=`canonPath ${_ARG}`
        ;;
    --name)
        BLD_NAME=${_ARG}
        ;;
    --prefix)
        BLD_BIN_PREFIX=`remapDir "$BLD_BIN_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_DOC_PREFIX=`remapDir "$BLD_DOC_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_INC_PREFIX=`remapDir "$BLD_INC_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_LIB_PREFIX=`remapDir "$BLD_LIB_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_ROOT_PREFIX=`remapDir "$BLD_ROOT_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_SAM_PREFIX=`remapDir "$BLD_SAM_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_SRC_PREFIX=`remapDir "$BLD_SRC_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_WEB_PREFIX=`remapDir "$BLD_WEB_PREFIX" "$BLD_PREFIX" "$_ARG"`
        BLD_PREFIX=`canonPath "${_ARG}"`
        ;;
    --product)
        # Done above
        ;;
    --q)
        # Done above
        ;;
    --quiet)
        # Done above
        ;;
    --setVersion)
        BLD_VERSION=${_ARG}
        ;;
    --silent)
        quiet=1
        ;;
    --samDir)
        BLD_SAM_PREFIX=`canonPath ${_ARG}`
        ;;
    --srcDir)
        BLD_SRC_PREFIX=`canonPath ${_ARG}`
        ;;
    --tool)
        # Done above
        ;;
    --tune)
        BLD_TUNE=`echo ${_ARG} | tr '[a-z]' '[A-Z]'`
        [ "$BLD_TUNE" = "SIZE" ] && BLD_TUNE=MPR_TUNE_SIZE
        [ "$BLD_TUNE" = "BALANCED" ] && BLD_TUNE=MPR_TUNE_BALANCED
        [ "$BLD_TUNE" = "SPEED" ] && BLD_TUNE=MPR_TUNE_SPEED
        if [ "$BLD_TUNE" != "MPR_TUNE_SIZE" -a "$BLD_TUNE" != "MPR_TUNE_BALANCED" -a "$BLD_TUNE" != "MPR_TUNE_SPEED" ]
        then
            echo "configure: unknown --tune option: $_ARG" 1>&2
            exit 2
        fi
        ;;
    --type)
        BLD_TYPE=${_ARG}
        [ "$BLD_TYPE" = "debug" ] && BLD_TYPE=DEBUG
        [ "$BLD_TYPE" = "release" ] && BLD_TYPE=RELEASE
        if [ "$BLD_TYPE" != "DEBUG" -a "$BLD_TYPE" != "RELEASE" ]
        then
            echo "configure: unknown --type option: $_ARG" 1>&2
            exit 2
        fi
        if [ "$BLD_TYPE" = "DEBUG" ]
        then
            BLD_DEBUG=1
        else
            BLD_DEBUG=0
        fi
        ;;
    --version|-V)
        echo $CONFIGURE_VERSION
        exit 0
        ;;
    --verbose|-v)
        # Done above
        ;;
    --webDir)
        BLD_WEB_PREFIX=`canonPath ${_ARG}`
        ;;
    *)  
        parseArg "${_SWITCH}" "${_ARG}"
        if [ $? != 0 ]
        then
            echo "configure: unknown option: $_SWITCH. Try --help" 1>&2
            exit 2
        fi
        ;;
    esac
done

fixDependencies

[ $quiet = 0 ] && echo -e "  # Check environment ..."
checkEnv

#
#   Set default tool value if corresponding environment variable (CC, AR, NM, LINK...) is defined
#
for t in $BLD_REQUIRED_TOOLS $BLD_REQUIRED_SDKS $BLD_OPTIONAL_TOOLS $BLD_OPTIONAL_SDKS
do
    eval value="\$${t}"
    if [ "$value" != "" ] ; then
        eval BLD_HOST_${t}=\"$value\"
    fi
done

for t in $BLD_REQUIRED_BUILD_TOOLS $BLD_REQUIRED_BUILD_SDKS $BLD_OPTIONAL_BUILD_TOOLS $BLD_OPTIONAL_BUILD_SDKS
do
    eval value="\$BUILD_${t}"
    if [ "$value" != "" ] ; then
        eval BLD_BUILD_${t}=\"$value\"
    fi
done

for t in $BLD_REQUIRED_FLAGS
do

    eval value="\$BUILD_${t}FLAGS"
    if [ "$value" != "" ] ; then
        eval BLD_BUILD_${t}FLAGS=\"$value\"
    fi

    eval value="\$${t}FLAGS"
    if [ "$value" != "" ] ; then
        eval BLD_HOST_${t}FLAGS=\"$value\"
		if [ "${BLD_HOST_SYSTEM}" = "${BLD_BUILD_SYSTEM}" ] ; then
			eval BLD_BUILD_${t}FLAGS=\"$value\"
		fi
    fi
done

#
#   Find and configure the build tools
#
[ $quiet = 0 ] && echo "  # Find build tools ..."

findToolsAndSdks

[ $quiet = 0 ] && echo "  # Set tool envionment variables ..."
setToolsEnv HOST
setToolsEnv BUILD
checkCompilerOptions HOST
checkCompilerOptions BUILD 

#TODO - delete

if [ $quiet = 0 ] ; then
    echo "  #"
    echo "  # Configuration for this build:"
    echo "  #"
    echo "  #   Configuring Product:   ${BLD_PRODUCT}"
    echo "  #   Base configuration:    build/${BLD_DEFAULTS}.defaults"
    echo "  #   Version:               ${BLD_VERSION}-${BLD_NUMBER}"
    echo "  #   Host system:           ${BLD_HOST_SYSTEM}"
    echo "  #   Host O/S dist:         ${BLD_HOST_DIST} (${BLD_HOST_DIST_VER})"
    echo "  #   Build system:          ${BLD_BUILD_SYSTEM}"
    echo "  #   Debug Type:            ${BLD_TYPE}"
    echo "  #   Tune for:              ${BLD_TUNE}"
    echo "  #   Packages:              ${BLD_PACKAGES}"

    traceTools HOST "$BLD_REQUIRED_TOOLS"           "host tools"
    traceTools HOST "$BLD_OPTIONAL_TOOLS"           "optional host tools"

    traceTools HOST "$BLD_REQUIRED_SDKS"            "host SDKs"
    traceTools HOST "$BLD_OPTIONAL_SDKS"            "optional host SDKs"

    traceTools BUILD "$BLD_REQUIRED_BUILD_TOOLS"    "build tools"
    traceTools BUILD "$BLD_OPTIONAL_BUILD_TOOLS"    "optional build tools"

    traceTools BUILD "$BLD_REQUIRED_BUILD_SDKS"     "build SDKs"
    traceTools BUILD "$BLD_OPTIONAL_BUILD_SDKS"     "optional build SDKs"
    echo "  # "
fi


#
#   Create the buildConfig.sh and buildConfig.make files
#
rm -f $CONFIG.sh $CONFIG.make $CONFIG.h
for f in $CONFIG.sh $CONFIG.make $CONFIG.h
do
    [ $quiet = 0 ] && echo "  # Creating $f ..."
    createConfig $f
done
[ $quiet = 0 ] && echo "  # "

cp $CONFIG.make config.tmp 
sed 's/'\''//g' < config.tmp | sed -e 's/""//g' >$CONFIG.make
sed 's/'\''//g' < config.tmp | sed 's/"//g' >$CONFIG.make
rm -f config.tmp

#
#   Modify the $CONFIG.h file. Do the following edits:
#   - Convert '#' to '//' comments
#   - Convert X=Y to #define X Y
#   - Convert all "'" to '"'
#
cp $CONFIG.h config.sav

egrep -v '^#|^    #' < config.sav | grep -v 'export' | sed 's/\([^=]*\)=\(.*\)/#define \1 \2/' | sed 's/'\''/"/g' | \
	sed 's/^#define/    #define/' | sed 's/^ #/#/' >$CONFIG.h
chmod 444 $CONFIG.sh $CONFIG.make $CONFIG.h
rm -f config.sav config.tmp

echo -e "#!/bin/bash\n\nconfigure $CMD_LINE" >$CONFIG.args

[ $quiet = 0 -a $verbose != 0 ] && echo "  # Creating $CONFIG.args ..."

postGen
postCheck

#
#   Touch all headers and remove objects to force a (somewhat) clean build
#
files=`echo src/include/*`
[ "$files" != 'src/include/*' ] && touch src/include/*
rm -f obj/*.o obj/*.obj bin/*.exe

[ $quiet = 0 ] && echo

exit 0
