/* BU.C    'BREAKUP'    
 *
 *  written for MANX 3.6a using 16-bits
 *   
 *  compile with:       cc bu
 *  link with:          ln bu.o -lc
 *
 * This is designed to break large files into
 * smaller, more manageable chunks.  Each new
 * file will be sized to MAXLINES.
 *
 *          8-18-88
 */

 #include <stdio.h>
 #include <libraries/dos.h>
 #include <exec/io.h>
 #include <functions.h>

 #define MAXLINES 1000               /* how many lines in each new file */
 #define BUFSIZE  256                /* maximum input line length       */
 char *name = "Writing FILE_ \x9bE" ;
 char *fnam = "FILE_ " ;
 char *iter = "ABCDEFGHIJKLMNOPQRSTUVWZYX" ;
 char *argstring = "args = BU infile\x9bE" ;
 char *author = "Brian Jackson 8-88" ;

 FILE *infile, *outfile ;
 int  count = 0 ;
 int  linecount = 0 ;
 char buffer[BUFSIZE] ;
 char *p, *fgets() ;
 int fileopen = 0 ;

 main( argc, argv )
 int argc ;
 char *argv[] ;
 {
  
    if( argc != 2 ) {
        Write( (long)Output(), argstring, 18L ) ;
        exit( 1L ) ;
        }

    if( ( infile = fopen( argv[1], "r" )) == 0) {
        Write( (long)Output(),"can't open source file\x9bE.", 24L ) ;
        exit( 1L ) ;
        }

    newfile() ;

    while( 1 ) {
        
        if( ! ( p = fgets( buffer, BUFSIZE, infile ))) {
             fclose( infile ) ;
             break ;
             }
        else {   
             fwrite( buffer, _BUILTIN_strlen(buffer), 1, outfile ) ;
             if( ++linecount == MAXLINES ) {
                  newfile() ;
                  }
             }
        }

 } 
    

 /*-----------------------------------------------
  * newfile - closes any open dest file and opens    
  *           a new one
  */

   newfile()
   {

     if( fileopen ) {
          fclose( outfile ) ;
          fileopen = 0 ;
          }
   
     name[13] = fnam[5] = *(iter + count++) ;
     Write( (long)Output(), name, 16L ) ;

     if( ( outfile = fopen( fnam, "w" ) ) == 0 ) {
          Write( ( long )Output(), "Can't open dest file - ", 23L ) ;
          Write( ( long )Output(), fnam, 6L ) ;
          fclose( infile ) ;
          exit( 1L ) ;
          }
     else {
          fileopen = 1 ;
          linecount = 0 ;
          }
   }
