Add tag handling (take 2).

Also refactor a few functions.