#!/usr/bin/awk -f

BEGIN { inheader=1; }
# check for end of header
/^ *$/ {
    inheader=0;
}

# check for from or reply-to header
/^[Rr][Ee][Pp][Ll][Yy]-[Tt][Oo]:/ && inheader == 1 {
    curheader="reply-to";
    reply_to=substr($0,10,length-9);
    next;
}
/^[Ff][Rr][Oo][Mm]:/ && inheader == 1 {
    curheader="from";
    from=substr($0,6,length-5);
    next;
}
# if header line begins with space or tab, it's a continuation
/^[     ]/ && inheader == 1 {
    if (curheader == "from")
        from = from "\n" $0;
    else if (curheader == "reply-to")
        reply_to = reply_to "\n" $0;
}
# other header lines that we don't care about
/^[^    ]/ && inheader == 1 {
    curheader="";
    next;
}

END {
    if (reply_to != "")
        reply_address = reply_to;
    else
        reply_address = from;
    print reply_address;
}
