Here is a script that works, but feels messy and disorganized: [paste code].
Please refactor it: organize logic into clean, single-purpose functions,
put related data into Tables, use local for all variables, and add a
comment above every function explaining what it does.
