Fix bugs (write reduced tree output and fix sorting errors).