#!/usr/bin/env bash
set -u

[[ $# -ge 2 ]] || {
    echo "usage: $0 <list of gene ids | cluster file> [<clid>] <PWC dir or BRH file>"
    echo "If three arguments then the input file is assumed to be a cluster file and"
    echo "the second argument the selected cluster id."
    exit 0
}
finput=$1
fsource=$2
clidcsv=""
sourceIsCluster=0
if [[ $# -ge 3 ]]; then
    sourceIsCluster=1
    clidcsv=$2
    fsource=$3
fi

# get source of BRH's
# 1. a directory
# 2. a single file
dPWC=""
fBRH=""
[[ -d $fsource ]] && dPWC=$fsource
[[ -f $fsource ]] && fBRH=$fsource
[[ -z $dPWC ]] && [[ -z $fBRH ]] && { echo "source not valid - $fsource"; exit 255; }

# for the sorting
LANG=C

geneList=()
if (( sourceIsCluster )); then
    clidlist=( $(echo "${clidcsv//,/ }") )
    clidopt=""
    for clid in "${clidlist[@]}"; do
        clidopt=" $clidopt -e '^$clid '"
    done
    geneList=( $(eval grep "$clidopt" "$finput" | awk '{print$2}' | sort) )
else
    geneList=( $(grep -v '^#' "$finput" | sort -u) )
fi

if [[ ${#geneList[@]} -eq 0 ]]; then
    echo "nothing found"
    exit 0
fi

getSpeciesList() {
    local gene
    for gene in ${geneList[@]}; do
        echo ${gene%:*}
    done | sort -u
}

checkPWC() {
    local A=$1
    local B=$2
    local sA=${A%:*}
    local sB=${B%:*}
    [[ $sA == $sB ]] && return 1
    local f=$dPWC/$sA/${sA}_${sB}.brh
    grep "^$A $B" $f
    return $?
}
checkBRH() {
    local A=$1
    local B=$2
    local sA=${A%:*}
    local sB=${B%:*}
    [[ $sA == $sB ]] && return 1
    grep "^$A $B" $fBRH
    return $?
}


speciesList=( $(getSpeciesList) )
Ngenes=${#geneList[@]}

Nfound=0
Ntot=0
for (( i=0; i<Ngenes; i++ )); do
    A=${geneList[$i]}
    for (( j=i+1; j<Ngenes; j++ )); do
        Ntot=$((Ntot+1))
        B=${geneList[$j]}
        if [[ -n $dPWC ]]; then
            checkPWC $A $B && Nfound=$((Nfound+1))
        elif [[ -n $fBRH ]]; then
            checkBRH $A $B && Nfound=$((Nfound+1))
        fi
    done
done

echo "# Nr of species    : ${#speciesList[@]}"
echo "# Nr of BRHs found : $Nfound BRHs out of $Ntot possible"
