Re-implemented sorting and graph output, and added a cycle check.