/* bigfile.c
 *
 * $Id: readdisk.c,v 1.3 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"

/* Comment out the following line to actually do performance tests. */
// #define CHECK_CHECKSUMS

int readMeg(char *buf, int fd);

int main(int argc, char *argv[]) {
        int fd, i;
        char buf[NUMBYTES+1];
#ifndef CHECK_CHECKSUMS
        struct timespec now_tv;
        long now, last;
#endif
#ifdef CHECK_CHECKSUMS
	int j;
	char cksum = 0;
#endif

#ifndef CHECK_CHECKSUMS
        clock_gettime(CLOCK_REALTIME, &now_tv);
        last = tv_to_msec(&now_tv);
#endif

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

#ifdef __SOLARIS__
        fd = open64(RAWDEV, O_RDONLY | O_LARGEFILE, NULL);
#else
        fd = open(RAWDEV, O_RDONLY, NULL);
#endif /* __SOLARIS__ */

        if(fd < 1) {
                printf("error: fd %d\n",fd);
        }
        for (i = 0; i < DISKSIZE; i++) {
#ifndef CHECK_CHECKSUMS
                if(i%100 == 0) {
                        clock_gettime(CLOCK_REALTIME, &now_tv);
                        now = tv_to_msec(&now_tv);
                        printf("%d: %ld\n", i/ 100, now - last);
                        last = now;
                }
#endif
                if(readMeg(buf, fd) < 0) {
                        fprintf(stderr, "Exiting with i = %d.\n", i);
                        exit(1);
                }
#ifdef CHECK_CHECKSUMS
		cksum = 0;
		for(j = 0; j < NUMBYTES; j++) {
			cksum ^= buf[j];
		}
		printf("Block: %d %d\n",i,cksum);
#endif /* CHECK_CHECKSUMS */


        }
	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;
}
