refactor write-char function