rename _write_tag to _output_tag; restructure some logic