optimize code, fix output issue