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

#include "tclient_tcp.h"

int main ( int argc, char **argv )
{
    int status, written, osize, opos, ipos, flags, bytes_read, bytes_written;
    tc_socket cnx;
    char err_msg[256];
    char obuf[256], ibuf[1024];

    if ( argc < 3 ) {
	fprintf(stderr, "Usage: test host port\n" );
	return 1;
    }
    status = tc_open_tcp_socket ( argv[1], atoi(argv[2]), 0, (char **) 0,
	&cnx, err_msg );
    printf ( "status of open: %d '%s'\n", status, (status&1) ? "" : err_msg );
    if ( (status&1) == 0 ) exit ( status );
    if ( argc == 3 ) {
        status = tc_write ( cnx, "GET / HTTP/1.0\n\n", 16, &written );
        printf ( "status of write: %d, written: %d\n", status, written );

        while ( status&1 ) {
           	status = tc_read ( cnx, err_msg, 255, &written );
	    if ( status&1 == 0 ) break;
	    err_msg[written] = '\0';
	    printf ( "%s", err_msg );
        }
        exit ( status );
    }

    printf("Starting full duplex\n");
    sprintf ( obuf, "GET %s HTTP/1.0\nAccept: */*\n\n", argv[3] );
    printf("Request:\n%s", obuf );
    printf("----\n");
    osize = strlen ( obuf );
    status = tc_start_io ( cnx, 0, obuf, osize );
    status = tc_start_io ( cnx, 1, ibuf, sizeof(ibuf)-1 );

    while ( tc_io_stall ( cnx, &flags, &bytes_read, &bytes_written ) ) {
	printf("stall completion, Flags: %d, read: %d, written: %d\n",
		flags, bytes_read, bytes_written );
	if ( flags&4 ) break;	/* error */
	if ( flags&1 ) {
	     opos = opos + bytes_written;
	     if ( opos < osize ) tc_start_io (cnx, 0, &obuf[opos], osize-opos);
	}
	if ( flags&2 ) {
	    ibuf[bytes_read] = '\0';
	    printf ( "%s\n", ibuf );
	    status = tc_start_io ( cnx, 1, ibuf, sizeof(ibuf)-1 );
	    if ( (status&1) == 0 ) exit ( status );
	}
    }
    exit(status);
}
