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

#include <dos/dos.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>

#include <clib/AMarquee_protos.h>

#include <pragmas/AMarquee_pragmas.h>
/* #define ASYNC_CONNECT */

struct Library * AMarqueeBase = NULL;
struct QSession * session     = NULL;

void CleanExit(void)
{
	printf("\nCleaning up...\n");
	if (session)      QFreeSession(session);        /* This MUST be done before we close the library! */
	if (AMarqueeBase) CloseLibrary(AMarqueeBase);  
	printf("All done.\n");
}

/* Main program */
int main(int argc, char ** argv)
{
	char * connectTo;
	int port;
	char *connectStr="";
	BOOL terminate=FALSE;
	 
	printf("Usage Note:  GetURL [url=localhost] [port=80]\n");  
	printf("e.g. GetURL \"ACS.hostile.cx\" port=80\n");

	atexit(CleanExit);
  
	connectTo = (argc>1) ? argv[1] : "localhost";
	port      = (argc>2) ? atoi(argv[2]) : 80;

	if ((AMarqueeBase = OpenLibrary("amarquee.library",49L)) == NULL)
	{
		printf("Couldn't open amarquee.library v49!\n");
		exit(RETURN_ERROR);
	}
	printf("Connecting to %s:%i\n",connectTo, port);

	#ifdef ASYNC_CONNECT
	if ((session = QNewSocketSessionAsync(connectTo, port,NULL)) == NULL)
	{
		printf("Couldn't connect to server %s:%i\n",connectTo, port);
		exit(RETURN_WARN);
	}
	#else
	if ((session = QNewSocketSession(connectTo, port,NULL)) == NULL)
	{
		printf("Couldn't connect to server %s:%i\n",connectTo, port);
		exit(RETURN_WARN);
	}
	#endif

	printf("Connected to server %s:%i\n",connectTo, port);
	printf("Retrieving index.html from %s ...\n", connectTo);

	connectStr="GET / HTTP/1.0\n\n";
	QSendRawOp(session,connectStr,strlen(connectStr));
	QGo(session,0L); /* Send it! */

	/* Wait for messages */
	while(!terminate)
	{
		struct QMessage * qMsg;
		ULONG signals = (1L << session->qMsgPort->mp_SigBit) | (SIGBREAKF_CTRL_C);

		/* Wait for next message from the server */
		signals = Wait(signals);
	 
		if (signals & (1L << session->qMsgPort->mp_SigBit))
		{
			while(qMsg = (struct QMessage *) GetMsg(session->qMsgPort))
			{
				if (qMsg->qm_Status!=QERROR_NO_ERROR) {
					// Got an error!
					if (qMsg->qm_Status==QERROR_NO_CONNECTION) {
						terminate=TRUE;
						printf("Connection to remote host was closed.\n");
					}
				}
     			else if (qMsg->qm_ID==0 && qMsg->qm_DataLen>0) { // Data sent to us
					// Print it out
					printf("**** START PACKET ****\n%s\n**** END PACKET ****\n",qMsg->qm_Data);
				}

				FreeQMessage(session, qMsg);
			}
		}
		if (signals & SIGBREAKF_CTRL_C) break;  /* Quit if CTRL-C pressed */
	}
	/* CleanExit() called here! */
}
