relay: cleanup code and fix a couple of bugs