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

void help()
{
	printf(	"Usage:	checker file_name\n");

}

#define PKT_SIZE	4096
#define MAX_VAL		0x3FFF

struct pkt_t {
	uint16_t seq_num;
	uint16_t data[];
};

int main(int argc, char *argv[])
{
	FILE *fp = NULL;
	uint8_t buf[PKT_SIZE];
	char *fn = NULL;
	uint16_t val = 0;
	uint16_t exp_val = 0;
	uint16_t *ptr = NULL;
	int ret = 0;
	int pos = 0;
	uint16_t seq_num;
	struct pkt_t *pktp = NULL;
	printf("*** Cecilie RDMA application - data checker ***\n");

	if(argc != 2){
		printf("Not enough arguments\n");
		help();
		return 1;
	}

	fn = argv[1];
	printf("File name: %s\n", fn);
	memset(buf, 0x00, sizeof(buf));

	fp = fopen(fn, "rb");
	if(!fp){
		printf("Couldn't open file %s\n", fn);
		return 1;	
	}

	
	while((ret = fread(buf, sizeof(uint8_t), sizeof(buf), fp)) == sizeof(buf)){
		if(ptr == NULL){
			pktp = (struct pkt_t*)buf;
			exp_val = pktp->data[0];
			seq_num = pktp->seq_num;
		}
		if(seq_num != pktp->seq_num){
			printf("Packet out of sequence\n");
		}

		pktp = (struct pkt_t*)buf;
		for(int i = 0; i < sizeof(buf)/sizeof(uint16_t)-1; i++){
			if(pktp->data[i] != exp_val){
				printf("Received value is not same as expected value od position %08x (val %04x != exp %04x)\n", pos*2, pktp->data[i], exp_val);
				exp_val = pktp->data[i];
//				goto error;
			}
			exp_val++;
			if(exp_val > MAX_VAL)
				exp_val = 0;
			pos++;
		}
	}
	
	fclose(fp);
	printf("Received data are OK\n");
	return 0;

error: 
	fclose(fp);
	printf("Received value is not same as expected value od position %08x (val %04x != exp %04x)\n", pos*2, *ptr, exp_val);
	return 2;


}

