#!/bin/sh
#
set -e          # exit when any return status is non-zero
#
DBNAME="foobar"
HOST="origin"
USER="thor"
#
cat \
RAW/$DBNAME.sdf \
 | mol2smi -OUTPUT_FORMAT TDT > $DBNAME.tdt
#
echo "Fingerprinting..."
cat $DBNAME.tdt \
  | fingerprint > TMP/$DBNAME.fp.tdt
#
echo "TDTcounting..."
TDTCOUNT=`cat TMP/$DBNAME.fp.tdt | tdtcount`
PCOUNT=`echo $TDTCOUNT | cut -d" " -f5`
echo "Primary ID count = $PCOUNT"
IDCOUNT=`echo $TDTCOUNT | cut -d" " -f2`
XCOUNT=`expr $IDCOUNT - $PCOUNT`
echo "   Xref ID count = $XCOUNT"
#
thormake "\$DY_THORDB/$DBNAME_datatypes%@$HOST::$USER%" 100 1
thormake \
	-DATATYPES_DATABASE "$DBNAME_datatypes" \
	"\$DY_THORDB/$DBNAME_indirect%@$HOST::$USER%" 1000 1
thormake \
	-DATATYPES_DATABASE "$DBNAME_datatypes" \
	-INDIRECT_DATABASE "$DBNAME_indirect" \
	"\$DY_THORDB/$DBNAME%@$HOST::$USER%" \
	"$PCOUNT" "$XCOUNT"
#
echo "Loading the datatypes database..."
thorlookup DTYPEMASTER%@daylight.daylight.com::mug% -INPUT_FORMAT TDT \
	$DBNAME_datatypes.dcis.tdt \
	| thorload -MERGE FALSE -OVERWRITE TRUE \
		"\$DY_THORDB/$DBNAME_datatypes%@$HOST::$USER%"
thorload -MERGE FALSE -OVERWRITE TRUE \
	"\$DY_THORDB/$DBNAME_datatypes%@$HOST::$USER%" \
	< $DBNAME_datatypes.$DBNAME.tdt
#
echo "Loading the indirect database..."
#
echo "Loading the database..."
cat TMP/$DBNAME.fp.tdt \
	| thorload \
        -GENERATE_INDIRECT TRUE \
        -INCLUDE_INDIRECT "$I SOL" \
        -INDIRECT_DATABASE "$DBNAME_indirect%@$HOST::$USER%" \
	-REJECT_LOG errs.load.txt \
	"$DBNAME%@$HOST::$USER%"
#
echo "Nearneighbor-ing..."
nearneighbors -NUM_PROCESSES 2 \
              -RECORD_COUNT "$PCOUNT" \
              TMP/$DBNAME.fp.tdt > TMP/$DBNAME.nn.tdt
jpscan -RECORD_COUNT "$PCOUNT" TMP/$DBNAME.nn.tdt > TMP/$DBNAME.jpscan.txt
jarpat -RECORD_COUNT "$PCOUNT" TMP/$DBNAME.nn.tdt > TMP/$DBNAME.jp.tdt
listclusters -v -m "$PCOUNT" TMP/$DBNAME.jp.tdt > TMP/$DBNAME.lclus.tdt
#
echo "Loading the database w/ clusters..."
cat TMP/$DBNAME.lclus.tdt \
	| thorload \
	-REJECT_LOG errs.load2.txt \
	"$DBNAME%@$HOST::$USER%"
#
echo "Thorcrunching..."
thorcrunch -CRUNCH_LIMIT 0.0 "\$DY_THORDB/$DBNAME%@$HOST::$USER%"
#
cat $DBNAME.message \
	| daymessage -MESSAGE RECORD "\$DY_THORDB/$DBNAME%@$HOST::$USER%"
#
thorchange -SETACCESS READONLY "\$DY_THORDB/$DBNAME%@$HOST::$USER%"
#
thorsum $DBNAME > $DBNAME.summary
#
echo "Done making $DBNAME."
echo "Delete TMP files? [no] \c"
read answer
if [ "$answer" = "yes" ]; then
  for file in `ls TMP` ; do
    echo "rm $file"
    rm $file
  done
endif
