#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "ff.h"
#include "id3.h"
#include "play.h"

#define SIZE_MAX 256
static struct s_id3tag {
	char tt2[SIZE_MAX];
	char tp1[SIZE_MAX];
	char tal[SIZE_MAX];
} id3tag;

char* id3tag_tt2(void)
{
	return &id3tag.tt2[0];
}

char* id3tag_tp1(void)
{
	return &id3tag.tp1[0];
}

char* id3tag_tal(void)
{
	return &id3tag.tal[0];
}

static void unicode_to_sjis(char* src, char* sjis, unsigned int size)
{
	int l;

	for(l = 0; l < size; l+=2)
	{
		WCHAR wc_sjis = ff_convert((WCHAR)((src[l + 1] << 8) | (src[l] & 0x00ff)), 0);
		if(wc_sjis > 0x0080)
		{
			*sjis++ = (char)(wc_sjis >> 8);
		}
		*sjis++ = (char)(wc_sjis & 0x00ff);
	}
	*sjis = '\0';
	return;
}

static char* get_v2_info(char* p, char* id3tag)
{
	unsigned int size = 
		(*(p + 0) << 16) +
		(*(p + 1) <<  8) +
		(*(p + 2) <<  0);

	if((*(p + 3+1+0)<<8) + *(p + 3+1+1) == 0xfffe)
	{
		unicode_to_sjis(p + 3+1+2, id3tag, size - 1-2);
	}
	else
	{
		strncpy(id3tag, (p + 3+1+0), size > SIZE_MAX ? SIZE_MAX-1 : (size_t)(size - 1));
	}
	id3tag[size - 1] = '\0';
	return (p + 3 + size);
}

void id3_v2(unsigned char *mp3_work, unsigned int id3_size)
{
	char *p, *r;

	strcpy(id3tag.tt2, "no data");
	strcpy(id3tag.tp1, "no data");
	strcpy(id3tag.tal, "no data");

	p = (char*)mp3_work + 10;
	while(p < (char*)mp3_work + 10 + id3_size)
	{
		if(r = strstr(p, "TT2"))
		{
			p = get_v2_info(r + 3, id3tag.tt2);
			continue;
		}
		if(r = strstr(p, "TP1"))
		{
			p = get_v2_info(r + 3, id3tag.tp1);
			continue;
		}
		if(r = strstr(p, "TAL"))
		{
			p = get_v2_info(r + 3, id3tag.tal);
			continue;
		}
		p++;
	}
	return;
}

static char* get_v2_3_info(char* p, char* id3tag)
{
	unsigned int size = 
		(*(p + 0) << 24) +
		(*(p + 1) << 16) +
		(*(p + 2) <<  8) +
		(*(p + 3) <<  0);

	if((*(p + 4+2+1+0)<<8) + *(p + 4+2+1+1) == 0xfffe)
	{
		unicode_to_sjis(p + 4+2+1+2, id3tag, size - 1-2);
	}
	else
	{
		strncpy(id3tag, (p + 4+2+1+0), size > SIZE_MAX ? SIZE_MAX-1 : (size_t)(size - 1));
	}
	id3tag[size - 1] = '\0';
	return (p + 4 + size);
}

void id3_v2_3(unsigned char *mp3_work, unsigned int id3_size)
{
	char *p, *r;

	strcpy(id3tag.tt2, "no data");
	strcpy(id3tag.tp1, "no data");
	strcpy(id3tag.tal, "no data");

	p = (char*)mp3_work + 10;
	while(p < (char*)mp3_work + 10 + id3_size)
	{
		if(r = strstr(p, "TIT2"))
		{
			p = get_v2_3_info(r + 4, id3tag.tt2);
			continue;
		}
		if(r = strstr(p, "TPE1"))
		{
			p = get_v2_3_info(r + 4, id3tag.tp1);
			continue;
		}
		if(r = strstr(p, "TALB"))
		{
			p = get_v2_3_info(r + 4, id3tag.tal);
			continue;
		}
		p++;
	}
	return;
}

void id3_v1(unsigned char *mp3_work)
{
	strncpy(id3tag.tt2, (char*)&mp3_work[3], 30);
	id3tag.tt2[30] = '\0';

	strncpy(id3tag.tp1, (char*)&mp3_work[3+30], 30);
	id3tag.tp1[30] = '\0';

	strncpy(id3tag.tal, (char*)&mp3_work[3+30+30], 30);
	id3tag.tal[30] = '\0';
	return;
}

void id3_none(void)
{
	strcpy(id3tag.tt2, "no data");
	strcpy(id3tag.tp1, "no data");
	strcpy(id3tag.tal, "no data");

	return;
}
