#!/bin/bash
#SBATCH -p short
#SBATCH -t 0-08:00
#SBATCH --mem 2G
#SBATCH -e mergebam.%j.err

module load conda/miniforge3/24.11.3-0
conda activate /n/groups/neuroduo/Shon/venv/bioenv
module load ucsc-tools/475


set -euo pipefail

input_dir="/n/groups/neuroduo/ava/260810_geo_resub/geo/CUTnTag/creb"
output_dir="/n/www/neuroduo.hms.harvard.edu/docroot/bigWig/Ava/221012_ChimpHuman/piN_CREB"

mkdir -p "$output_dir"

shopt -s nullglob


############################################################
# Function: check whether a BigWig is valid
############################################################

valid_bigwig () {

    file="$1"

    # Must exist and be non-empty
    if [[ ! -s "$file" ]]; then
        return 1
    fi

    # bigWigInfo must be able to parse it successfully
    if bigWigInfo "$file" > /dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}


############################################################
# Loop through every expected combination
############################################################

for species in Human Chimp; do

    for line in \
        H1C1b_F10-1 \
        H2C2a_G11-1 \
        H2C2a_G6-2
    do

        for condition in minusKCl 15mKCl; do

            for antibody in CREB IgG; do

                prefix="${species}_piN_${line}_${condition}_${antibody}"

                output="${output_dir}/${prefix}_merged.bw"

                echo
                echo "============================================================"
                echo "$prefix"

                ################################################
                # Check whether existing output is valid
                ################################################

                if valid_bigwig "$output"; then

                    echo "COMPLETE: valid BigWig already exists:"
                    echo "  $output"
                    echo "Skipping."
                    continue

                fi


                ################################################
                # If output exists but is invalid, remove it
                ################################################

                if [[ -e "$output" ]]; then

                    echo "INCOMPLETE/INVALID BigWig found:"
                    echo "  $output"
                    echo "Removing and rerunning."

                    rm -f "$output"

                else

                    echo "Output does not exist yet."

                fi


                ################################################
                # Find replicate BigWigs
                ################################################

                files=(
                    "$input_dir"/${prefix}_Rep*.bw
                )

                nfiles=${#files[@]}

                echo "Found $nfiles replicate BigWigs."

                if [[ $nfiles -lt 2 ]]; then

                    echo "WARNING: fewer than 2 replicates found."
                    echo "Skipping:"
                    echo "  $prefix"

                    continue

                fi

                echo "Input files:"
                printf '  %s\n' "${files[@]}"

                echo
                echo "Running bigwigAverage..."
                echo "Output:"
                echo "  $output"


                ################################################
                # Average replicate BigWigs
                ################################################

                bigwigAverage \
                    -b "${files[@]}" \
                    -o "$output"


                ################################################
                # Verify newly generated output
                ################################################

                if valid_bigwig "$output"; then

                    echo "SUCCESS: valid BigWig created:"
                    echo "  $output"

                else

                    echo "ERROR: output was created but failed bigWigInfo validation:"
                    echo "  $output"

                    rm -f "$output"

                    exit 1

                fi

            done
        done
    done
done


echo
echo "============================================================"
echo "All available missing or incomplete BigWigs have been processed."
