
usage ()
{
    echo "Usage: cmt_format_deps.sh [-no_stamps] DEP OBJ SRC DEPENDENCIES"
    echo "Create DEP [and its STAMP] containing Make rule with target DEP OBJ"
    echo "and prerequisites [STAMP] SRC SRC-DEPENDENCIES... based on DEPENDENCIES."
}

: ${CMTMSGPREFIX:=$0:}

if [ "${makecmd}" ]; then
    [ "${cmtmsg}" ] && echo "${CMTMSGPREFIX}" "($0)"
    set -x
fi

if [ "$1" = "-no_stamps" ]; then
    no_stamps=yes
    shift
fi
[ $# -eq 4 ] || { usage; exit 2; }

if [ "${no_stamps}" ]; then
    \rm -f ${1} || exit
    sed '1s#^[^:]*[:]\{1,2\}#'$1' '$2' : #' $4 >${1} || exit
else
    # the stamp file records the last change of the dependencies,
    # i.e., the contents of ${1}, while the last modification time of ${1}
    # changes every time the dependencies are calculated
    stamp=${1}.stamp
    tmp=${1}.tmp
    \rm -f ${tmp} || exit
    sed '1s#^[^:]*[:]\{1,2\}#'$1' '$2' : '${stamp}' #' $4 >${tmp} || exit

    if [ -f "${1}" ] && cmp -s ${1} ${tmp}; then
	[ -f ${stamp} ] || touch ${stamp}
	\rm -f ${tmp} || exit
    else
	touch ${stamp}
	\mv -f ${tmp} ${1} || exit
    fi
    touch ${1}
fi

if [ "${makecmd}" ]; then set +x; fi
