#!/usr/bin/perl -wT

    use Data::Dumper;
    
    use Mail::Box;
    
    use Mail::Box::Manager;
    
    use Spreadsheet::WriteExcel;
    
    
    # start
    
    print "Content-type:text/html\n\n";
    
    # add mail box
        
    my $mgr    = Mail::Box::Manager->new;
    
    # manager
    
    my $folder = $mgr->open(folder =>'F://vm_mail/Inbox.sbd/Video472882d8') || die "$!";
    
    # Number of Messages
    
    print " Number of Messages :".$folder->messages.'<br>';
    
    # Sheet Creation
    
    my $workbook     = Spreadsheet::WriteExcel->new('query.xls');
    
    my $worksheet_I  = $workbook->add_worksheet('Type I');
    
    my $worksheet_II = $workbook->add_worksheet('Type II');
    
    my $worksheet    = [$worksheet_I,$worksheet_II];
    
    # Counters
    
    my $msg_counter = 0;
    my $type_II     = 0;
    
    foreach ($folder->messages) {
        
        my $lv;
        
        print $msg_counter ."-".$type_II;
        
        if($type_II eq 0){        
        
                @{$lv{'name'}}       = split(/:/,$_->escapedBody()->[1]);
                @{$lv{'contact'}}    = split(/:/,$_->escapedBody()->[2]);
                @{$lv{'contact_no'}} = split(/:/,$_->escapedBody()->[3]);
                @{$lv{'address'}}    = split(/:/,$_->escapedBody()->[4]);
                @{$lv{'category'}}   = split(/:/,$_->escapedBody()->[5]);
                
                $lv->{'header'}      = ['name','contact','contact_no','address','category'];
                
        }elsif($type_II eq 1){        
        
                @{$lv{'name'}}       = split(/:/,$_->escapedBody()->[1]);
                @{$lv{'id'}}         = split(/:/,$_->escapedBody()->[2]);
                @{$lv{'contact'}}    = split(/:/,$_->escapedBody()->[3]);
                @{$lv{'contact_no'}} = split(/:/,$_->escapedBody()->[4]);
                @{$lv{'area'}}       = split(/:/,$_->escapedBody()->[5]);                
                @{$lv{'address'}}    = split(/:/,$_->escapedBody()->[6]);
                @{$lv{'email'}}      = split(/:/,$_->escapedBody()->[7]);
                @{$lv{'web'}}        = split(/:/,$_->escapedBody()->[8]);
                @{$lv{'category'}}   = split(/:/,$_->escapedBody()->[9]);
                
                $lv->{'header'}      = ['name','id','contact','contact_no','area','address','email','web','category'];        
        }
        
        
        # neutralize
        
        $lv{'column_counter'}=0;
        
        for my $address_key (@{$lv->{'header'}}){
            
            $lv{$address_key}->[1]=~s/(\<\/p\>\<br\>)//g;
            $lv{$address_key}->[1]=~s/(\s+)$//g;
            
            $worksheet->[$type_II]->write($msg_counter,$lv{'column_counter'},$lv{$address_key}->[1]); 
            
            $lv{'column_counter'}++;
        }
        
        if( ($type_II eq 0) && ($msg_counter==142)) {$msg_counter=0; $type_II=1; }
        
        $msg_counter++;
        
    } # all messages