#include <libnet/url.h>
#include <libnet/httpstream.h>
#include <util/string.h>

#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace net;
using namespace os;

String Lookup( const String& cWord )
{
	String	cQueryString = String( "http://www.m-w.com:80/cgi-bin/dictionary?book=Dictionary&va=" ) + cWord ;
	Url cUrl(cQueryString);
	HTTPstream cStream(cUrl);
	String	cResult;

	const char* pzBeginMark = "<!-- begin content -->";
	const char* pzEndMark = "<!-- end content -->";
	int nMatchIndex = 0;
	bool bStart = false;
	bool bEnd = false;

	char zBuffer[1025];
	ssize_t nBytes = 0;

	while( ( nBytes = cStream.Read( zBuffer, 1024 )) > 0 )
	{
		for( int i = 0; i < nBytes; i++ ) {
			if( bStart && !bEnd ) {
				cResult += zBuffer[i];
			}
			if( !bStart ) {
				if( zBuffer[i] == pzBeginMark[nMatchIndex] ) {
					nMatchIndex++;
					if( !pzBeginMark[nMatchIndex] ) {
						bStart = true;
					}
				} else {
					nMatchIndex = 0;
				}
			} else if( !bEnd ) {
				if( zBuffer[i] == pzEndMark[nMatchIndex] ) {
					nMatchIndex++;
					if( !pzEndMark[nMatchIndex] ) {
						bEnd = true;
					}
				} else {
					nMatchIndex = 0;
				}
			}
		}
	}

	return cResult;
}

String FilterTags( const String& cHTML )
{
	int i;
	const char *p;
	String cResult;
	String cTag;
	bool bTag = false;

	p = cHTML.c_str();
	for( i = 0; i < cHTML.size(); i++, p++ ) {
		if( *p=='<' ) {
			bTag = true;
		}
		if( !bTag ) {
			if( *p != '\n' && *p != '\r' ) {
				cResult += *p;
			}
		} else {
			cTag += *p;
		}
		if( *p=='>' ) {
			bTag = false;
			if( strncmp( cTag.c_str(), "<br", 3 ) == 0 ) {
				cResult += '\n';
			}
			cTag = "";
		}
	}
	return cResult;
}

int main( int argc, char *argv[] )
{
	if( argc != 2 ) {
		std::cout << "Usage: " << argv[0] << " <word>" << std::endl;
		return 0;
	}

	std::cout << FilterTags(Lookup( argv[1] )).c_str() << std::endl;

	return EXIT_SUCCESS;
}

