#!/usr/local/bin/perl

@BOUNDARY=('','','','','');
$BND_LEV=0;
# dopuszczamy do 5 poziomow zagniezdzonych multipartow jedne w drugich

$MULTIPART=0;  # czy mail jest typu multipart
$TXT=1;        # czy mail jest typu text/plain
$HDR=1;        # czy jestesmy w naglowku
$FIRST_CT=1;   # czy pierwszy naglowek Content-type:
$PRN=1;        # czy drukowac biezacy wiersz
$OK=0;         # czy cokolwiek zostalo wydrukowane

while (<>) {
   if ( $HDR ) {
      if ( /^Content-type: *(.+)/i ) {
         $TYPE=$1;
         $TXT=0;
         $MULTIPART=1 if $TYPE =~ /^multipart/i;
         $TXT=1 if $TYPE =~ m#^text/plain#i or $TYPE =~ m#^text *$#i;
         $PRN=0 if $TXT==0;
      }
      if ( $MULTIPART and /boundary *= *"?([^"\n]+)/ ) {
         $BOUNDARY{$BND_LEV}=$1;
         $PRN=0;
      }
      $PRN=0 if $TXT==0 and /^Content-transfer-encoding:/i;
      $PRN=0 if $MULTIPART and /^$/;
      if ( $PRN ) {
         print;
      } else {
         $PRN=1;
      }
      if ( /^$/ ) {
         $HDR=0;
         $PRN=$TXT;
      }
   } else {
      $MULTIPART=2 if $MULTIPART and m#^Content-type: .*text/plain#i;
      $PRN=1 if $MULTIPART==2 and ( /^$/ or $FIRST_CT );
      if ( $MULTIPART and $PRN and /^$/ ) {
         $MULTIPART=1 if $MULTIPART>1;
         $FIRST_CT=0 if $FIRST_CT;
      }
      if ( $MULTIPART and $PRN and /^--$BOUNDARY{$BND_LEV}/ ) {
         $PRN=0;
      }
      if ( $MULTIPART and /boundary *= *"?([^"\n]+)/ ) {
         $BND_LEV += 1;
         $BOUNDARY{$BND_LEV}=$1;
      }
      $BND_LEV -= 1 if $MULTIPART and $BND_LEV>0 and /^--$BOUNDARY{$BND_LEV}--/;
      if ( $PRN ) {
         print;
         $OK=1 if not $OK and not /^ *$/;
      }
   }
}
print "Zawartosc nietekstowa!\n" if not $OK;
