#!/bin/bash
set -euo pipefail

OUTDIR="/BRC/yan/heart/ATAC_heart_openbed/counts"

echo "[$(date)] Merging into count matrix..."

# collect files in sorted order
files=($(ls ${OUTDIR}/counts_step3.3_rmbl_Adule_*.bed | sort))

# build header
header="chr\tstart\tend"
for f in "${files[@]}"; do
    sample=$(basename ${f} .bed | sed 's/^counts_step3.3_rmbl_//')
    header="${header}\t${sample}"
done

# write header + data
{ echo -e "${header}";
  paste "${files[@]}" \
    | awk 'BEGIN{OFS="\t"} {
        printf $1"\t"$2"\t"$3;
        for(i=4; i<=NF; i+=4) printf "\t"$i;
        print ""
    }';
} > ${OUTDIR}/count_matrix.txt

echo "  → $(wc -l < ${OUTDIR}/count_matrix.txt) lines (incl. header)  →  ${OUTDIR}/count_matrix.txt"
echo "[$(date)] Done."
