Almost got it working, still something very, deeply wrong around line 386