Re-added most of accidentally deleted code