/* rawtest.c
 *
 * $Id: rawtest.c,v 1.3 2000/12/04 03:37:03 alderman Exp $
 */

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

#ifdef FREEBSD
#define RAWDEV "/dev/rda2s1e"
#else
#define RAWDEV "/dev/rdsk/c2t3d0s6"
#endif

#include "global.h"

/* This is just a little test to become more comfortable with the
 * techniques of raw I/O.
 */
int main(void) {
	struct stat sbuf;
	int rv;
	int i;
	int fd;
	int ctr = 0;
	char sum;
	char buf[MAX_BUF_SIZE];
	
	fd = open(RAWDEV, O_RDONLY, NULL);
	if(fd < 1) { 
		printf("open error");
		exit(1);
	}
	rv = fstat(fd, &sbuf);
	if(rv != 0) {
		printf("fstat error: %d\n",rv);
		exit(1);
	}
	printf("Size: %d\n",sbuf.st_size);

	while(readMeg(&buf,fd) > 0) { 
		sum = 0;
		for(i=0; i < NUMBYTES; i++) {
			sum += buf[i];
		}

		printf("Block %d, sum %d\n",++ctr, sum); 
	}

}

int readMeg(char *buf, int fd) {
        int curByte = 0;
        int rv;
	int block_size = NUMBYTES;

        while(1) {
#ifdef DEBUG
                fprintf(stderr, "Commencing read %d, %lu, %d, %d\n", fd, (unsigned long)&buf, block_size, curByte);
#endif
                rv = read(fd, buf, block_size - curByte);
#ifdef DEBUG
                fprintf(stderr, "Read %d bytes.\n",rv);
#endif
                curByte += rv;
                if(rv > 0) {
                        // fprintf(stderr, "Read %d bytes.\n",rv);
                        if (curByte < block_size) {
                                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;
}

