/* bigfile.c
 *
 * $Id: fsreaddisk.c,v 1.1 2000/12/18 03:47:10 alderman Exp $
 *
 * Big file: read a big file sequentially.
 */

#include <stdio.h>
#include <sys/types.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> 

#include "global.h"
#include "timer.h"

int readMeg(char *buf, int fd);

int main(int argc, char *argv[]) {
        int fd, i;
        char buf[NUMBYTES+1];
        struct timespec now_tv;
        long now, last;
	int rv, j;
	char *filename;
     
	clock_gettime(CLOCK_REALTIME, &now_tv);
        last = tv_to_msec(&now_tv);

        memset(buf, '\0', NUMBYTES);

        for (i = 0; i < 86; i++) {
		filename = malloc(256);
		rv = snprintf(filename,255,"bf/%2.2d",i);
		fd = open(filename, O_RDONLY, NULL);
                if(fd < 1) {
                        printf("open error: fd %d on %s\n",fd, filename);
                        exit(1);
                }
                free(filename);
		for(j = 0 ; j < 100; j++) {
			if(readMeg(buf, fd) < 1)  {
	                        fprintf(stderr, "Exiting with i = %d.\n", i);
                      		exit(1);
			}
		}
		close(fd);
                clock_gettime(CLOCK_REALTIME, &now_tv);
                now = tv_to_msec(&now_tv);
                printf("%d: %ld\n", i, now - last);
                last = now;
        }
	exit(0);
}
               

int readMeg(char *buf, int fd) {
        int curByte = 0;
        int rv;
        while(1) {
                rv = read(fd, buf, NUMBYTES - curByte);
                curByte += rv;
                if(rv > 0) {
                        // fprintf(stderr, "Read %d bytes.\n",rv);
                        if (curByte < NUMBYTES) {
                                continue;
                        } else {
				return curByte;
			}
                } else if (rv == 0) {
                        fprintf(stderr, "Read Zero bytes.\n");
                        return rv;
                } else {
                        fprintf(stderr, "Read returned negative: %d.\n", rv);
                        return rv;
                }
        }
        return rv;
}
