make this work with either old or new structure of emails, and cleanups