This fixes a bunch of bugs in our attachment-related code, and in so doing refactors things to make more sense, adds more tests, and also adds documentation.