Generalise and cleanup debugging code