/*
 *      Split_number_list.c
 *      
 *      Copyright 2008 ercoppa <ercoppa@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STEP 5000
#define STOP 10000000

FILE *filew;
int file_num = 0;

void insert_to_file( long long unsigned int num, short status );

int main(int argc, char** argv)
{
	
	FILE *file;
	if ( ( file = fopen( "test", "r" ) ) == NULL ) {
		
		printf( "Il file non puo' essere aperto.\n" );
		return 1;	
		
	} else {
		
		long long unsigned int num = 0;
		long long unsigned int sentinel = STEP;
		char row[ 200 ];
		
		if ( ( filew = fopen( "num_0", "w" ) ) == NULL ) {
		
			printf( "Il file non puo' essere aperto.\n" );
			return 1;
		
		}
		
		fscanf( file, "%[^\n]", row);
		while ( !feof( file ) ){
		
			num = atoll( row );
			if ( num > sentinel ) {
				
				sentinel += STEP;
				//printf("%d\n", ++file_num);
				insert_to_file( num, 1 );
				
			} else insert_to_file( num, 0 );
			
			if ( num >= STOP) break;
			
			fscanf( file, "\n%[^\n]", row);
		
		}
		
		fclose( file );
		fclose( filew );
		
	}
	
	return 0;
}

void insert_to_file( long long unsigned int num, short status ){
	
	
	if ( status == 1 ){
	
		fclose( filew );
		char filename[ 50 ] = "num_";
		char suffix[ 10 ];
		sprintf( suffix, "%d", ++file_num);
		strcat( filename, suffix );
		//printf("%s\n", filename);
		
		if ( ( filew = fopen( filename, "w" ) ) == NULL ) {
		
			printf( "Il file non puo' essere aperto.\n" );
			return;
		
		}
		
	}
	
	fprintf( filew, "%llu\n", num); 
	
}

