Code restructured and simplified