refactored a bit to avoid using imap and tee