/*
 * Copyright (c) 2009 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */

/*
 * helloworld.c: simple test application
 */



#include <stdio.h>
#include<xgpio.h>
#include "platform.h"
#include "xparameters.h"
#include "xio.h"
#include<string.h>
#include<stdlib.h>
#include<assert.h>
#include "xtmrctr.h"
#include "xtmrctr_i.h"
/*int main()
{
    init_platform();

    print("Hello World\n\r");

    cleanup_platform();

    return 0;
}*/

typedef unsigned long long field_t;
#define FIELD_M     7
#define FIELD_W     3
#define MSB			31
#define FIELD_P ((1UL << MSB)  - 1)
#define   BYTESIZE      (MSB * FIELD_M / 8 + 1)
#define MULALGO0
#define num 1

static field_t con_one[FIELD_M] = {1, 0x68768cde, 0x5f6ca339, 0x5b9f5d37, 0x354d412e, 0x5f57d0ba, 0x47d860c5};



field_t CURVECONST_A[FIELD_M] = {0x7FFFFFFC, 0, 0, 0, 0, 0, 0};
field_t CURVECONST_B[FIELD_M] = {624,        0, 0, 0, 0, 0, 0};



//field_t CURVE_BASEPT_X[FIELD_M] = {0X7F7DC269UL, 0X4E28A2CAUL, 0X666B0192UL, 0X1A724B7UL, 0X24F85C51UL, 0X511020A5UL, 0X1B106B7FUL};
//field_t CURVE_BASEPT_Y[FIELD_M] = {0X287B1945UL, 0X5F6CC1A5UL, 0X10F48656UL, 0X3FAFD2C9UL, 0X56431800UL, 0X72B0BBBBUL, 0X1949F6DAUL};

field_t CURVE_BASEPT_X[num][FIELD_M] = {

		{1804289383,846930886,1681692777,1714636915,1957747793,424238335,719885386}


       };

    /*field_t CURVE_BASEPT_Y[FIELD_M] = {
    4324075587266815854ULL, 42263446425800273603ULL, 876137797417765149ULL, 106389378469014827ULL, 44469853093370071416ULL, 1360097373849218934ULL, 1206088058734080628ULL
    };*/
    field_t CURVE_BASEPT_Y[num][FIELD_M] = {

    		{1804289383,846930886,1681692777,1714636915,1957747793,424238335,719885386}


       };






typedef struct _point_t{
	field_t x[FIELD_M];
	field_t y[FIELD_M];
	field_t z[FIELD_M];   // used only in projective coordinate system, else ignored
}point_t;

void copy_element(field_t *d, field_t *s)
{
	memcpy(d, s, FIELD_M*sizeof(field_t));
}

void init_element(field_t a[5])
{
	memset(a, 0, FIELD_M*sizeof(field_t));
}

static void fillzeros(point_t *dest)
{
	memset(dest, 0, sizeof(point_t));
}

void copypoint(point_t *dest, point_t *src)
{
	memcpy(dest, src, sizeof(point_t));
}

field_t baseadd(field_t a, field_t b)
{
	field_t c1 = a + b;
	field_t c2 = c1 - FIELD_P;


	return ((c1 >= FIELD_P) ? c2 : c1);
}

static field_t basesub(field_t a, field_t b)
{
	field_t c;
	c = (baseadd(a, FIELD_P - b));

	return c;
}

/*#if defined(MULALGO0)
static void sanitycheck()
{
	if(FIELD_P >= (1U<<31)-1){
		print("Wrong Multiplier Configured\n");
		//exit(-1);
	}
}*/
/*
 * This function can be used when the field cardinality is less than 2^32
 */
static field_t basemul(field_t a, field_t b)
{
	unsigned long long pr, q1;

	pr = a * (unsigned long long)b;
	q1 = pr / FIELD_P;

//	printf("%016llx\n", pr);

	return (pr - (q1 * FIELD_P));
}

static field_t basemulx2(field_t a)
{
	field_t msb = a >> (MSB - 1);
	a = a << 1;
	return (a & FIELD_P) + msb;
}

/* Constant multiplication with 3 */
inline static field_t basemulx3(field_t a)
{
	field_t a2;
	field_t msb = a >> (MSB - 1);
	a2 = ((a << 1) + msb) & FIELD_P;
	return baseadd(a2 , a);
}

/* Constant multiplication with 4 */
inline static field_t basemulx4(field_t a)
{
	field_t msb = a >> (MSB - 2);
	a = a << 2;
	return (a & FIELD_P) + msb;
}

/* Constant multiplication with 8 */
inline static field_t basemulx8(field_t a)
{
	field_t msb = a >> (MSB - 3);
	a = a << 3;
	return (a & FIELD_P) + msb;
}

#define ISEVEN(x)     ((x & 1ULL) == 0)

/* Binary Euclidean Algorithm to find
   the Inverse of element a in GF(FIELD_P)
*/
static field_t baseinverse(field_t a)
{
	field_t u, v, e;
	field_t x1, x2;
	field_t Pby2;

	if(a == 0) return 0;
	Pby2 = (FIELD_P + 1) >> 1;
	u = a; v = FIELD_P;
	x1 = 1ULL; x2 = 0ULL;

	while(u != 1 && v != 1){
		while(ISEVEN(u)){
			u = u >> 1;
			if (ISEVEN(x1))
				x1 = x1 >> 1;
			else{
				x1 = ((x1 - 1) >> 1) + Pby2;
			}
		}
		while(ISEVEN(v)){
			v = v >> 1;
			if (ISEVEN(x2))
				x2 = x2 >> 1;
			else{
				x2 = ((x2 - 1) >> 1) + Pby2;
			}
		}
		if(u >= v){
			u = basesub(u, v);
			x1 = basesub(x1, x2);

		}else{
			v = basesub(v, u);
			x2 = basesub(x2,x1);
		}
	}
	if (u == 1){
		return x1 ;
	}
	else{
		return x2;
	}
}



static void oefadd(field_t *res, field_t *a, field_t *b)
{
	int i;

	for(i=0; i<FIELD_M; ++i){
		res[i] = baseadd(a[i], b[i]);
	}
}

static void oefsub(field_t *res, field_t *a, field_t *b)
{
	int i;

	for(i=0; i<FIELD_M; ++i){
		res[i] = basesub(a[i], b[i]);
	}
}

/*
	OEF Classical multiplier. Also does the modular reduction.
	Computes : res = ( a * b ) mod P
 */
static void oefmul(field_t *res, field_t *a, field_t *b)
{
	int i, i1, j;
	field_t upper, tmp;

	for(i=0; i<FIELD_M; ++i){
		res[i] = 0;
		for(j=0; j<i+1; ++j){
			tmp = basemul(a[j], b[i-j]);
			res[i] = baseadd(res[i], tmp);
		}

		i1 = i + FIELD_M;
		upper = 0;
		for(j=i1-FIELD_M+1; j<FIELD_M; ++j){
				tmp = basemul(a[j], b[i1-j]);
				upper = baseadd(upper, tmp);
		}
		res[i] = baseadd(res[i], basemul(upper, FIELD_W));
	}
}

/* OEF Square - is there a better algorithm ? */
static void oefsqr(field_t *res, field_t *a)
{
	oefmul(res, a, a);
}

/* OEF Multiplication with constant 2 */
static void oefmulx2(field_t *res, field_t *a)
{
	int i;
	for(i=0; i<FIELD_M; ++i){
		res[i] = basemulx2(a[i]);
	}
}

/* OEF Multiplication with constant 3 */
static void oefmulx3(field_t *res, field_t *a)
{
	int i;
	for(i=0; i<FIELD_M; ++i){
		res[i] = basemulx3(a[i]);
	}
}

/* OEF Multiplication with constant 4 */
static void oefmulx4(field_t *res, field_t *a)
{
	int i;
	for(i=0; i<FIELD_M; ++i){
		res[i] = basemulx4(a[i]);
	}
}

/* OEF Multiplication with constant 8 */
static void oefmulx8(field_t *res, field_t *a)
{
	int i;
	for(i=0; i<FIELD_M; ++i){
		res[i] = basemulx8(a[i]);
	}
}

static void frobeniusmap(field_t *b, field_t *a)
{
	int i;

	for(i=0; i<FIELD_M; ++i){
		b[i] = basemul(a[i], con_one[i]);
	}
}

static void oefinverse(field_t *ainv, field_t *a)
{
	field_t b1[FIELD_M], b2[FIELD_M];
	field_t cinv;
	int i;

	init_element(b1);
	copy_element(b2, a);

	for(i = 0; i < FIELD_M-1; ++i){
		frobeniusmap(b1, b2);
		oefmul(b2, b1, a);
	}


	cinv = baseinverse(b2[0]);
	init_element(b2);
	b2[0] = cinv;

	oefmul(ainv, b2, b1);

#ifdef __DEBUG__
	oefmul(b1, a, ainv);
	printfield(b1);
	if (b1[0] != 1) goto fatalerror;
	for(i = 1; i < FIELD_M; ++i){
		if(b1[i] != 0) goto fatalerror;
	}
	return;
fatalerror:
	print("oefinv: Error in finding inverse (at i)\n");
	printfield(a);
	printfield(ainv);
	exit(-1);
#endif

}
static void pt_double(point_t *pt)
{
	field_t a[FIELD_M], b[FIELD_M], c[FIELD_M], d[FIELD_M];
	field_t temp1[FIELD_M], temp2[FIELD_M];

	/* A <- y1^2 */
	oefsqr(a, pt->y);           // a = y1^2

	/* B <- [[4 . x1] . A] */
	oefmulx4(temp1, pt->x);     // 4.x1
	oefmul(b, temp1, a);        // temp1.a

	/* D <- (3 . X1^2) + (CURVE_A . z1^4) */
	oefsqr(c, pt->x);           // x1^2
	oefmulx3(temp1, c);         // 3.x1^2
	oefsqr(temp2, pt->z);       // z1^2
	oefsqr(c, temp2);           // z1^4
	oefmul(temp2, CURVECONST_A, c);        // CURVE_A.z1^4
	oefadd(d, temp2, temp1);    // 3.z1^2 + CURVE_A.z1^4

	/* C <- [8 . [A^2]] */
	oefsqr(temp1, a);           // a^2
	oefmulx8(c, temp1);         // 8.a^2

	/* X3 <- [[D^2] - [2B]] */
	oefsqr(temp1, d);           // d^2
	oefmulx2(temp2, b);         // 2.b
	oefsub(pt->x, temp1, temp2); // d^2 - 2b

	/* Z3 <- [2[Y1 . Z1]] */
	oefmul(temp1, pt->y, pt->z);// y1.z1
	oefmulx2(pt->z, temp1);     // 2.y1.z1

	/* Y3 <- [[D(B - X3)] - C] */
	oefsub(temp1, b, pt->x);    // b - x3
	oefmul(temp2, temp1, d);    // d(b - x3)
	oefsub(pt->y, temp2, c);    // d(b - x3) - c

}
static void pt_add(point_t *pt1, point_t *pt2)
{
	field_t a[FIELD_M], b[FIELD_M], c[FIELD_M], d[FIELD_M], e[FIELD_M];
	field_t f[FIELD_M], g[FIELD_M], h[FIELD_M], i[FIELD_M];


	oefsqr(a, pt1->z);          // a = z1^2
	oefmul(b, pt1->z, a);       // b = z1.a
	oefmul(c, pt2->x, a);       // c = x2.a
	oefmul(d, pt2->y, b);       // d = y2.b
	oefsub(e, c, pt1->x);       // e = c - x1
	oefsub(f, d, pt1->y);       // f = d - y1
	oefsqr(g, e);               // g = e^2
	oefmul(h, g, e);            // h = g.e
	oefmul(i, g, pt1->x);       // i = x1.g

	// x3 = f^2 - (h + 2i)
	oefsqr(a, f);             // f^2
	oefsub(b, a, h);          // f^2 - h
	oefmulx2(c, i);           // 2i
	oefsub(pt1->x, b, c);     // f^2 - h - 2i

	// y3 = f(i - x3) - y1.h
	oefsub(a, i, pt1->x);     // i - x3
	oefmul(b, f, a);          // f(i-x3)
	oefmul(c, h, pt1->y);     // y1.h
	oefsub(pt1->y, b, c);     // f(i-x3) - y1.h

	// z3 = z1.e
	copy_element(d, pt1->z);
	oefmul(pt1->z, e, d); // e.z1
}






void smul(field_t *k, point_t *basepoint, point_t *res,int bx)
{
	int word, msb, i, j, found=0;
	int malloced;



	int deb,seal;
	Xuint32 status;
	XGpio pin;

	status=XGpio_Initialize(&pin,XPAR_GENERIC_GPIO_DEVICE_ID);
	    	           // if (status != XST_SUCCESS)
	    	             //    return XST_FAILURE;

	XGpio_SetDataDirection(&pin,1,0x0);



	point_t q;
	field_t zinv[FIELD_M], zinv2[FIELD_M], zinv3[FIELD_M];

	malloced = 0;
	if(basepoint == NULL){
		malloced = 1;
		basepoint = (point_t *) malloc(sizeof(point_t));
		// initilize  basepoint
		copy_element(basepoint->x, CURVE_BASEPT_X[bx]);
		copy_element(basepoint->y, CURVE_BASEPT_Y[bx]);
	}
	//for(i=0;i<FIELD_M;i++)
		//xil_printf("basepoint_x=%x",basepoint->x[i]);
	init_element(basepoint->z);
	basepoint->z[0] = 1;

	// find the msb in k
	word = FIELD_M - 1;
	msb  = sizeof(field_t)*8 - 1;
	while(1){
		if(k[word] >> msb){
			copypoint(&q, basepoint);
			break;
		}

		msb--;
		if(msb < 0){
			msb = sizeof(field_t)*8-1;
			word--;
			if(word < 0){
				/* We have not found a leading MSB so fill q with 0s */
				fillzeros(&q);
				break;
			}
		}
	}
			// double and add
				for(i=word; i>=0; --i){
					for(j=msb-1; j>=0; --j){
						unsigned long Curr_timer,Init_timer,Calibration,BeginTime,EndTime,TIMER_COUNTER_0,XPAR_XPS_TIMER_1_DEVICE_ID,TimeRun;

						    /*for(i=0;i<FIELD_M;i++)
						    	xil_printf("%lu",alpha[i]);*/

						   // XTmrCtr XPS_Timer;
						   // XTmrCtr_Initialize(&XPS_Timer, XPAR_XPS_TIMER_1_DEVICE_ID);
						    //XTmrCtr_SetOptions(&XPS_Timer, TIMER_COUNTER_0, XTC_ENABLE_ALL_OPTION | XTC_AUTO_RELOAD_OPTION);
						    //Init_timer = XTmrCtr_GetValue(&XPS_Timer, TIMER_COUNTER_0);
						   // Curr_timer = XTmrCtr_GetValue(&XPS_Timer, TIMER_COUNTER_0);
						   // Calibration = Curr_timer - Init_timer;
						    //xil_printf("Calibration value is %d \r\n", Calibration);


						    	 //Start timer
						  //  BeginTime = XTmrCtr_GetValue(&XPS_Timer, TIMER_COUNTER_0);

						//XGpio_Initialize(&pin,XPAR_GENERIC_GPIO_DEVICE_ID);
						seal=1;
						XGpio_Initialize(&pin,XPAR_GENERIC_GPIO_DEVICE_ID);
						XGpio_DiscreteWrite(&pin, 1, seal);

						pt_double(&q);
						seal=!seal;
						XGpio_DiscreteWrite(&pin, 1, seal);

						   // EndTime = XTmrCtr_GetValue(&XPS_Timer, TIMER_COUNTER_0);

						       //Calculate runtime taking calibration into account
						   	// TimeRun = EndTime - BeginTime - Calibration;

						    // xil_printf("timrun=%x \n", TimeRun);
						    // xil_printf("endtime=%x \n", EndTime);
						//seal=1;
						//XGpio_DiscreteWrite(&pin, 1, seal);
						//pt_double(&q);
						//seal=!seal;
						//XGpio_DiscreteWrite(&pin, 1, seal);

						if((k[i] >> j) & 1){
							//seal=!seal;
							//XGpio_DiscreteWrite(&pin, 1, seal);
							//BeginTime = XTmrCtr_GetValue(&XPS_Timer, TIMER_COUNTER_0);
							seal=!seal;
							XGpio_DiscreteWrite(&pin, 1, seal);


							pt_add(&q, basepoint);
							seal=!seal;
							XGpio_DiscreteWrite(&pin, 1, seal);
							//EndTime = XTmrCtr_GetValue(&XPS_Timer, TIMER_COUNTER_0);
							//TimeRun = EndTime - BeginTime - Calibration;
							//xil_printf("%d \n", TimeRun);
							//seal=!seal;
							 //XGpio_DiscreteWrite(&pin, 1, seal);

						}
					}
					msb = sizeof(field_t)*8;
				}

				// convert to affine coordinates
				oefinverse(zinv, q.z);          // zinv
				oefsqr(zinv2, zinv);            // zinv^2
				oefmul(zinv3, zinv2, zinv );    // zinv^3
				oefmul(res->x, q.x, zinv2);     // x.(zinv^2)
				oefmul(res->y, q.y, zinv3);     // y.(zinv^3)
				init_element(res->z);
				res->z[0] = 1;

				if(malloced) free(basepoint);
	}




int main()
{
    init_platform();
    int x_cor,x_cor1;
    //field_t alpha[FIELD_M]={0xff,0xff,0xff,0xff,0xff,0xff,0xff};
    field_t alpha[FIELD_M]={0x5,0x0,0x0,0x0,0x0,0x0,0x0};
    point_t C1;

    unsigned long Curr_timer,Init_timer,Calibration,BeginTime,EndTime,TIMER_COUNTER_0,XPAR_XPS_TIMER_1_DEVICE_ID,TimeRun;
    XGpio pin;
    Xuint32 status;
    status=XGpio_Initialize(&pin,XPAR_GENERIC_GPIO_DEVICE_ID);
    XGpio_SetDataDirection(&pin,1,0x0);

    int inum,i,seal;
    int bx=0;




    for(inum=0;inum<num;inum++)
            {
            	////////seal=1;
            	///////XGpio_DiscreteWrite(&pin, 1, seal);

            	smul(alpha,NULL,&C1,bx);

    /*print("x cordinate\n");
    for(i=0;i<FIELD_M;i++)
    {
    	x_cor=C1.x[i];
    	xil_printf("%d\t",x_cor);
    	x_cor1=(C1.x[i]>>32);
    	xil_printf("wrong=%d\r\n",x_cor1);
    }
    print("y coordinate\n");
    for(i=0;i<FIELD_M;i++)
       {
        	x_cor=C1.y[i];
        	xil_printf("%d\t",x_cor);
        	x_cor1=(C1.y[i]>>32);
        	xil_printf("%d\n",x_cor1);
        }*/

   ///////////// seal=0;
    ////////////        XGpio_DiscreteWrite(&pin, 1, seal);
           bx=bx+1;
           }



    print("\n work done \n\n\n\n\n\n\n\n\n");

    cleanup_platform();

    return 0;
}




