/*--------------------------------------------*
 *  file  : benchmark_ran.C                   *
 *  Author: Hongfei Guo, Kai Xu               *
 *  Course: CS736 term project                *
 *--------------------------------------------*/

#include "global.h"

// Randomly write into a bunch of files;
// Parameters:
//    OPERATIONSIZE   - the buffer size of each write
//    FILENUMBER      - the number of files we write
//    FILESIZE        - the size of each file

int  randWrite()
{
    char   buf[OPERATIONSIZE];
    char   fileName[20];
    FILE*  fd;
    int    count;

    // random write
    for (int i=0; i<FILENUMBER; i++) 
    {
	sprintf(fileName, "temp_%d", i);
	fd = fopen(fileName, "w+");		
        
	count = 0;
        long totalWrite = FILESIZE / OPERATIONSIZE;
        // round up the result
        if ((FILESIZE % OPERATIONSIZE) != 0)
           totalWrite ++;

	for (int j=0; j<totalWrite; j++) 
	{
	    int p = rand() % totalWrite;
	    fseek(fd, p*OPERATIONSIZE, 0);
	    fwrite(buf, 1, OPERATIONSIZE, fd);
            count ++;
           
	}
        //printf("# of fwrite() : %d\n", count);
        fclose(fd);
    }
     return 0;
}

// Randomly read from a bunch of files;
// Parameters:
//    OPERATIONSIZE   - the buffer size of each read
//    FILENUMBER      - the number of files we read
//    FILESIZE        - the size of each file

int randRead()
{
    char   buf[OPERATIONSIZE];
    char   fileName[20];
    FILE*  fd;
    int    count;

    // random read 
    for (int i=0; i<FILENUMBER; i++) 
    {
	sprintf(fileName, "temp_%d", i);
	fd = fopen(fileName, "r");	

        count = 0;
        long totalRead = FILESIZE / OPERATIONSIZE;
        // round up the result
        if ((FILESIZE % OPERATIONSIZE) != 0)
           totalRead ++;

	for (int j=1; j<=totalRead; j++) {
	    int p = rand() % totalRead;
	    
	    fseek(fd, p*OPERATIONSIZE, 0);
	    fread(buf, 1, OPERATIONSIZE, fd);
	    count ++;
	}
        //printf("# of fread() : %d\n", count);
	fclose(fd);
    }
    return 0;
}
 
