Major overhaul of code