#!/usr/bin/env bash

set -u

[[ $# -eq 1 ]] && cd "$1"

source common.sh
setup_environment > /dev/null

[[ -f $PL_TODO ]] || fatal_msg "PL_TODO not set!"

doCSV=1

fast_check() {
    local nmax=$(wc -l < "$PL_TODO")
    local nsum=0
    local ndir=0
    for x in "${PL_TODO_LABELS[@]}"; do
        ndir=$((ndir+1))
        local pwc="$DIR_PROJECT_PWC/$x"
        [[ -d $pwc ]] || echo "DIR NOT FOUND"
        local ndone=$(find "$pwc" -name "*.$EXT_ALIGN" | wc -l)
        nsum=$((nsum+ndone))
        if [[ $doCSV -eq 1 ]]; then
            [[ $ndone -eq 0 ]] || {
                local perc="DONE"
                [[ $ndone -eq $nmax ]] || perc=$(printf "%5.2f" $(calc "100.0*$ndone/$nmax"))
                printf "%s,%s\n" "$HOSTNAME,$x,$ndone" "$perc"
            }
            continue
        fi
        local status="$ndone/$nmax"
        [[ $ndone -lt $nmax ]] || status="DONE"
        [[ $ndone -eq 0 ]] || printf "%-20s %20s\n" $(basename $x) $status
    done
}

detailed_check() {
    local N=$(wc -l < "$PL_TODO")
    local nA=$N
    local nB=$N
    local iA0=$(get_todo_lblind $OP_LABELA_FIRST)
    local iA1=$(get_todo_lblind $OP_LABELA_STOP)
    local iB0=$(get_todo_lblind $OP_LABELB_FIRST)
    local iB1=$(get_todo_lblind $OP_LABELB_STOP)

    [[ -z $iA0 ]] && iA0=0
    [[ -z $iA1 ]] && iA0=$N
    [[ -z $iB0 ]] && iB0=0
    [[ -z $iB1 ]] && iB0=$N

    # loop over all possible alignments
    local ndone=0
    local ntot=$((iA1-iA0+1))
    for ((iA=iA0; iA<iA1+1; iA++)); do
        local A=${PL_TODO_LABELS[$iA]}
        get_pwc_dir "$A"
        [[ -d $R_PWC_DIR ]] || { error_msg "missing PWC directory for <$A>"; continue; }
        local nok=0
        local nbad=0
        for ((iB=iB0; iB<iB1+1; iB++)); do
            local B=${PL_TODO_LABELS[$iB]}
            local f=$R_PWC_DIR/${A}_${B}.$EXT_ALIGN
            [[ -f $f ]] && { nok=$((nok+1)); continue; }
            nbad=$((nbad+1))
        done
        # if no missing alignments, count as done
        local status="$nok/$nB"
        if [[ $nbad -eq 0 ]]; then
            ndone=$((ndone+1))
            status="DONE"
        fi
        if [[ $doCSV -eq 1 ]]; then
            
            printf "%-20s %12s\n" $A $status
        fi
    done
    printf "done taxids %d/%d\n" $ndone/$ntot
}


#perc=$(calc "100.0*$nsum/($ndir*$nmax*1.0)")
#
#echo "Percentage done $perc"
detailed_check
