messy as hell but gets things mostly correct