# This script adds a filename to a given projectfile
# the new name is written to the alphabetical position in a _end block
# It is called addproj_pl newfile projectfile

 #!/win1_bin_perl -w

 $newfile = shift."\n";                         # new filename from @ARGV and add a \n
 $newfile =~ tr/A-Z/a-z/ ;                      # set to lower case

 @end2 = split(/_/,$newfile);                   # find the _end of the new file

 while($f = shift){                             # get each name from @ARGV

 print "Perl adds ".$newfile."\n";

   unlink ($f.'_bak');                          # deletes old backup
   rename ($f,$f.'_bak');                       # and creates a new one

   open(I,$f.'_bak') || die;                    # open the old file
   open(O,">".$f) || die;                       # open the new file
   $end_fits = 0;                               # marker set when end fits
   while(<I>){

     $inline = $_;
     $inline =~ s/^\s+//g ;                     # erase all whitespaces at the
                                                # beginning of a line
     if(!/[#,:]/){                              # dont work on remarks or lables
       $inline =~ s/\ //g ;                     # erase all whitespaces
       $inline =~ tr/A-Z/a-z/ ;                 # and set to lower case
     }
     @end1 = split(/_/,$inline);                # find the _end of the current line

     if(@end1[$#end1] eq @end2[$#end2]){        # is the _end the same ?
       if($newfile lt $inline){                 # is the new file less ?

           print O $newfile;                    # then print the newfile
           $newfile = '';                       # and erase it

       }else{
         $end_fits += 1 ;                       # end fits but newfile > inline
       }
     }else{                                     # the _end does not match
       if($end_fits > 0){                       # but it did
           print O $newfile;                    # so the newfile > inline
           $newfile = '';                       # and erase it
        }
     }
     print O $inline;
   }
 print O $newfile;                    # print the newfile at the end of the file
 close O; close I;                    # close files
}
