/* bm.rw is responsible for creating and opening a file, bnch.test.
Then the file is written to for the number of blocks (512) specified by
the user input to the prompt.  Following this, the file is closed,
reopened, and read until end of file is reached */
 
char * ctime(); 
#define MAX 80 
#define MODE 0755 
#define FILE "bnch.test" 
int t_start[2], t_end[2]; 
int total_time; 
main () {

	char line[MAX];
	int repeat_for = 0;
	char *l;
	l = line;
	getline(l,MAX);
	repeat_for = atoi(line);
        run_test(repeat_for);

}
getline(s, lim)
char *s;
int lim;
{
	int c,i;
	char *save;
	save = s;
	printf("ENTER THE NUMBER OF TIMES TO REPEAT: ");
	for (i=0; i<lim-1 && (c=getchar()) != 
		'\0' && c != '\n'; *save++ = c, ++i)
			;	
		if ((c  ==  '\0') && (i == 1))
			--save;
		*save = '\0';
		return(i);
}

run_test (repeat_for) 
int repeat_for;  {

int fd;
char write_buf [512];
char read_buf [512];
char i;
int j;
int ctr;
int num_bytes;
	for (i = 0; i < 127; i++) {
		write_buf[i] = i;
		write_buf[i+127] = i;
		write_buf[i+254] = i;
		write_buf[i+381] = i;
	}
	fd = creat (FILE, MODE);
	if (fd < 0) 
	{
		printf (" error in create\n");
		return(0);
	}
	close(fd);
	timeon();
	fd = open(FILE, 2);	
	for (ctr = repeat_for; ctr > 0; ctr--) {
		num_bytes = write(fd, write_buf, 512);
		if (num_bytes != 512) {
			printf(" write error: i = %d\n", ctr);
			break;
		}
	}
	lseek(fd,0L,0);
	for (ctr = repeat_for; ctr > 0; ctr--) {
		num_bytes = read(fd, read_buf, 512);
		if (num_bytes != 512) {
			printf("read error: i = %d\n", ctr);
			break;
		}

	}
	close(fd);
	timeoff();
}
timeon() {
	time(t_start);
	printf("WRITE-READ test starting: %s\n", ctime(t_start));
}

timeoff(){
	time(t_end);
	total_time += (32768 * (t_end[0] - t_start[0])) + ((t_end[1] - t_start[1]));
	printf("WRITE_READ test ending: %s\n", ctime(t_end));
	printf("total time = %d\n", total_time);
}
