/*
 * Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
 *
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *    Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the
 *    distribution.
 *
 *    Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

/* ========================================================================== */
/*                             Include Files                                  */
/* ========================================================================== */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <xdc/std.h>
#include <xdc/cfg/global.h>//anjana
#include <xdc/runtime/Error.h>
#include <xdc/runtime/System.h>

#include <xdc/runtime/Types.h>
#include <xdc/runtime/Timestamp.h>

#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Task.h>

#include <ti/ndk/inc/stkmain.h>
//tagged by anjana
#include <ti/ndk/inc/netmain.h>
#include <ti/sysbios/timers/dmtimer/Timer.h>

#include <ti/drv/emac/emac_drv.h>
#include <ti/drv/emac/src/v4/emac_drv_v4.h>

#include <ti/csl/soc.h>
#include <ti/csl/cslr_device.h>

#include <ti/drv/gpio/GPIO.h>//anjana
#include <ti/drv/gpio/soc/GPIO_soc.h>//anjana

#include <ti/board/board.h>

/* TI-RTOS Header files */
#include <ti/drv/i2c/I2C.h>
#include <ti/drv/i2c/soc/I2C_v1.h>

/* UART Header files */
#include <ti/drv/uart/UART.h>
#include <ti/drv/uart/UART_stdio.h>
#include <ti/drv/uart/src/UART_osal.h>
#include <ti/drv/uart/soc/UART_soc.h>
#include <ti/drv/uart/src/UART_utils_defs.h>

#include <ti/csl/soc/am572x/src/csl_device_xbar.h>

/*GPIO_board.h*/
#include <ti/board/src/evmAM572x/include/board_cfg.h>
#include <ti/csl/soc/am572x/src/cslr_soc_mpu_baseaddress.h>

/* Enable the below macro to have prints on the IO Console */
//#define IO_CONSOLE

#ifndef IO_CONSOLE
#define NIMU_log                UART_printf
#else
#define NIMU_log                printf
#endif

/* ========================================================================== */
/*                             Macros                                  */
/* ========================================================================== */
/* LM Board PBx pins which are connected to GPIO pins. */
typedef enum GPIO_PUSHButton {
    USER_PB1 = 0,
    USER_PB2,
	USER_PB3
}GPIO_PUSHButton;
/**Phy address of  port 0 */
#define EMAC_CPSW_PORT0_PHY_ADDR_EVM     1
/**Phy address of port 1 */
#define EMAC_CPSW_PORT1_PHY_ADDR_EVM     2
#define MAX_TABLE_ENTRIES   3

//tagged by anjana
#define NMFACTOR 0.08099
#define DEGFACTOR 0.00015
#define PRT 1274 //for 784 prf
#define PI 3.14159265
#define RADIAN 0.0174 //PI/180
#define PIXEL_SCALE 75//450/6Nm//37.5//150//450/3Nm //18.75 as 450/24Nm //4.4118 as 450/102NM
#define UART_INSTANCE 2
#define INPUT_LENGTH           (8U)
#define AZMTH_CNT_DEG	11.37 //for 360 deg = 4096 pulses

/* ========================================================================== */
/*                            Global Variables                                */
/* ========================================================================== */

/**Task handle for EIP*/
Task_Handle main_task;
static int nimu_device_index = 0U;
NIMU_DEVICE_TABLE_ENTRY NIMUDeviceTable[MAX_TABLE_ENTRIES];

void InitialiseUART_3(void);

extern int CpswEmacInit (STKEVENT_Handle hEvent);
//tagged by anjana
void Init_variables(void);
void TimerInitialization();
void myIsr(UArg arg);
void app_delay(uint32_t delayValue);
void MicroSecDelay( UInt32 uSDelay );
void SendDataToPC();
void PixelCalc();
void CopyfirstPRT();
void Cmp_Copy_FivePRT();
/* Callback function */
void AppGpioCallbackFxn(void);
void AppGpioCallbackFxn_1(void);
void AppGpioCallbackFxn_2(void);
void UART_callback(UART_Handle, void *buf, size_t);
void Read_AzimuthCnt();
extern UART_HwAttrs uartInitCfg[];
extern void UART_putNum_Anjana(int32_t value);
struct sockaddr_in sin1;
//---------------------------------------------------------------------------
// Configuration
//
//char *HostName1    = "tidsp";

volatile uint32_t gpio_intr_triggered = 0,gpio_intr_triggered_1=0;
char HeadingMark=0,prv_HeadingMark=0;
char *LocalIPAddr1 = "192.168.1.2";
char *IPAddr = "192.168.1.144";
unsigned int CountPRT,CountSecond,TCP_TXBuffer,BearingCount;
//float Bearingangle;
char scanPrompt[256] __attribute__ ((aligned (128)));
char scanPrompt_try[4];
/* Length of the input in number of characters */
#define UART_TEST_READ_LEN     (8U)
Bool Start_Count,NextData,NextTheta,NextSerialData;
UInt16 NoOfSwipe,NoOfPRT,PrvRow,row,clmn,NoofdataSend,test=2200;
Int16 THIndx_prv,t,target_end,target_start,THIndex;
Bool Start_PRT,Trigger,target_Flag,targetEnd_Flag,RangeEnd_flag,targetStart_Flag,BufferFillFlg,FalledgeFlag,RiseedgeFlag, NextPRTFlg,ThetaFlg,NextTrgtFlg_start,NextTrgtFlg_end;

UInt16 XY_buffer_1[360][1274];
UInt16 XY_buffer_2[1100];
UInt16 XY_OneSwipe_buff[6][13];
SemaphoreP_Handle callbackSem = NULL;
int32_t AzimuthCnt=0;
//int32_t addrScanPrompt;
UART_Handle    uart = NULL;
Timer_Handle timerHandle;
float SinTheta[360]={0,0.02,0.03,0.05,0.07,0.09,0.10,0.12,0.14,0.16,0.17,0.19,0.21,0.22,0.24,0.26,0.28,0.29,0.31,0.33,0.34,0.36,0.37,0.39,0.41,
					0.42,0.44,0.45,0.47,0.48,0.50,0.52,0.53,0.54,0.56,0.57,0.59,0.60,0.62,0.63,0.64,0.66,0.67,0.68,0.69,0.71,0.72,0.73,0.74,0.75,
					0.77,0.78,0.79,0.80,0.81,0.82,0.83,0.84,0.85,0.86,0.87,0.87,0.88,0.89,0.90,0.91,0.91,0.92,0.93,0.93,0.94,0.95,0.95,0.96,0.96,
					0.97,0.97,0.97,0.98,0.98,0.98,0.99,0.99,0.99,0.99,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,1.00,0.99,0.99,0.99,0.99,
					0.98,0.98,0.98,0.97,0.97,0.97,0.96,0.96,0.95,0.95,0.94,0.93,0.93,0.92,0.91,0.91,0.90,0.89,0.88,0.87,0.87,0.86,0.85,0.84,0.83,
					0.82,0.81,0.80,0.79,0.78,0.77,0.75,0.74,0.73,0.72,0.71,0.69,0.68,0.67,0.66,0.64,0.63,0.62,0.60,0.59,0.57,0.56,0.54,0.53,0.52,
					0.50,0.48,0.47,0.45,0.44,0.42,0.41,0.39,0.37,0.36,0.34,0.33,0.31,0.29,0.28,0.26,0.24,0.22,0.21,0.19,0.17,0.16,0.14,0.12,0.10,
					0.09,0.07,0.05,0.03,0.02,0.00,-0.02,-0.03,-0.05,-0.07,-0.09,-0.10,-0.12,-0.14,-0.16,-0.17,-0.19,-0.21,-0.22,-0.24,-0.26,-0.28,
					-0.29,-0.31,-0.33,-0.34,-0.36,-0.37,-0.39,-0.41,-0.42,-0.44,-0.45,-0.47,-0.48,-0.50,-0.52,-0.53,-0.54,-0.56,-0.57,-0.59,-0.60,
					-0.62,-0.63,-0.64,-0.66,-0.67,-0.68,-0.69,-0.71,-0.72,-0.73,-0.74,-0.75,-0.77,-0.78,-0.79,-0.80,-0.81,-0.82,-0.83,-0.84,-0.85,
					-0.86,-0.87,-0.87,-0.88,-0.89,-0.90,-0.91,-0.91,-0.92,-0.93,-0.93,-0.94,-0.95,-0.95,-0.96,-0.96,-0.97,-0.97,-0.97,-0.98,-0.98,
					-0.98,-0.99,-0.99,-0.99,-0.99,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-0.99,-0.99,-0.99,-0.99,-0.98,
					-0.98,-0.98,-0.97,-0.97,-0.97,-0.96,-0.96,-0.95,-0.95,-0.94,-0.93,-0.93,-0.92,-0.91,-0.91,-0.90,-0.89,-0.88,-0.87,-0.87,-0.86,
					-0.85,-0.84,-0.83,-0.82,-0.81,-0.80,-0.79,-0.78,-0.77,-0.75,-0.74,-0.73,-0.72,-0.71,-0.69,-0.68,-0.67,-0.66,-0.64,-0.63,-0.62,
					-0.60,-0.59,-0.57,-0.56,-0.54,-0.53,-0.52,-0.50,-0.48,-0.47,-0.45,-0.44,-0.42,-0.41,-0.39,-0.37,-0.36,-0.34,-0.33,-0.31,-0.29,
					-0.28,-0.26,-0.24,-0.22,-0.21,-0.19,-0.17,-0.16,-0.14,-0.12,-0.10,-0.09,-0.07,-0.05,-0.03,-0.02};
float CosTheta[360]={1.00,1.00,1.00,1.00,1.00,1.00,0.99,0.99,0.99,0.99,0.98,0.98,0.98,0.97,0.97,0.97,0.96,0.96,0.95,0.95,0.94,0.93,0.93,0.92,0.91,
					0.91,0.90,0.89,0.88,0.87,0.87,0.86,0.85,0.84,0.83,0.82,0.81,0.80,0.79,0.78,0.77,0.75,0.74,0.73,0.72,0.71,0.69,0.68,0.67,0.66,
					0.64,0.63,0.62,0.60,0.59,0.57,0.56,0.54,0.53,0.52,0.50,0.48,0.47,0.45,0.44,0.42,0.41,0.39,0.37,0.36,0.34,0.33,0.31,0.29,0.28,
					0.26,0.24,0.22,0.21,0.19,0.17,0.16,0.14,0.12,0.10,0.09,0.07,0.05,0.03,0.02,0.00,-0.02,-0.03,-0.05,-0.07,-0.09,-0.10,-0.12,-0.14,
					-0.16,-0.17,-0.19,-0.21,-0.22,-0.24,-0.26,-0.28,-0.29,-0.31,-0.33,-0.34,-0.36,-0.37,-0.39,-0.41,-0.42,-0.44,-0.45,-0.47,-0.48,
					-0.50,-0.52,-0.53,-0.54,-0.56,-0.57,-0.59,-0.60,-0.62,-0.63,-0.64,-0.66,-0.67,-0.68,-0.69,-0.71,-0.72,-0.73,-0.74,-0.75,-0.77,
					-0.78,-0.79,-0.80,-0.81,-0.82,-0.83,-0.84,-0.85,-0.86,-0.87,-0.87,-0.88,-0.89,-0.90,-0.91,-0.91,-0.92,-0.93,-0.93,-0.94,-0.95,
					-0.95,-0.96,-0.96,-0.97,-0.97,-0.97,-0.98,-0.98,-0.98,-0.99,-0.99,-0.99,-0.99,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,
					-1.00,-1.00,-1.00,-0.99,-0.99,-0.99,-0.99,-0.98,-0.98,-0.98,-0.97,-0.97,-0.97,-0.96,-0.96,-0.95,-0.95,-0.94,-0.93,-0.93,-0.92,
					-0.91,-0.91,-0.90,-0.89,-0.88,-0.87,-0.87,-0.86,-0.85,-0.84,-0.83,-0.82,-0.81,-0.80,-0.79,-0.78,-0.77,-0.75,-0.74,-0.73,-0.72,
					-0.71,-0.69,-0.68,-0.67,-0.66,-0.64,-0.63,-0.62,-0.60,-0.59,-0.57,-0.56,-0.54,-0.53,-0.52,-0.50,-0.48,-0.47,-0.45,-0.44,-0.42,
					-0.41,-0.39,-0.37,-0.36,-0.34,-0.33,-0.31,-0.29,-0.28,-0.26,-0.24,-0.22,-0.21,-0.19,-0.17,-0.16,-0.14,-0.12,-0.10,-0.09,-0.07,
					-0.05,-0.03,-0.02,0.00,0.02,0.03,0.05,0.07,0.09,0.10,0.12,0.14,0.16,0.17,0.19,0.21,0.22,0.24,0.26,0.28,0.29,0.31,0.33,0.34,0.36,
					0.37,0.39,0.41,0.42,0.44,0.45,0.47,0.48,0.50,0.52,0.53,0.54,0.56,0.57,0.59,0.60,0.62,0.63,0.64,0.66,0.67,0.68,0.69,0.71,0.72,0.73,
					0.74,0.75,0.77,0.78,0.79,0.80,0.81,0.82,0.83,0.84,0.85,0.86,0.87,0.87,0.88,0.89,0.90,0.91,0.91,0.92,0.93,0.93,0.94,0.95,0.95,0.96,
					0.96,0.97,0.97,0.97,0.98,0.98,0.98,0.99,0.99,0.99,0.99,1.00,1.00,1.00,1.00,1.00};


/* ========================================================================== */
/*                          Function Definitions                              */
/* ========================================================================== */

/**
 *  \name main
 *  \brief Main Function
 *  \param none
 *  \return none
 *
 */
int main()
{
    /* Call board init functions */
    Board_initCfg boardCfg;
    Task_Params taskParams;
    EMAC_HwAttrs_V4 cfg;

    boardCfg = BOARD_INIT_PINMUX_CONFIG |
    BOARD_INIT_MODULE_CLOCK | BOARD_INIT_UART_STDIO;
    Board_init(boardCfg);


    CSL_xbarMpuIrqConfigure(CSL_XBAR_INST_MPU_IRQ_92, CSL_XBAR_GMAC_SW_IRQ_RX_PULSE);
    CSL_xbarMpuIrqConfigure(CSL_XBAR_INST_MPU_IRQ_93, CSL_XBAR_GMAC_SW_IRQ_TX_PULSE);

    /* Select RGMII 2 ports GMIIx_SEL = 2 for RGMII*/
   CSL_FINS (((CSL_control_coreRegs *) CSL_MPU_CTRL_MODULE_CORE_CORE_REGISTERS_REGS)->CONTROL_IO_1,
          CONTROL_CORE_CONTROL_IO_1_GMII1_SEL, 2U);
    CSL_FINS (((CSL_control_coreRegs *) CSL_MPU_CTRL_MODULE_CORE_CORE_REGISTERS_REGS)->CONTROL_IO_1,
          CONTROL_CORE_CONTROL_IO_1_GMII2_SEL, 2U);

    /*GMAC RESET ISOLATION Enable*/
   CSL_FINS (((CSL_control_coreRegs *) CSL_MPU_CTRL_MODULE_CORE_CORE_REGISTERS_REGS)->CONTROL_IO_2,
          CONTROL_CORE_CONTROL_IO_2_GMAC_RESET_ISOLATION_ENABLE, 0U);
    CSL_FINS (((CSL_control_coreRegs *) CSL_MPU_CTRL_MODULE_CORE_CORE_REGISTERS_REGS)->CONTROL_IO_2,
          CONTROL_CORE_CONTROL_IO_2_GMAC_RESET_ISOLATION_ENABLE, 1U);

    EMAC_socGetInitCfg(0, &cfg);
    cfg.port[0].phy_addr = EMAC_CPSW_PORT0_PHY_ADDR_EVM;
    cfg.port[1].phy_addr = EMAC_CPSW_PORT1_PHY_ADDR_EVM;
    EMAC_socSetInitCfg(0, &cfg);


    NIMUDeviceTable[nimu_device_index++].init =  &CpswEmacInit ;
    NIMUDeviceTable[nimu_device_index].init =  NULL ;

    //UART_stdioDeInit();
    Init_variables();
    TimerInitialization();
    /***********************/
     	 	GPIO_init();
            /* Set the callback function */
            GPIO_setCallback(USER_PB1, AppGpioCallbackFxn);
            GPIO_setCallback(USER_PB2, AppGpioCallbackFxn_1);
            GPIO_setCallback(USER_PB3, AppGpioCallbackFxn_2);

     /******************************/

    /*Task_Params_init(&taskParams);
    taskParams.priority = 1;
    taskParams.stackSize = 0x1400;
    main_task = Task_create (TaskFxn, &taskParams, NULL);*/

    //Tagged by anjana
   /* Task_Params_init(&taskParams);
    taskParams.priority = 5;
    taskParams.stackSize = 0x1400;
    main_task = Task_create (PixelCalc, &taskParams, NULL);*/

    Task_Params_init(&taskParams);
    taskParams.priority = 1;//4;
    taskParams.stackSize = 0x1400;
    main_task = Task_create (SendDataToPC, &taskParams, NULL);

    BIOS_start();

    return -1;
}

void Init_variables(void)
{
   //TCP_TXBuffer=0,
   THIndx_prv=0;
   NextData=0;
   NextSerialData=0;
   NextTheta=0;
   Start_Count=0;
   CountPRT=0;
   CountSecond=0;
   BearingCount=0;
//   Bearingangle=0;

   row=0;
   PrvRow=0;
   NoofdataSend=0;
   clmn =0;
   NoOfPRT=0;
   NoOfSwipe=0;
   BufferFillFlg =0;
   NextPRTFlg=0;
   ThetaFlg=0;
   NextTrgtFlg_start=0;
   target_Flag=0;
   targetEnd_Flag=0;
   RangeEnd_flag=0;
   targetStart_Flag=0;
   target_start=0;
   target_end=0;
   Trigger=0;
   Start_PRT=0;
   FalledgeFlag=0;
   RiseedgeFlag=0;
   AzimuthCnt=0;
   memset(scanPrompt, 0, sizeof(scanPrompt));

}
/*initialization for 1 microsecond timer*/
void TimerInitialization()
{
	Timer_Params timerParams;
	Timer_Handle myTimer;
	Error_Block eb;
	Error_init(&eb);
	Timer_Params_init(&timerParams);
	timerParams.period = 1;
	timerParams.periodType = Timer_PeriodType_MICROSECS;
	timerParams.arg = 1;
	timerParams.startMode = Timer_StartMode_AUTO;
	myTimer = Timer_create(Timer_ANY, myIsr, &timerParams, &eb);
	if (myTimer == NULL) {
	System_abort("Timer create failed");
	}

}
void myIsr(UArg arg)
{

	if(Start_Count)
	{
			CountPRT++;
		/*	BearingCount++;
		if(BearingCount==518)
		{
			Bearingangle=Bearingangle+1;
			if(Bearingangle>=4096)
			{
				Bearingangle=0;
				NoOfPRT=0;
				//THIndx_prv=0;
				NoOfSwipe++;
			}

			BearingCount=0;
		}*/
		//if(CountSecond<2342857)
		{
		CountSecond++;
		}
		/*else
		{CountSecond=0;}*/

	}
	//System_exit(0);
}

void InitialiseUART_3()
{
	int32_t addrScanPrompt;//,byterd;
	//char HeadingMark_1, prv_HeadingMark_1;
	  //UART_Handle       uart = NULL;
	  UART_Params       uartParams;
	   /* UART SoC init configuration */
	  UART_HwAttrs uart_cfg;
	  SemaphoreP_Params semParams;
	  UART_init();
/***************************************UART_In_Callback();***************/
    /* Create call back semaphore */
      UART_osalSemParamsInit(&semParams);
      semParams.mode = SemaphoreP_Mode_BINARY;
      callbackSem = UART_osalCreateBlockingLock(0, &semParams);
	  /* Get the default UART init configurations */
	  UART_socGetInitCfg(UART_INSTANCE, &uart_cfg);
      uart_cfg.edmaHandle = NULL;
      uart_cfg.dmaMode    = FALSE;
      uart_cfg.loopback   = FALSE;

      UART_socSetInitCfg(UART_INSTANCE, &uart_cfg);

	  /* Set callback mode for read */
      UART_Params_init(&uartParams);
      uartParams.baudRate = 76800;
      uartParams.parityType= UART_PAR_EVEN;
	  uartParams.readCallback = UART_callback;
	  uartParams.readMode = UART_MODE_CALLBACK;
	  //uartParams.readDataMode = UART_DATA_BINARY;
	  /*uartParams.writeCallback = NULL;
	    uartParams.writeMode = UART_MODE_CALLBACK;*/

	  uart = UART_open(UART_INSTANCE, &uartParams);
	    if (uart == NULL)
	    {
	      //  goto Err;
	    }
/*************************************************************************/

	    addrScanPrompt= (int32_t)scanPrompt;
		if(UART_read(uart, (void *)addrScanPrompt,INPUT_LENGTH)==UART_ERROR)
				{
			//goto Err;
				}

}
void UART_putNum_Anjana(int32_t value)
{
    char     num[10]  = {0};

    uint32_t quotient = 0;
    uint32_t dividend = 0;
    uint32_t mod_val  = 0;
    int32_t  i,count    = 0;

   /* if (value < 0)
    {
        UART_putc(((uint8_t)('-')));*/
        /*
        ** Making the negative number as positive.
        ** This is done to simplify further processing and printing.
        */
        /*value = -value;
    }*/

    dividend = (uint32_t)value;
    do
    {
        quotient   = dividend / 10U;
        mod_val    = dividend % 10U;
        num[count] = (char) (mod_val);
        if (0U == quotient)
        {
            break;
        }
        count++;
        dividend = quotient;
    } while (count < 10);

    /* Avoid warning for overflow.  Can't actually happen since 10 digits
     * is sufficent to print any 32-bit number */
    if(count == 10)
    {
        count--;
    }

    for(i=0;i<=count;i++)
    {
    	scanPrompt[i]=(uint8_t)num[count-i] + (uint8_t)0x30U;
    }

}

void Read_AzimuthCnt()
{
	int32_t addrScanPrompt_1;
	char HeadingMark_1, prv_HeadingMark_1;

	if(NextSerialData)
	{
		NextSerialData=0;
		HeadingMark=scanPrompt[0];

	memset(scanPrompt, 0, sizeof(scanPrompt));
	addrScanPrompt_1= (int32_t)scanPrompt;
	UART_read(uart, (void *)addrScanPrompt_1,INPUT_LENGTH);
	//UART_osalPendLock(callbackSem, SemaphoreP_WAIT_FOREVER);
	HeadingMark_1=HeadingMark & 0x80;
	prv_HeadingMark_1=prv_HeadingMark & 0x80;
	if(HeadingMark_1 != prv_HeadingMark_1)
	{
		AzimuthCnt=0;
		NoOfPRT=0;
		NoOfSwipe++;

	}
	else if(AzimuthCnt>=4096)
	{

	 AzimuthCnt=0;
	 NoOfPRT=0;


	}
	prv_HeadingMark=HeadingMark;
	}
}
void PixelCalc()
{
	Int16 Pixel_X,Pixel_Y;
	float RangeInNM,Theta;
    if(NoOfPRT<1800)
	 {

    	if(target_Flag)
    	{
    		target_Flag=0;
    	}


	 }
}


void Cmp_Copy_FivePRT()
{
int R,C,count,index=0;
for(C=0;C<NoofdataSend;C++)
{
	for(R=0;R<4;R++)
		{
			if(XY_buffer_1[R][C]== XY_buffer_1[R+1][C])
				{count++;}
			else
			{count--;}
		}
	if(count>2)
	{
		XY_buffer_2[index]=XY_buffer_1[R][C];
	index++;
	}
	count=0;
}
NoofdataSend=index;
}
void CopyfirstPRT()
{
	UInt16 C;
	for(C=0;C<NoofdataSend;C++)
	 {
	 	XY_buffer_2[C]=XY_buffer_1[0][C];
	 }
}

void SendDataToPC()
{
	SOCKET s = INVALID_SOCKET;
	struct sockaddr_in sin1;
	int K,I,respose,NoOfBytes;
	UInt16 *pBuf = 0;
	struct timeval timeout;

	// Allocate the file descriptor environment for this Task
	fdOpenSession( (HANDLE)Task_self() );
	NIMU_log("\n== Start TCP Client Test ==\n");

	// Create test socket
//	s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	s = socket(AF_INET, SOCK_STREAM, 0);
	if( s == INVALID_SOCKET )
	{
		NIMU_log("failed socket create (%d)\n",fdError());
	goto leave;
	}

	// Prepare address for connect
	bzero( &sin1, sizeof(struct sockaddr_in) );
	sin1.sin_family = AF_INET;
	sin1.sin_addr.s_addr =  inet_addr(IPAddr);//inet_addr(SERVER_IP);//htonl(-1);
	sin1.sin_port = htons(5060);//htons(9000);
	// Configure our Tx and Rx timeout to be 5 seconds For TCPIP
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;

	if(setsockopt( s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof( timeout ) ) < 0 )
			{
				NIMU_log("failed Socket opt(%d)\n",fdError());
			goto leave;
			}
	else
	{NIMU_log("Socket opt succesful\n");}

	//setsockopt( s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof( timeout ) );
	// Connect socket
	if( connect( s, (PSA) &sin1, sizeof(sin1) ) < 0 )
	{
		NIMU_log("failed connect (%d)\n",fdError());
	goto leave;
	}

	// Allocate a working buffer
    if( !(pBuf = malloc( test )) )
    	{
    		NIMU_log("failed temp buffer allocation\n");
    	goto leave;
    	}
    //Task_sleep(50);
   	// Fill buffer with a test pattern

    K=0;
    NIMU_log("Start Send\n");
    UART_stdioDeInit();
    InitialiseUART_3();
    Task_sleep(10);
    Start_PRT=1;
    NoOfPRT=0;
   GPIO_enableInt(USER_PB1);
   GPIO_enableInt(USER_PB2);
   GPIO_enableInt(USER_PB3);

    while(NoOfSwipe<10)
    {
    	if(Start_Count==1)
    	{
				if(NoOfPRT<1800)
				{
					Read_AzimuthCnt();
					PixelCalc ();
					if(BufferFillFlg==1)
					{
					BufferFillFlg=0;
					//for(K=0;K<THIndex;K++)
					//{
						for(I=0; I<NoofdataSend; I++)
							{
							*(pBuf+I)	=XY_buffer_2[I];//XY_buffer_1[0][I];
							//XY_OneSwipe_buff[NoOfSwipe][I]=XY_buffer_2[I];
							}
					//}
						NoOfBytes = NoofdataSend*2;
						//row=0;
						/*I=50;
						*(pBuf+I)='\n';*/
						//respose=send( s, pBuf, NoOfBytes, 0 );
						respose=send( s, &XY_buffer_2, NoOfBytes, 0 );

				}
				else
				{
					NoOfPRT=0;
					//NoOfSwipe++;
				}
    	}
    }

    }
    row=0;
   // NIMU_log("Second1:%d\n",CountSecond);
   // NIMU_log("Total PRT= %d\n",K);

	leave:
	if( pBuf )
	free( pBuf );
	if( s != INVALID_SOCKET )
	fdClose( s );
	//NIMU_log("Second2:%d\n",CountSecond);
	//NIMU_log("== End TCP Client Test ==\n\n");

	// Free the file descriptor environment for this Task
	fdCloseSession( (HANDLE)Task_self() );
	Task_exit();
	}

/*
 *  ======== Callback function ========
 */
void AppGpioCallbackFxn(void)
{
	//gpio_intr_triggered = 1;

	if((CountPRT<70)&&(Trigger==1))
	{

			target_Flag=1;
			targetStart_Flag=1;
			target_start=CountPRT;

	}

	else if(Trigger==1)
	{Trigger=0;
	//target_Flag=0;
	//targetEnd_Flag=0;
	RangeEnd_flag=1;
	target_end=CountPRT;}
}
void AppGpioCallbackFxn_1(void)
{

	if(targetStart_Flag==1)
		{
			targetStart_Flag=0;
			targetEnd_Flag=1;
			target_end=CountPRT;
			//target_Flag=0;
		}

}
void AppGpioCallbackFxn_2(void)
{
	if(Start_PRT==1)
	{
		Start_Count=1;
		Start_PRT=0;
	}
	if(Start_Count==1)
	{
	Trigger=1;
	//BufferFillFlg =0;
	NextData=1;
	//targetEnd_Flag=0;
	CountPRT=0;
	NoOfPRT++;
	ThetaFlg=0;
	}
}


void UART_callback(UART_Handle handle, void *buf, size_t count)
{
	AzimuthCnt=AzimuthCnt+count;
	NextSerialData=1;
	//memset(buf,0,INPUT_LENGTH);
	//UART_osalPostLock(callbackSem);
	}
/******************************/

void app_delay(uint32_t delayValue)
{
    volatile uint32_t delay = delayValue*10;
    while (delay--);
}
