#include "s600.h"

u32 s600_iap_100ms;

const u8 s600_value_char_map[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

u16 s600_get_avg_value(const u16 *values, u16 size)
{
	u32 sum = values[0];
	u16 i;

	for (i = 1; i < size; i++) {
		sum += values[i];
	}

	return sum / size;
}

u32 s600_checksum_put(u32 checksum, const u8 *data, u16 size)
{
	const u8 *data_end;

	for (data_end = data + size - 1; data < data_end; data += 2) {
		checksum += *(u16 *) data;
	}

	if (data == data_end) {
		checksum += *data;
	}

	return checksum;
}

u32 s600_checksum_put_value(u32 checksum, u16 value)
{
	return checksum + value;
}

u16 s600_checksum_finish(u32 checksum)
{
	while (checksum & 0xFFFF0000) {
		checksum = (checksum >> 16) + (checksum & 0xFFFF);
	}

	return ~checksum;
}

u8 s600_char2value(char ch)
{
	if (ch >= '0' && ch <= '9') {
		return ch - '0';
	}

	if (ch >= 'a' && ch <= 'z') {
		return ch - 'a' + 10;
	}

	if (ch >= 'A' && ch <= 'Z') {
		return ch - 'A' + 10;
	}

	return 0xFF;
}

// "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
u8 s600_month2value(const char *text)
{
	switch (text[0]) {
	case 'J':
		if (text[1] == 'a') {
			return 1;
		} else if (text[2] == 'n') {
			return 6;
		} else {
			return 7;
		}

	case 'F':
		return 2;

	case 'M':
		if (text[2] == 'r') {
			return 3;
		} else {
			return 5;
		}

	case 'A':
		if (text[1] == 'p') {
			return 4;
		} else {
			return 8;
		}

	case 'S':
		return 9;

	case 'O':
		return 10;

	case 'N':
		return 11;

	case 'D':
		return 12;

	default:
		return 0;
	}
}

u16 s600_decode_u16(const u8 *buff)
{
	return DECODE_U16(buff);
}

u32 s600_decode_u24(const u8 *buff)
{
	return DECODE_U24(buff);
}

u32 s600_decode_u32(const u8 *buff)
{
	return DECODE_U32(buff);
}

void s600_encode_u16(u8 *buff, u16 value)
{
	buff[0] = value;
	buff[1] = value >> 8;
}

void s600_encode_u24(u8 *buff, u32 value)
{
	s600_encode_u16(buff, value);
	buff[2] = value >> 16;
}

void s600_encode_u32(u8 *buff, u32 value)
{
	s600_encode_u24(buff, value);
	buff[3] = value >> 24;
}
