#include "eclib.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int print_all()
{
    uint8_t value = 0;
    for (int i = 0; i <= 0x0F; i ++) {
        for (int j = 0; j <= 0x0F; j ++) {
            value = read_ec_ram(i * 16 + j);
            printf("%02X ", value);
        }
        printf("\n");
    }
}

int main(int argc, char **argv)
{
    uint8_t value = 0;
    uint8_t addr = 0;
    bool isread = true;
    int ch;
     if (!port_dev_init()) {
        printf("Please run as root user!\n");
        return -1;
    }
    if (argc > 1)
    {
        while ((ch = getopt(argc, argv, "a:rw:l")) != -1)
        {
            switch (ch) 
            {
                case 'a':
                    addr = strtol(optarg, NULL, 16);
                    break;
                case 'r':
                    isread = true;
                    break;
                case 'w':
                    isread = false;
                    value = strtol(optarg, NULL, 16);
                    break;
                case '?':
                    printf("-a [address] -r read -w [value] write\n");
                    return -1;
            }
        }
        if(isread)
        {
            printf("0x%02X", read_ec_ram(addr)); 
        }
        else
        {
            printf("write 0x%02X=0x%02X\n", addr, value);
            write_ec_ram(addr, value);
        }
    }
    else
    {
        print_all();
    }
    
    port_dev_exit();

    return 0;
}