Re-orders code and adds better documentation