Rewrote the whole thing in SQL.