#!/bin/bash
# CMM 5/2026  (renamed from dry_martini.sh 7/2026 — it does martiniglass/VMD
#              visualization prep, not force-field setup)
# WET martini. Needs to be run from a martiniglass-aware conda env ('martini').
#
# Produces:
#  - water-stripped .gro and .xtc via martiniglass + gmx trjconv (MUCH smaller)
#  - martini-aware VMD file
#  - an MDAnalysis-readable analysis TPR (${label}-${stage}-vis.tpr) built with
#    the gmx2024 conda env, because production TPRs from GROMACS 2026 are tpx
#    v138 which MDAnalysis 2.10 cannot read (max 137). See memory:
#    reference-tpx138-mdanalysis.
#
# run from the simulation directory.
# usage: make_vis.sh label stage [inxtc]
#   label = 1.0mM, stage = run  ->  reads ${label}-${stage}.xtc by default.
#   inxtc (optional 3rd arg) overrides the input trajectory. Use this for
#   -noappend restart segments, e.g.
#     make_vis.sh 200mM run 200mM-run.part0002.xtc
#   or a trjcat'd continuation:
#     gmx trjcat -f 50mM-run.part000[2-9].xtc -o 50mM-cont.xtc
#     make_vis.sh 50mM run 50mM-cont.xtc
#   Output keeps the ${label}-${stage}-vis.* names regardless of inxtc.
label=$1
stage=$2
inxtc=${3:-${label}-${stage}.xtc}

# gmx from the older env (writes tpx <=137 that MDAnalysis can read)
GMX2024=/opt/homebrew/anaconda3/envs/gmx2024/bin/gmx

# Build the vis tops from the production _System.top:
#  ${label}_vis.top      : header stripped (lines 1-5) for martiniglass -vf
#  ${label}-run-vis.top  : last line (W <count>) removed -> water-stripped top
#                          that KEEPS the atomtypes header; grompp-able and
#                          matches the water-stripped -vis.xtc atom set.
cp ${label}_System.top ${label}_vis.top
cp ${label}_System.top ${label}-run-vis.top
# Strip EVERY water line, not just the last one. `sed '$d'` assumed a single
# trailing "W <count>", which is wrong for a genconf-replicated system: those
# topologies REPEAT the molecule block (TTA,anion,W,TTA,anion,W), so one W line
# survives in the middle, the vis top then expects ~140k atoms the stripped
# -vis.gro does not have, and grompp dies. Matching on the molecule name is
# robust to however many blocks there are.
sed -i "" -E '/^[[:space:]]*W[[:space:]]+[0-9]+[[:space:]]*$/d' ${label}-run-vis.top
sed -i "" '1,5d' ${label}_vis.top

martiniglass -p ${label}_vis.top -f ${label}-${stage}.gro
gmx trjconv -f ${label}-${stage}.gro -s ${label}-${stage}.gro -n index.ndx -o ${label}-${stage}-vis.gro
gmx trjconv -f ${inxtc} -s ${label}-${stage}.tpr -pbc mol -n index.ndx -o ${label}-${stage}-vis.xtc
martiniglass -p ${label}_vis.top -vf
mv vis.vmd ${label}-${stage}-vis.vmd

# Analysis TPR for cmc.py / rdp.py (MDAnalysis-readable).
# Wet martini: water IS stripped from -vis.xtc, so use the water-stripped
# ${label}-run-vis.top (built above) against the stripped -vis.gro.
$GMX2024 grompp -p ${label}-run-vis.top -c ${label}-${stage}-vis.gro \
    -f martini_run_vis.mdp -o ${label}-${stage}-vis.tpr -maxwarn 5
