same comments as above. can this all be pulled into a function with a signature like `startkey, endkey, filename = function(mode, case_id)` or similar?