
#import "DiskSpeed.h"

@implementation DiskSpeed
#define 	meg 	(1024.0 * 1024.0)

- (BOOL)canRunBenchmark
{
	if(access([deviceCell stringValue],R_OK)){
		[readCell setStringValue:"CANNOT OPEN DEVICE"];
		return NO;
	}
	return YES;
}

- setupBenchmark
{
	const 	size = 1024;
	int 	bit;
	char 	buf[size];
	const 	char *name = [deviceCell stringValue];
	int	fd = open(name,O_RDONLY,0666);

	if(fd<0){
		return nil;
	}
	
	/* find the size of the disk */

	disksize	= 0;
	for(bit=31;bit>10;bit--){
		disksize	|= 1<<bit;
		lseek(fd,disksize,SEEK_SET);
		if(read(fd,buf,size)==-1){
			disksize &= ~(1<<bit);
		}
	}
	return self;
}

- benchmark
{
	long		bytes;
	const char 	*name 	= [deviceCell stringValue];
	int		fd 	= open(name,O_RDWR,0666);


	if(fd<0){
		return nil;
	}
	

	bytes = 20 * meg;
	if(bytes > disksize){
		bytes = disksize * 0.80;
	}
	
	{
			const	readsize = 65536 * 4;
			char 	buf[readsize];
			int 	i;

			lseek(fd,0,0);
			totalbytes = 0;

			for(i=0;i<bytes;i+=readsize){
				int	q;

				q = read(fd,buf,readsize);
				
				if(q<0) {
					NXRunAlertPanel(0,"Read error",0,0,0);
					break;
				}
				totalbytes	+= q;
			}
			
		}
	close(fd);
	return self;
}

-  shutdownBenchmark
{
	double	megread,megxfer;
	char	buf[256];

	megread	= totalbytes / meg;
	megxfer	= (megread * 1024) / wallTime;
	[readCell setDoubleValue:megxfer];

	sprintf(buf,"Disk read speed: %g",megxfer);
	[self	logResults:buf];

	return self;
}

@end
