/*
  Copyright (c) 2004,   Beijing Senselock Data Security Centre
  All rights reserved.
  
  File£ºsample_36_hw.c
  
  Briefs£ºThis code will 
    
*/

#include <string.h>
#include "..\..\inc\hardware\ses_v3.h"
#include "..\inc\sample_36.h"

#define _DEBUG

/* global variable defination. */
unsigned char last_ses_error = 0; /* last SES error */
IO_PACKAGE out_pkg;  /* output package */
IO_PACKAGE *output = &out_pkg; 
IO_PACKAGE *input = (IO_PACKAGE *)pbInBuff; /* input package */

/*
	Exit upon an error.
  
	Parameters:
		errcode[in]: error code
		msg[in]: additional error message
		msglen[in]: message length
  
	Return:
		none.

	Remarks:
		none.
*/
void error_exit(unsigned char errcode, unsigned char *msg, int msglen)
{
	output->tag = errcode;
	output->len = 0;
	
	/* for debug purpose only */
#ifdef  _DEBUG
	if (msglen != 0 && msg != NULL)
	{
		memcpy(output->buff, msg, msglen);
		output->len = msglen;
	}
#endif

	_set_response(2+output->len, (unsigned char *)output);
	_exit();
}

unsigned char foo(float op1, float op2, unsigned short times, float *p_result)
{
	unsigned char ret = 0;
	unsigned char trialFlag = 1;  // 1: trial version; 0: standard version
    RTC_TIME_T exp = {0};
	time_t et = 0;
	time_t t = 0;
	int i = 0;
	HANDLE hFile;
 	float result = 0;
	float tmp = 0;


	ret = _open(EXPIRE_TIME_FID, &hFile);
	if (ret == SES_SUCCESS)
	{
		ret = _read(hFile, 0, 1, &trialFlag);
		if (ret == SES_SUCCESS)
		{

			if (trialFlag) // trial version software
			{
				ret = _read(hFile, 1, sizeof(RTC_TIME_T), (unsigned char *)&exp);
				if (ret == SES_SUCCESS)
				{
					LE16_TO_CC(&exp.year); /* the EXPIRE_TIME_FID file is written by PC */
					ret = _time(&t);
					
					if (ret == SES_SUCCESS)
					{
						ret = _mktime(&et, &exp);
						if (ret == SES_SUCCESS)
						{
							if (t > et)
							{
								_close(hFile);
								return ERR_SW_EXPIRED;
							}
						}
					}
				}
			}
		}
	}
	_close(hFile);
	if (ret != SES_SUCCESS)
	{
		last_ses_error = ret;
		return ERR_SES;
	}		
	for (; i<times; i++)
	{
		tmp = _multf(op1, op2); 		 
		result = _addf(tmp, result);
	}
			
	ret = _mem_copy(p_result, &result, sizeof(float));
	if (ret != SES_SUCCESS)
	{
		last_ses_error = ret;
		return ERR_SES;
	}

}
void main()
{
	unsigned char ret = 0;
	unsigned char length = 0;
	float result = 0;
	DATA_BLOCK *dblk = (DATA_BLOCK *)&input->buff;

	LE16_TO_CC(&dblk->times);	
	LE32_TO_CC(&dblk->op1);
	LE32_TO_CC(&dblk->op2);

	// do functions ...
	ret = foo(dblk->op1, dblk->op2, dblk->times, &result);
	
	if (ret != ERR_SUCCESS)
	{
		if (ret == ERR_SES)
		{
			error_exit(ERR_SES, &last_ses_error, 1);
		}
		error_exit(ret, NULL, 0);
	}
	CC_TO_LE32(&result);

	length = sizeof(float);
	ret = _mem_copy(output->buff, &result, length);
	if (ret != SES_SUCCESS)
	{
		error_exit(ERR_SES, &ret, 1);
	}
	output->tag = ERR_SUCCESS;
	output->len = (unsigned char)length;
	_set_response(IO_PACKAGE_HEADER_SIZE+output->len, (unsigned char *)output);
	_exit();  
}
