/*
  diskio.c

  Basic I/O operations for 1.44 Mb diskettes.
  
  MAT 4970
  Bill Slough
*/

#include <stdio.h>
#include <stdlib.h>
#include "diskio.h"
#include <fcntl.h>
#include <unistd.h>

int DisketteRead(char * filename, unsigned int sector, char * buffer) {
    /* open the file for reading */
    int fd = open(filename, O_RDONLY);
    if (fd == -1) {
	fprintf(stderr, "No such file: %s\n", filename);
	return -1;
    }

    /* skip the appropriate number of bytes to reach the desired sector */
    off_t position = lseek(fd, sector*BLOCKSIZE, SEEK_SET);
    if (position != sector*BLOCKSIZE) {
	fprintf(stderr, "Sector not found.\n");
	close(fd);
	return -1;
    }

    /* read a block of data */
    ssize_t nread = read(fd, buffer, BLOCKSIZE);
    if (nread != BLOCKSIZE) {
	fprintf(stderr, "Could not read all bytes of the desired sector.\n");
	close(fd);
	return -1;
    }

    /* close the file */
    close(fd);
    return 0;
}


int DisketteWrite(char * filename, unsigned int sector, char * buffer) {
    /* open the file for writing */
    int fd = open(filename, O_WRONLY);
    if (fd == -1) {
	fprintf(stderr, "Could not open the file for writing.\n");
	return -1;
    }

    /* skip the appropriate number of bytes to reach the desired sector */
    off_t position = lseek(fd, sector*BLOCKSIZE, SEEK_SET);
    if (position != sector*BLOCKSIZE) {
	fprintf(stderr, "Sector not found.\n");
	close(fd);
	return -1;
    }

    /* write a block of data */
    ssize_t nwritten = write(fd, buffer, BLOCKSIZE);
    if (nwritten != BLOCKSIZE) {
	fprintf(stderr, "Could not write all bytes of the desired sector.\n");
	close(fd);
	return -1;
    }

    /* close the file */
    close(fd);
    return 0;
}


void DisplaySector(char * values) {
    /* output the bytes, in hexadecimal */
    const int PerRow = 16;
    int i;
    for (i = 0; i < BLOCKSIZE; i++) {
	/* view the ith byte as an unsigned integer quantity */
	unsigned char current_byte = (unsigned char) values[i];

	/* output the value of this byte as a two-digit hexadecimal quantity */
	printf(" %02x", current_byte); 

	/* advance to the next row when necessary */
	if ((i + 1) % PerRow == 0)  
	    printf("\n");
    }
}
