refine code and add variable-length buffer