/* Graciously written by Scott Anderson for System Programming
 * Spring 2005
 *
 * Mark edited it to conform to Linux coding standards, Spring 2008.
 */

#include <stdio.h>
#include <stdlib.h>		/* for exit() */
#include <sys/types.h>		/* for open() */
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>		/* for strcpy */

#include "global_defs.h"	// for Status type
#include "page.h"		// for page size
#include "random_rw.h"

int main( int argc, char* argv[] )
{
	int file_size;
	int dbf;
	int i;
	char buf[128];
	char command;
	int block_num;
	struct Page a_block;

	if ( argc < 3 ) {
		printf("Usage: %s dbfile size_in_blocks [nobug]\n", argv[0]);
		exit(1);
	}
	file_size = atoi(argv[2]);

	dbf = open(argv[1], O_RDWR | O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP );
	if ( -1 == dbf ) {
		perror("Couldn't open file");
		exit(2);
	}
	if ( argc > 3 && !strcmp("nobug", argv[3]) ) {
		/* Write the last block, thereby implicitly zeroing all
		   preceeding blocks and allowing random seeks.  If
		   you don't do this, you can write beyond the end of
	           the file, but you can't read. */ 
		for (i = 0; i < sizeof(a_block.data); i++)
			a_block.data[i] = '\0';
		random_write(dbf, file_size - 1, &a_block);
	}

	for (;;) {
		for (i = 0; i < sizeof(a_block.data); i++)
			a_block.data[i] = '\0';

		printf("command: ");
		fgets(buf,sizeof(buf),stdin);
		command = buf[0];

		if ( 'q' == command ) break;
		switch ( command ) {
		case 'r' :
			printf("What block do you want to read? ");
			/* I don't bother checking for errors in fgets */
			fgets(buf, sizeof(buf), stdin);
			block_num = atoi(buf);
			if ( block_num > file_size ) {
				printf("Too big; file: %d blocks.", file_size);
				continue;
			}
			random_read(dbf, block_num, &a_block);
			printf("%s\n", a_block.data);
			break;
		case 'w':
			printf("What block do you want to write? ");
			fgets(buf, sizeof(buf), stdin);
			block_num = atoi(buf);
			if ( block_num > file_size ) {
				printf("Too big; file: %d blocks.", file_size);
				continue;
			}
			printf("What data do you want to write? ");
			fgets(buf, sizeof(buf), stdin);
			strcpy(a_block.data, buf); /* copy it into the page */
			random_write(dbf, block_num, &a_block);
			break;
		}
	}
	close(dbf);
	return 0;
}
