Simplify imap

Use @simonster's suggestions for cleaning this up.