Terminal code rework, many bug fixes