clone of some replicode related code I found