#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#include <tc/tc_api.h>
#include <tc/tc_type.h>
#include <tc/tc_errcode.h>

void _tc_print_format_binary(const unsigned char* in, const unsigned int len) 
{
    int i=0;
    printf("Size=%d\n", len);
    for(; i<len; i++) {
        printf("%02x", in[i]);
        if(0 == (i+1)%4) printf(" ");
        if(0 == (i+1)%32) printf("\n");
    }
    if(0 != (i+1)%32) printf("\n");
}

int main()
{
    TC_RC rc;

    TC_HANDLE tc_handle = 0;
    uint32_t  primary_index;
    uint32_t  key_index;
    uint32_t  ulNVIndex = 0x1500001;
    uint32_t  ulHierarchy = 0x40000001;
    TC_BUFFER write_msg, read_msg;
    write_msg.buffer = (unsigned char *)malloc(8);
    write_msg.size = 0;
    read_msg.buffer = (unsigned char *)malloc(8);
    read_msg.size = 0;
    memcpy(write_msg.buffer, "ok", 3);
    write_msg.size = 3;

    rc = TC_Start("tabrmd",
                  &tc_handle);
    if (rc != TC_SUCCESS) {
        printf("Failed to start TC device\n");
        goto end;
    }

    rc = TC_NVDefine(tc_handle,
                     ulNVIndex,
                     ulHierarchy,
                     2048,
                     NULL);
    if (rc != TC_SUCCESS) {
        printf("Failed to NVDefine\n");
        goto end;
    }

    rc = TC_NVWrite(tc_handle,
                    ulNVIndex,
                    ulHierarchy,
                    NULL,
                    0,
                    &write_msg);
    if (rc != TC_SUCCESS) {
        printf("Failed to NVWrite\n");
        goto end;
    }

    rc = TC_NVRead(tc_handle,
                   ulNVIndex,
                   ulHierarchy,
                   NULL,
                   0,
                   3,
                   &read_msg);
    if (rc != TC_SUCCESS) {
        printf("Failed to NVRead\n");
        goto end;
    }

    _tc_print_format_binary(read_msg.buffer, read_msg.size);
    printf("%s\n", read_msg.buffer);

    free(write_msg.buffer);
    free(read_msg.buffer);

    rc = TC_NVRelease(tc_handle,
                      ulNVIndex,
                      ulHierarchy,
                      NULL);
    if (rc != TC_SUCCESS) {
        printf("Failed to NVRelease\n");
        goto end;
    }

end:
    rc = TC_End(&tc_handle);
    if (rc != TC_SUCCESS) {
        printf("Failed to stop TC device\n");
    } 
}