sub pack_str($$$$) {
    my($charset)	= shift;
    my($s)		= shift;
    my($s1)		= shift;
    my($s2)		= shift;

    if (($s =~ /^\s*$/) or ($s =~ /^[\x0E-\x7F]*$/)) {
	return $s1.$s.$s2;
    } else {
        my $hb64 = "=?$charset?B?". encode_base64($s);
        $hb64 =~ s/\n+$//m;
        $hb64 =~ s/\n/?=\n =?$charset?B?/gm;
	return $s1.$hb64."?=".$s2;
    }
}

sub pack_hdr($$$$) {
    my $header_name	= shift;
    my $is_addr		= shift;
    my $content_type	= shift;
    my $header_value	= shift;

    chomp($header_value);
    return($header_name.": ".$header_value) if ($header_value =~ /^[\x0E-\x7F]*$/);

    my($charset) = ($content_type =~ /charset\s*=\s*"?([a-z\d-]+)"?/im ? $1 : 'WINDOWS-1251');

    if ($is_addr) {
	$header_value =~ s/([\n,]?\s*)([^<>\n]*?)(\s*<)/pack_str($charset,$2,$1,$3) /eg;

	return($header_name.": ".$header_value);
    } else {
	return($header_name.": ".pack_str($charset, $header_value, "", ""));
    }
}
