Fix and cleanup nasty code