Fix some bugs, output can overwrite existing file