/* Copyright 2013 Akira Ohta (akohta001@gmail.com)
    This file is part of ntch.

    The ntch is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    The ntch is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ntch.  If not, see <http://www.gnu.org/licenses/>.
    
*/
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <assert.h>

#include "utils/nt_std_t.h"
#include "utils/text.h"



wchar_t*  nt_decord_html_entity(const wchar_t *src)
{
	wchar_t ch;
	wchar_t *cptr;
	int len, i;

	assert(src);
	len = wcslen(src);
	if(len < 0)
		return NULL;

	cptr = malloc((len+1)*sizeof(wchar_t));
	if(!cptr)
		return NULL;

	wcscpy(cptr, src);

	for(i = 0; i < len; i++){
		ch = cptr[i];
		switch(ch){
		case L'&':
			if(len > (i+5)){
				if(cptr[i+1] == L'q' &&
						cptr[i+2] == L'u' &&
						cptr[i+3] == L'o' &&
						cptr[i+4] == L't' &&
						cptr[i+5] == L';'){
					if(nt_w_str_move(
							cptr+i, len-i, 6, -5)){
						cptr[i] = L'\"';
						len	-= 5;
						break;
					}else{
						goto END_FOR;
					}
					break;
				}
			}
			if(len>(i+4)){
				if(cptr[i+1]==L'a'&&
						cptr[i+2]==L'm'&&
						cptr[i+3]==L'p'&&
						cptr[i+4]==L';'){
					if(nt_w_str_move(
							cptr+i,	len-i,5,-4)){
						cptr[i]	=L'&';
						len	-=4;
						break;
					}else{
						goto END_FOR;
					}
					break;
				}
			}
			if(len>(i+3)){
				if(cptr[i+1]==L'g'&&
						cptr[i+2]==L't'&&
						cptr[i+3]==L';'){
					if(nt_w_str_move(
							cptr+i,len-i,4,-3)){
						cptr[i]	=L'>';
						len	-=3;
						break;
					}else{
						goto END_FOR;
					}
					break;
				}else if(cptr[i+1]==L'l'&&
					cptr[i+2]==L't'&&
					cptr[i+3]==L';'){
					if(nt_w_str_move(
							cptr+i,len-i,4,-3)){
						cptr[i]=L'<';
						len	-=3;
						break;
					}else{
						goto END_FOR;
					}
					break;
				}
			}
		}
	}
END_FOR:
	return cptr;
}


