/* In its JUMPDISK appearance, this file is crunched. It is the source */
/* for a program that is presented in running form. To decrunch this */
/* file, see the Articles Menu item on DECRUNCHING. */
/* Before compiling, DELETE these first four lines of file. */

#include <stdio.h>
#include <stdlib.h>

void main( int argc, char *argv[] );

void main( int argc, char *argv[] )
{
   FILE *infile, *outfile;
   long count = 0, size = 0, filesize = 0;
   int c = 0;
   
   if( argc != 5 )
   {
      printf( "Usage:  xsplit <input> <output1> <output2> <size>\n" );
      exit( 0 );
   }
   
   infile = fopen( argv[1], "rb" );    // open the input file
   if( infile == NULL )
   {
      printf( "Error!  Could not open file '%s'.\n", argv[1] );
      exit( 20 );
   }
   
   fseek( infile, 0, 2 );              // position at end of file
   filesize = ftell( infile );         // get file size
   fseek( infile, 0, 0 );              // position at start of file
   
   size = atol( argv[4] );
   if( size > filesize ) size = filesize; // can't copy more than filesize
   
   outfile = fopen( argv[2], "wb" );   // open the first output file
   if( outfile == NULL )
   {
      printf( "Error!  Could not open file '%s'.\n", argv[2] );
      fclose( infile );
      exit( 20 );
   }
   
   while( count < size )               // copy the first part
   {
      c = fgetc( infile );
      fputc( c, outfile );
      count++;
   }
   
   fclose( outfile );                  // close first output file
   
   if( size == filesize )              // make early exit if all is copied
   {
      fclose( infile );
      exit( 0 );
   }
   
   outfile = fopen( argv[3], "wb" );   // open second output file
   if( outfile == NULL )
   {
      printf( "Error!  Could not open file '%s'.\n", argv[3] );
      fclose( infile );
      exit( 20 );
   }

   while( count < filesize )           // copy the second part
   {
      c = fgetc( infile );
      fputc( c, outfile );
      count++;
   }

   fclose( outfile );                  // close all and make an exit
   fclose( infile );
   exit( 0 );
}
