#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/timeb.h>
#include <time.h>


#define ERR_MSG         "\n>>> ERROR: "


#define MAX_LINES 50000
#define MAX_CHARS 50000
#define NO_RAND   15000


// set the random number initial value
void Randomize()
{
                struct timeb now;
                long seed ;

                ftime(&now);
                seed = (long)(now.millitm * (now.time % 100)) ;
                srand( seed );
}


// calculate a random value between 0 and 1
float frand()
{
        return ( (float)(rand()%NO_RAND)/( (float)NO_RAND) );
}


// make a permutation of the given Vector
int * Mix(int * p, int len,int  change)
{
        int a,b, i, tmp;
        for(i=0;i<change;i++)
        {
            // find two positions
            a = (int) (frand() * (len-1));
            b = (int) (frand() * (len-1));
            // change the values
            tmp = p[a];
            p[a] = p[b];
            p[b] = tmp;
        }

        return p;
}

main()
{
	FILE *infd, *out1fd, *out2fd;
        char inFile[50];
        char out1File[50];
        char out2File[50];
        char buf[MAX_CHARS];
        char *line[MAX_LINES];
	int i, count = 0;
	int *mix;
	
	Randomize();
 
        cout << "\n Input File    : ";
        cin >> inFile;
        cout << "\n 1st Output File               : ";
        cin >> out1File;
        cout << "\n 2nd Output File               : ";
        cin >> out2File;

	infd = fopen(inFile, "rt");
        if (infd == NULL)
        {
           cout << ERR_MSG << "can not open file :" << inFile << " !!!";
           exit(-1);
        }

 	out1fd= fopen(out1File, "wt");
        if (out1fd == NULL)
        {
           cout << ERR_MSG << "can not open file :" << out1File << " !!!";
           exit(-1);
        }

 	out2fd= fopen(out2File, "wb");
        if (out2fd == NULL)
        {
           cout << ERR_MSG << "can not open file :" << out2File << " !!!";
           exit(-1);
        }	

        // read the lines of the file
	while (!feof(infd))
	{
		fgets(buf, MAX_LINES, infd);
		line[count] = new char[strlen(buf)];	
		strcpy(line[count], buf); 
		count++;
	}

	mix = new int[count];
        // fill the array in order
        for(i=0; i<count; i++) mix[i] = i;
 
        // make a permutation
        mix = Mix(mix, count, count);

        i=0; 
        // write the lines in two different files
        while(i<count-2)
	{
		fputs(line[mix[i++]], out1fd); 
		fputs(line[mix[i++]], out2fd); 
	}
        // if the number of lines was odd one is left
        // write this in the first file
	if (i<count-1)
        {
             cout << "\n odd file \n";
             fputs(line[mix[i]], out1fd);  
	}	

        // close the files
	fclose(infd);
	fclose(out1fd);
	fclose(out2fd);
}

