#!/usr/bin/perl -w
#___________________________________________________________________________
# Name     : formbul.pl
# Author   : Peter Henrichsen
# Purpose  : This perl script is started by dbnprd and forms the input
#          : text files into wmo bulletin format for sending to the
#          : world.
#
# History  : Mon Oct 16 11:27:11 EDT 2000 Peter Henrichsen
#          : This new version of formbul.pl will segment the 
#          : input text into parts according to the size of the text file.
#          : $maxsize = 14500 ; # this is the size in bytes that is used to
#          : determine if the bulletin text is to be split into segments.
#          : THE LOGIC FOLLOWS:
#          : $size = -s $infile ;# obtain the size of the file.
#          : Where $size is the size of the input file in bytes.
#          : $line_count = `wc -l <$infile`; # get the line count
#          : $number_bytes = $size + ($line_count*3); # caculate the new byte count.
#          : $num_parts = int($number_bytes/$maxsize + .8) ; # caculate the number of parts
#          : The $num_parts is the number of segments that will be made from the input
#          : text file.
#          : Tue Nov 28 07:57:53 EST 2000 Peter Henrichsen
#          : modified to run on the ibm asp
#
# Location : This script is found on lnx185 as:
#          : /tmp_mnt/export/sgi73/peterhen/ibm/formbul/formbul.pl
#          :& on ibm as
#          : /nfsuser/g02/wx12ph/util/ush/formbul.pl &
#          : /nwprod/util/ush/formbul.pl
#
#
# Argumemts  There are three required arguements  -d $1 -f $2 -j $job where:
#          : $1 is deck or bulletin name.
#          : $2 is'infile' is the input text file (fullpath).
#          : $job is 'job name' where 'infile' text file was made.
#          : There are four optional arguements they are: -m $model -p $pcom and -s $SENDDBN
#          : and  -o $output_file 
#          : where:
#          : $model is 'model that made the text file' .
#          : $pcom is the current pcom path
#          : $SENDDBN is set to YES or NO for the sending of the completed bulletin.
#          : $output_file is the name you wish to have the bulletin in other than
#          : the file that the script creates.

#
# Required Items: Are 1. formbul_config that is found in:
#          : /nwprod/util/ush/formbul_config
#                     2. bulls directory that is found in:
#          : /nwprod/util/fix/bulls
#___________________________________________________________________________
#
use File::Basename;
use Getopt::Std;
($name, $path, $suffix) = fileparse($0,' ');
$pgmname = basename($0); # get program name for error messages.

$dbn_root=$ENV{'DBNROOT'};

if (!defined($dbn_root) || !$dbn_root) {
  print STDERR "\n$0: environment variable DBNROOT not set!\n";
   exit 0;
}
# require "/nfsuser/g02/wx12ph/util/ush/formbul_config"; # used for my check_out runs

  require "/nwprod/util/ush/formbul_config";

$reqid = $$;
$job = "formbul" ;
$jobid = $job . ".o" . $reqid;
# get input file name

getopt ('dfjmpso') ;
if ((! $opt_d) || (! $opt_f) || (! $opt_j)) {
 # check to see if there are "-d","-f" & "-j" options.
 print "Input deck, file name or job name missing \n";
   $msg = "$pgmname, ERROR,deck, file name or job name missing !";
   print "$msg \n";
#   post_msg($jlog_file, $jobid,$msg);
   exit 0;
}

$in_jobid=$ENV{'jobid'}; # get jobid from enviornment

$job = $opt_j ;

if (!defined($in_jobid) || !$in_jobid)  { # test for jobid
      print  "\n$0: environment variable in_jobid not set!\n";

  $jobid = $job . ".o" . $reqid;
 } else {
   $jobid = $in_jobid ;
 
 }  


# check to see if $opt_m is present
if ($opt_m) {
 print "Fount a input opt_m = $opt_m so use it to set model !\n";
 $model = $opt_m ;
} else {
 print "Seting $model to 'man'  !\n";
  $model = "man" ;
}

# check to see if $opt_p is present
if ($opt_p) {
 print "Fount a input opt_p = $opt_p so use it !\n";
 $pcom = $opt_p ;
 $jlog_file = "/com/logs/jlogfile";
}
#
print  "pcom = $pcom \n";
print  "deckpath = $deckpath \n";

# check to see if $opt_s is present
if ($opt_s) {
 print "Fount a input opt_s = $opt_s so use it!\n";
 $senddbn = $opt_s ;
}
$endline = "<<@";
print  "jlog_file is: $jlog_file \n";
print  " job is: $job reqid is: $reqid jobid is: $jobid \n";

print  "\nThe BULLETIN DAY HOUR MIM (DDHHMM)=>$DDHHMM<= !!!!\n\n";
#
$deck_name = lc $opt_d ; # transulate input deck name to lower case
$indeck = $deckpath . "/" . $deck_name;
print "OPEN the bulletin control card file $indeck \n";

GETCONTROLS: if(! open(INDECK, "< $indeck")) {
                 if(! ($indeck=make_control_file($opt_d,$deckpath))) {
                   $msg = "$pgmname, ERROR, can not get $opt_d from $deckpath!";
                   print "$msg \n";
                   #post_msg($jlog_file, $jobid,$msg);
                   exit 0;
                 }
               goto GETCONTROLS; # go back and read the control file.
              }

($name, $path, $suffix) = fileparse($opt_f,' ');
print "$name $path $suffix from fileparse\n" ;
$basename = basename($opt_f);
$dirname = dirname($opt_f);

print "Basename is $basename , dirname is, $dirname :\n";

  $infile = $opt_f;
print "OPEN the bulletin input TEXT FILE=>$infile<= \n";

  if(!open(INPUTEXT, "< $infile")) {
   $msg = "$pgmname, ERROR, can not get $infile!";
   print "$msg \n";
#
   #post_msg($jlog_file, $jobid,$msg) ;
   exit 0;
  }
   print "We have opened the $infile for reading \n";


@bul_names = "";
@file_names = "";
@headers_ray = "";
$machine = $job ;

$numbuls = &get_controls(*file_names,*headers_ray,*bul_names); # get headers and filenames

print "\n$numbuls is the number of bulletins to make \n";
   for ($i=0; $i < $numbuls; $i++) {
    print "$file_names[$i] is file name for bul$i\n" ;
    print "$headers_ray[$i] is header for bul$i\n" ;
   }

if($numbuls == 1) {
#
# WE COME HERE WHEN THERE IS ONLY ONE BULLETIN IN THE INPUT TEXT FILE.
#
 $big_header = $headers_ray[0] ;
  $size = -s $infile ;
   print  "The size of $infile is $size bytes \n";

  if ($size > $maxsize ) { # START of size loop

# WE COME HERE IF THIS BULLETIN MUST BE SPLIT IN TO SEGMENTS!

   $is_seg = 1;
    print  "$infile is a big file\n and must be segmented into parts !\n";
    $line_count = `wc -l <$infile`; # get the line count
    chomp($line_count);

    print  "Line count is $line_count \n";

    $number_bytes = $size + ($line_count*3); # caculate the new byte count.
    print  "number_bytes is the size + line_count*3 = $number_bytes \n";
    $num_parts = int($number_bytes/$maxsize + .8) ;
    print  "$infile will be segmented into $num_parts parts !\n";

   } else {

# WE COME HERE IF THIS BULLETIN IS SMALL AND IS NOT SEGMENTED!

     $is_seg = 0 ;
    print  "$infile is a small file !\n";
    $num_parts = 1;

   } # END of size loop

    @new_bull  = "";
    $numpart = $num_parts;
    @new_bull = &make_seg($numpart,$big_header); # call sub make_seg to segment text file
#
    open (OUTFILE,">$file_names[0]") ;# open out put file.

#   check on the lenght of each bulletin part and the block to $block_size bytes

    $num_records = 0;
      for ($i=0; $i < $num_parts; $i++) {
        $part_num = $i ;

#       block the part into $block_size bytes

        $new_bull[$i] = &block_seg($part_num,$new_bull[$part_num]); 
#
#      WRITE this bulletin or segment to the output file.
#
#      NOTE if this bulletin is segmented all the segments are written to the same
#           file.

        print OUTFILE $new_bull[$i] ;
      }
       close(OUTFILE) ; # finished with file close it before posting.

#     Write message to log file.

       $msg = "Bulletin $bulname made from $name !";
        #post_msg($jlog_file, $jobid,$msg) ;
      # print "\n $msg \n";

      if($num_parts > 1) {

#     Write extra message to log file if bulletin is segmented.

        $msg = "$bulname USES $num_records RECORDS AND HAS $num_parts PARTS !";
          #post_msg($jlog_file, $jobid,$msg) ;
        # print "\n $msg \n";
      }

#     Check to see if a new name is to be used for the bulletin.
      if($opt_o) {
#
        print "Will copy $file_names[0] into $opt_o and then remove $file_names[0]\n";
        copy($file_names[0], $opt_o);
#      now i must remove the orgional file.
       unlink($file_names[0]) ;
        $send_name = $opt_o ;
      } else {
        $send_name = $file_names[0];
      }

#   Check to see if we are to send or post the completed bulletin.
     if($senddbn =~ /YES/) {


#      POST bulletin to status file for OSO to get and send.

       ` $POST_IT TRAN $model $job $send_name `;
       print "$POST_IT TRAN $model $job $send_name \n";
       $msgp = "Posted $send_name with TRAN !";
       #post_msg($jlog_file, $jobid,$msgp) ;

     } else {
 
      $msgp = "TESTING $send_name NOT POSTED!";
      #post_msg($jlog_file, $jobid,$msgp) ;

     }
} else { 

#  COME HERE IF THERE ARE MORE THAN ONE BULLETIN IN THE INPUT TEXT FILE.

  print "We have $numbuls bulletins to make from $name \n";

  $bulnames = "";

   for ($ii=0; $ii < $numbuls; $ii++) { # START OF NUMBER OF BULLETIN LOOP.

      print "$file_names[$ii] is file name for bul$ii\n" ;
      print "$headers_ray[$ii] is header for bul$ii\n" ; 
      $big_header = $headers_ray[$ii]; 
      $len_bighead = length $big_header ; 
      @new_bull  = "";
      $numpart = 1;

#  call sub make_seg to get text from input file into bulletin format.

    @new_bull = &make_seg($numpart,$big_header); 
#
#  DO SOME CHECKING TO SEE IF THIS BULLETIN HAS MORE DATA THAN THE HEADER!
#
    $len_newbul = length $new_bull[0] ;
    $limit = $len_bighead+6 ;
    print "The length of big_head is $len_bighead length new_bull[0] =$len_newbul \n";

#   check to see if the bulletin has more data than the header!

    if($len_newbul > $limit) {

#  GOOD Bulletin open output file for writing.

      open (OUTFILE,">$file_names[$ii]") ;# open out put file.
      $num_records = 0;
      $i=0;
        $part_num = $i ;

#       SUBROUTINE &block_seg blocks the part into $block_size bytes

        $new_bull[$i] = &block_seg($part_num,$new_bull[$part_num]); 

#      WRITE to the output file.

        print OUTFILE $new_bull[$i] ;

       close(OUTFILE) ; # close this file before posting in.
        $bulnames = $bulnames . $bul_names[$ii] . " " ;

#     Check to see if a new name is to be used for the bulletin.
      if($opt_o) {
#
        print "Will copy $file_names[$ii] into $opt_o and then remove $file_names[$ii]\n";
        copy($file_names[$ii], $opt_o);
#      now i must remove the orgional file.
       unlink($file_names[$ii]) ;
        $send_name = $opt_o ;
      } else {
        $send_name = $file_names[$ii];
      }


#   Check to see if we are to send or post the completed bulletin.
     if($senddbn =~ /YES/) {

#      POST bulletin to status file for OSO to get and send.

       ` $POST_IT TRAN $model $job $send_name `;
        print "$POST_IT TRAN  $job $send_name \n";
       $msgp = "Posted $send_name with TRAN !";
       #post_msg($jlog_file, $jobid,$msgp) ;

     } else {
      $msgp = "TESTING $send_name NOT SENT  !";
       #post_msg($jlog_file, $jobid,$msgp) ;

     }
    } else {

#   BAD ###  SKIP THE BULLETIN BECAUSE IT IS ONLY A HEADER!

      print "Skipping part $ii because  $len_newbul is < or = $limit \n";
    }
  }

#     Write message to log file.

     $msg = "Bulletins ${bulnames}made from $name !";
     #post_msg($jlog_file, $jobid,$msg) ;
  # print "\n $msg \n";
}
exit 0;
########## END OF MAIN PROGRAM ###########################

sub make_control_file {
#
#___________________________________________________________________________
# Name     : make_control_file
# Author   : Peter Henrichsen
# Purpose  : This perl subroutine make a control file for the perl script formbul.pl.
#
# History  : Wed Aug  9 07:08:37 EDT 2000 Peter Henrichsen
#
#
# Location : This script is found on lnx185 as:
#          : /tmp_mnt/export/sgi73/peterhen/ibm/formbul/(in formbul.pl)
#
#
# arg1 = control flags that come from the $9 arg from dbnet.  This is the bulletin
#        name or can have the form of bulletinname_centername_pil(a max of 6 characters)
#        Some examples are:   "tcus54", "tcus54_kwbc" or "tcus54_kwbc_scppr2" .
# arg2 = the control directory where to put the control file named as arg1.

# usage example:
#
# make_control_file(tcus54_kwbc_scppr2, /usr/DBNet/user/bulls)
#
# 
#_______________________________________________________________________________________
# 
my($control_flags,$control_directory) = @_; # name the input args.
my $center = "KWBC";
my $pil = "";
my $bulname = "";
my $outcontrol_file = "";
   $control_flags =~ tr/A-Z/a-z/; # transulate to lower case
   $outcontrol_file = $control_directory . "/" .  $control_flags ;# create path for writing
  print "OPEN the bulletin control file $outcontrol_file \n";
  if(!open(OUTDECK, "> $outcontrol_file")) {
   print "Trouble opening $outcontrol_file for writing \n";
  return ""; # error return
}
# die "cannot open $outcontrol_file for writing : $!";
  $ts = time ; # get number of seconds for use by local time function.

  $date = scalar(localtime($ts));# Get local time for lineone

  $part1 = "NUMBER OF BULLETINS TO MAKE01xxx MEMBER=";
  $lineone = $part1 . $control_flags . " " . $date . " DKPH \n"; #make lineone 

  # now write first line into $outdeck 
  print OUTDECK $lineone ; # write lineone
  print "Wrote lineone = $lineone ";
  
  @parts = split(/_/, $control_flags); #split coltrol_flags into parts 
  $bulname = $parts[0]; #get bulletin name.
  if( @parts == 3) {
    if($parts[1] =~ /$valid_centers/){
     $center = $parts[1]; #get valid center name.
    }
   $pil = $parts[2]; # get pil

  } elsif ( @parts == 2) {
   if($parts[1] =~ /$valid_centers/){
     $center = $parts[1];#get valid center name.
   }
  
  }
   $bulname =~ tr/a-z/A-Z/; # transulate to upper case:
 $center =~ tr/a-z/A-Z/; # transulate to upper case.
 $pil =~ tr/a-z/A-Z/; # transulate to upper case.
 my $len = length $bulname ; # get length of bulletin name.
 print "Bulletin name =>$bulname<= Center name=>$center<= Pil =>$pil<=  \n";
 $linetwo = "INEW B=" . $len . "00000" . $bulname . " F=" . $center .",W=" .  $pil . "\n";

 print OUTDECK $linetwo ; # write linetwo

 print " I wrote linetwo of $linetwo ";
close(OUTDECK) ;
 return $outcontrol_file;  # good retun $outcontrol_file name
}
sub get_controls {
#
#___________________________________________________________________________
# Name     :get_controls
# Author   : Peter Henrichsen
# Purpose  : This perl subroutine reads the control card file and forms the
#          : the header lines and the output file_names
#
# History  : Fri Sep 15 07:08:55 EDT 2000 Peter Henrichsen
#
#
# Location : This script is found on lnx185 as:
#          : /tmp_mnt/export/sgi73/peterhen/ibm/formbul/(in formbul.pl)
#
#
#_______________________________________________________________________________________
#
($headers_ray,$file_names,$bul_names) = @_; # name the input args.
my $num_buls;
my $VALID_CENTERS = uc $valid_centers;# convert to uppercase.
 $center = "KWBC";

$_ = <INDECK> ; # read a line in from the INDECK  into $_

  chomp($_); # remove trailing \n from $_

   if (/make/i) { # search for make in $_

     if(substr($_,27,1) == 0) { # check tens part        
        $num_buls = substr($_,28,1); # get number of bulletins to make
     } else {
        $num_buls = substr($_,27,2); # get number of bulletins to make
     }
       $num_buls = int($num_buls); # get $numbul into integer
       
      print "Number of bulletins to make = $num_buls :\n";
      
   }

 if($num_buls >= 1){

   for ($i=0; $i < $num_buls; $i++) {

      $_ = <INDECK> ; # read in one line
       if (/inew/i) { # search for inew
                   
         @words = split; # same as @words = split(/\s+/, $_);
        
         $len = length $words[1]; # get number of bytes in $words[1]
        
         $bulname = substr($words[1],8,$len-8);
         $pil = ""; # blank $pil
         $center = ""; # blank $center
         
         @parts = split(/,/, $words[2]); # get equal flags.
         $flags ={};

         foreach $part (@parts) {
           ($key, $value) = split /=/, $part;
            $flags{$key} = $value; # load into hash %flags           
         }
           while ( ($key,$value) = each %flags) { # print key and value
              print "$key => $value\n";
           }

           if($flags{F} =~ /$VALID_CENTERS/) {
            $center = $flags{F};
           }else {          
            $center = "KWBC";
            print  "Using default center =>$center<=\n";
           }
          
                    
         print "Bulname=$bulname center=$center \n";         

           $lenpil = 0;
           if($flags{W}) {
            $pil = $flags{W};
            $lenpil = length $pil;
            
            $output = $pcom . "/" . $bulname ."." . $center . "." . $pil . "." . $machine ;
            $head =  sprintf("%s%s %s %s%s%s",$header,$bulname,$center,$DDHHMM,$endline,
                     $pil);       

            $ispil = 1; # set ispil flag to true.
           }else {
            $output = $pcom . "/" . $bulname ."." . $center . "." . $machine ;
           $head =  sprintf("%s%s %s %s",$header,$bulname,$center,$DDHHMM);
            $ispil = 0; # set ispil flag to false.
           }
      }
            print "length of pil line=>$lenpil<=\n"; 
         $output = lc $output ; # transulate output file name into lowercase.
         $bul_names[$i] = $bulname;
         $file_names[$i] = $output;
         $headers_ray[$i] = $head;
   }
 }
return $num_buls;
}
sub make_seg {
#
#___________________________________________________________________________
# Name     : make_seg
# Author   : Peter Henrichsen
# Purpose  : This perl subroutine segments a text file into parts for formbul.pl.
#
# History  : Wed Oct  4 06:44:13 EDT 2000 Peter Henrichsen
#
#
# Location : This script is found on lnx185 as:
#          : /tmp_mnt/export/sgi73/peterhen/ibm/formbul/(in formbul.pl)
#
#
#_______________________________________________________________________________________
#
my($numparts,$header) = @_; # name the input args.
my $endbul  = "<<%";

my @seg_names = "";

my @parts = ( PAA, PAB, PAC, PAD, PAE, PAF,
              PAG, PAH, PAI, PAJ, PAK, PAL,
              PAM, PAN, PAO, PAP, PAQ, PAR,
              PAS, PAT, PAU, PAV, PAW, PAX,
              PAY, PAZ, 
              PBA, PBB, PBC, PBD, PBE, PBF,
              PBG, PBH, PBI, PBJ, PBK, PBL,
              PBM, PBN, PBO, PBP, PBQ, PBR,
              PBS, PBT, PBU, PBV, PBW, PBX,
              PBY, PBZ,
              PCA, PCB, PCC, PCD, PCE, PCF,
              PCG, PCH, PCI, PCJ, PCK, PCL,
              PCM, PCN, PCO, PCP, PCQ, PCR,
              PCS, PCT, PCU, PCV, PCW, PCX,
              PCY, PCZ,
              PDA, PDB, PDC, PDD, PDE, PDF,
              PDG, PDH, PDI, PDJ, PDK, PDL,
              PDM, PDN, PDO, PDP, PDQ, PDR,
              PDS, PDT, PDU, PDV, PDW, PDX,
              PDY, PDZ,
              PEA, PEB, PEC, PED, PEE, PEF,
              PEG, PEH, PEI, PEJ, PEK, PEL,
              PEM, PEN, PEO, PEP, PEQ, PER,
              PES, PET, PEU, PEV, PEW, PEX,
              PEY, PEZ   );

my $key = 0;

my @bull_array="";
 if($numparts == 1) {
   $key = 0;
    $bull_array[$key]=  sprintf("%s%s",
             $header,$endline) ;
    
    print  "bull_array$key  $bull_array[$key] \n";

 } else { # have parts
    if($ispil) { # check to see if there is a pil if so I must fidel with the header.
    $lenhead = length $header;
     $new_head = substr($header,0,$lenhead-9); # get truncated header
     print "$lenhead is the lenght of header, newhead =>$new_head<= \n";
      $offset = ($lenhead - 6) ;
     $new_pil = substr($header,$offset,6);# get new pil
      print "$new_pil = the pil from the header, the old pil is =>$pil<=\n";
     $header = $new_head ;
    }
   for ($key=0; $key < $numparts; $key++) {

    $part_head = $parts[$key];
    $seg_names[$key] = $part_head ;
    if($ispil) {
     $bull_array[$key]= sprintf("%s %s%s%s%s",
             $header,$parts[$key],$endline,$pil,$endline) ;
    } else {
    $bull_array[$key]=  sprintf("%s %s%s",
             $header,$parts[$key],$endline) ;
    }
    print  "bull_array$key  $bull_array[$key] \n";
   }
#   $part_head =~ s/(.).(.)/\1Z\2/;
   $part_head =~ s/(.).(.)/$1Z$2/;
    if($ispil) {
     $bull_array[--$key]= sprintf("%s %s%s%s%s",
             $header,$part_head,$endline,$pil,$endline) ;
    } else {
    $bull_array[--$key]=  sprintf("%s %s%s",
             $header,$part_head,$endline) ;
    }
    print  "Last member of the bull_array$key  $bull_array[$key] \n";
 }
$j=0;
   
NEWPART: print  "The header for bull_array$j  $bull_array[$j] \n";

      $arry_len = length $bull_array[$j] ; # get # of bytes in  bull_array.
      $bulen = $arry_len ;
      print  "The length of bull_array$j is $arry_len \n";

       while (<INPUTEXT>) { # read a line in from the INPUTEXT  into $_

          chomp($_); # remove trailing \n from $_
#           if (/$bulname/i ) { # search for $bulname in $_
           if (/$bulname/i or ($ispil and /$pil/i)) { # search for $bulname or $pil in $_
               
#             print "Found $bulname  $_ in text skip it!\n";
             print "Found $bulname  or $pil in  $_ .. skip  this line!\n";

           } else {
            if (/nnnn/i) { # search for termimiating nnnn's
                print "Found end because, last line= $_\n";
                $bull_array[$j] =  $bull_array[$j] . $endbul ;
                $bulen = $bulen + 3 ;
                print  "Part $j is the LAST segment and is $bulen bytes long \n";
                print  "I ADDED  $endbul to this segment \n";
                goto ENDBUL;
            } else {
              $_ =~ s/\s+$//; # remove trailing blanks from $_
              $_ =~ s/%/P/g; # remove percert from $_ line
              $_ =~ s/>//g; # remove > from $_ line
              $_ =~ s/'//g; # remove ' from $_ line
              $_ =~ s/,/\//g; # remove , from $_ line
              $_ =~ tr/\032//d; #  delete  CTRL-Z or '032' from  $_  line
              $_ =~ tr/\000//d; #  delete binary zero or CTRL-@ from  $_  line
              $_ =~ tr/\015//d; #  delete CTRL-M or carraige return from  $_  line
              $_ =~ tr/a-z/A-Z/; #  convert $_ line to upper case
              $outline = $_ . $endline ;  # add end line
              $linelen = length $outline; # get # of bytes in line
               if(($linelen + $bulen) <= $seg_size) {
                $bulen = $bulen + $linelen ; # add # of bytes to total.
                 $bull_array[$j] =  $bull_array[$j] . $outline ;
                 if($bulen == $seg_size) {
                  $bull_array[$j] =  $bull_array[$j] . $endbul ;
                  $bulen = $bulen +3;
                   print "I have $bulen bytes in this segment \n";
                   $j  = $j + 1;
                    $bulen = 0;
                   goto NEWPART ;
                 } else {
                   $endseg = "";
                 }
               } else {
                  $endseg = 1;
                  $bull_array[$j] =  $bull_array[$j] . $endbul ;
                  $bulen = $bulen + 3;
                   print "I have  $bulen bytes in segment # $j I ADDED  $endbul  \n";
                $j = $j + 1;
                  print "Will load $linelen bytes in $j segment \n";
                $bull_array[$j] =  $bull_array[$j] . $outline ;
                  print "Seg $j now is $bull_array[$j] \n";
                goto NEWPART ;
               }
            }
           }
          } # end of while loop for input text file
        $bull_array[$j] =  $bull_array[$j] . $endbul ;
        $bulen = $bulen + 3 ;
        print  "Part $j is the LAST segment and is $bulen bytes long \n";
        print  "THIS FILE IS NOW EMPTY SO I ADDED $endbul TO END SEGMENT! \n";
ENDBUL: print  " Checking for complete segments\n" ;

 if($is_seg) {
   print "is_seg = $is_seg IS ON SO check, for uncompleted segments\n" ;
   if(($j+1) < $numparts) {
      $old_head  = $seg_names[$j];
      $new_head = $old_head;
      $new_head =~ s/(.).(.)/$1Z$2/;
      print "I have another part so I must change $old_head to $new_head in segment$j\n";
      $bull_array[$j] =~ s/$old_head/$new_head/ ;
      $header_last = substr($bull_array[$j],0,65) ;
      print "The header for sement$j is now $header_last \n";
      #$num_parts = $numparts - 1 ;
      $num_parts = $j + 1 ;
      print  "I INSERTED $new_head into segment $j and CHANGED num_parts form $numparts to $j + 1  \n";
   } else {
      print "ALL segments are complete because $j+1 = $numparts \n";
   }
 } else {
   print "is_seg = $is_seg IS OFF , NO checking required.\n";
 }
 return @bull_array ;
}
sub block_seg {
#
#___________________________________________________________________________
# Name     :block_seg
# Author   : Peter Henrichsen
# Purpose  : This perl subroutine blocks a bulletin or bulletin segment into
#            ($block_size = 1280) bytes.
#
# History  : Wed Aug 23 13:57:50 EDT 2000 Peter Henrichsen
#
#
# Location : This script is found on lnx185 as:
#          : /tmp_mnt/export/sgi73/peterhen/ibm/formbul/(in formbul.pl)
#
#
#_______________________________________________________________________________________
#
my($part_num,$bul_ray) = @_; # name the input args.
my $delimiter = "\n";
my $pad = " ";
my $big_buf = "";
my $start = 0 ;
my $num_bytes = length $bul_ray;
    print "Part $part_num has $num_bytes bytes \n";
my $sub_parts = int($num_bytes/$block_size + .5) ;
#
# must check to see if ($block_size * $sub_parts) is less than $num_bytes
#
 if(($block_size * $sub_parts) < $num_bytes) {
   $sub_parts = $sub_parts + 1 ;
 }
my $num_add = ($block_size * $sub_parts) - $num_bytes ;
   print "sub_parts is $sub_parts and num_add is $num_add \n";
      for ($m=0; $m < $num_add; $m++) { # padd to even mul of $block_size.
       $bul_ray = $bul_ray . $pad ;
      }
    $num_bytes = length $bul_ray;
    print "Part $part_num now has $num_bytes bytes \n";
#  now I must add the delimiter after every $block_size  bytes.
     for ($j=0; $j < $sub_parts; $j++) {
      $buf = substr($bul_ray,$start,$block_size);
       $start = $block_size * ($j + 1) ;
       $big_buf = $big_buf . $buf . $delimiter ;
     }
     $num_records = $num_records + $sub_parts ;
     $bul_ray = $big_buf ;
     $num_bytes = length $bul_ray;
     print "Part $part_num now has $num_bytes bytes \n";
 return $bul_ray  ;
}
sub post_msg  {
#___________________________________________________________________________
# Author   : Peter Henrichsen
# Purpose  : This perl subroutine posts messages to a log file.  Three arguments
#            are required.
#
# History  : Wed Sep 13 07:35:51 EDT 2000 Pete Henrichsen
#          
# Location : This script is found on lnx185 as:
#          : /tmp_mnt/export/sgi73/peterhen/ibm/formbul/(in formbul.pl)
#
# usage example:
#
# post_msg (log_file,jobids,message_text)
#
# Argumemts: 'log_file' this is the full path of the log_file.
#          : 'jobids'The variable jobid contains the 
#            name of the job and its pid in the form JOBNAME.pid.
#          : 'message_text' is the text of the message to write into jlog_file.
#
#____________________________________________________________________________
#
my($log_file, $jobids, $message_text) = @_;

my $endline = "\n";


 if ( ! -r $log_file ) { 
  printf(STDERR "\nusage error: $0: $log_file cannot be read: $!\n");
  return ""; # error return
 }


 print  "jlog_file is: $log_file \n";


 print "datetime=>$datetime<= \n"; # 07/19 10:09:42Z


 open (JLOGFILE, ">> $log_file" );

 $msgline = $datetime . $jobids . "-" . $message_text . $endline ; # make line

 print "$msgline \n";

 print JLOGFILE  $msgline; # write line to jlog_file
 close(JLOGFILE);
 return $msgline ;# good return
}
