Some further improvements which I will abandon because it's just too needlessly complicated.