#!/bin/bash

# purch1act_one.sh 
# For one given bioactive library type  say BCTYPE invivo/ BCSUBTYPE fda
# Loop over each molecule
#   Loop over each purchasable library
#     store by catalogs if purchasable analogs
#     (offline re/pre process results for display/download)

# ====================== Configuration ======================
ROOT="/nfs/exk/newdbpublic"
BCTYPE="invivo"      # Bioactive Catalog Type: invitro | invivo | natural
BCSUBTYPE="street"  # Bioactive Catalog Subtype

SWDIR="/nfs/db5/newdb/Purch/maps"
PURCH="/nfs/db5/newdb/Purch/maps"

# ====================== Main Loop ======================

# for each catalog inside BCTYPE/BCSUBTYPE

for i in "$ROOT/Bioact/$BCTYPE/$BCSUBTYPE"/*; do

    # set up where the results will go
    bccatname=$(basename -s .smi $i)
    echo i is $i bccatname is $bccatname

# this is where purchasable results of bioactives goes
    thisbacat="$ROOT/Purchbioact/$BCTYPE/$BCSUBTYPE/$bccatname"
    mkdir -p $thisbacat # this bioactive cat
    cd $thisbacat || exit 1   # all results go within  this

# let's pick one purch cat at a time, and screen through all annotated mols
    for class in cc ise iso ode odo oth; do  # loop over purchasable class
        mkdir -p "$thisbacat/$class"
	ln -sf $PURCH/$class $PURCH/maps
        cd $class

# for each purch cat
        for pc in "$PURCH/$class/"*.map; do
            echo "pc is $pc"

# loop over all mols in bccatname
            while read -r smiles code; do
                [[ -z "$smiles" && -z "$code" ]] && continue

		if [ ! -s "$code.smi" ]; then
                	echo "$smiles $code" > "$code".smi
		fi

		basepurch=$(basename -s .smi.anon.map $pc)
		echo "$bccatname $code $class $basepurch"

                python /nfs/exk/newdb/SWAG/prog9.py -f "$code.smi" -d "$pc"
		if [ -s "$code" ]; then
    			mv "$code" "$code.$basepurch.txt"
    			# File exists and is NOT empty - rename it
		else
    			# File is missing or empty - delete it
    			rm -f "$code"
		fi
            done < "$i"
        done
        cd .. # pop out of this class ready for the next
    done
done
