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

[[ $# -ge 2 ]] || { echo "usage: $0 <list of gene ids> <PWC dir or BRH file>"; exit 0; }
finput=$1
fsource=$2
dPWC=""
fBRH=""
[[ -d $fsource ]] && dPWC=$fsource
[[ -f $fsource ]] && fBRH=$fsource

[[ -z $dPWC ]] && [[ -z $fBRH ]] && { echo "source not valid - $fsource"; exit 255; }
                                                                                      
LANG=C

geneList=( $(grep -v '^#' $finput | sort -u) )
sortGeneList() {
    local gene
    for gene in ${geneList[@]}; do
        echo ${gene%:*}
    done | sort -u
}
speciesList=( $(sortGeneList) )

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


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