relay: major cleanup of code