#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <devctl.h>
#include <fcntl.h> 
#include <errno.h>
#include <inttypes.h>
#include "dcmd_f3s.h"


int fd;

int main(int argc, char **argv)
{
	int i, ret, len, chip;
	unsigned char *buf;
        char *path1 = argv[1];

        fd = open(path1, O_RDWR, S_IRUSR | S_IWUSR);
        if (fd == -1) {
                perror("open failed");
                exit(1);
        }
	if (argc < 4) {
		fprintf(stderr,"usage: readssr /dev/fs0 size chip");
		return -1;
	}

	len = atoi(argv[2]);
	chip = atoi(argv[3]);
	fprintf(stderr, "readssr: read ssr from chip[%d], len %d bytes \n", chip, len);

	buf = malloc(len + 64);
	if (buf == NULL) {
		fprintf(stderr, "no enough memory\n");
		return -1;
	}
	memset (buf, 0x0, len);

	//FIXME: move to targeted chip, assume chip size 128MB here
	lseek(fd, chip * 0x8000000, SEEK_SET);

	// read test
	ret = devctl(fd, DCMD_F3S_READSSR, buf, len, NULL);
	if (ret != EOK) {
		fprintf(stderr, "devctl failed %d\n", ret);
		return (-1);
	}
	fprintf(stderr, "read secsi done.%d\n", ret);
	for (i=0;i<len;i+=4) {
		fprintf(stderr, "buf[%d...%d]: 0x%02X 0x%02X 0x%2X 0x%02X \n",i, i+4, buf[i], buf[i+1], buf[i+2], buf[i+3]);
	}

	close(fd);
	free(buf);
	return 0;
}
