#!/usr/bin/env bash
# Rebuilds Table 4 of the phylogenetic tree guide: support for primate clades
# from five 1,000-column windows of primate_mtdna.aln.fasta (columns 1,001-2,000,
# 4,001-5,000, 7,001-8,000, 10,001-11,000 and 13,001-14,000).
# Each window: IQ-TREE 3.1.1, TVM+F+I+G4, 1000 UFBoot + 1000 SH-aLRT replicates,
# then 200 standard bootstrap replicates, macaque outgroup, seed 12345.
#
# Usage: IQTREE=/path/to/iqtree3 bash support_windows.sh
set -euo pipefail
cd "$(dirname "$0")"
IQTREE="${IQTREE:-iqtree3}"
mkdir -p windows

python3 - <<'PY'
seqs, name = {}, None
for line in open("primate_mtdna.aln.fasta"):
    line = line.strip()
    if line.startswith(">"):
        name = line[1:]
        seqs[name] = []
    elif line:
        seqs[name].append(line)
seqs = {k: "".join(v) for k, v in seqs.items()}
for start in range(1000, 16000, 3000):
    with open(f"windows/w{start + 1}.fa", "w") as out:
        for k, v in seqs.items():
            out.write(f">{k}\n{v[start:start + 1000]}\n")
PY

for w in windows/w*.fa; do
  b="${w%.fa}"
  "$IQTREE" -s "$w" -m TVM+F+I+G4 -B 1000 -alrt 1000 -o Rhesus_macaque \
    --seed 12345 -T 2 --prefix "${b}_ufboot" -quiet -redo
  "$IQTREE" -s "$w" -m TVM+F+I+G4 -b 200 -o Rhesus_macaque \
    --seed 12345 -T 2 --prefix "${b}_standard" -quiet -redo
done
