#ifndef NO_LIBNET

#include <allegro.h>
#include <stdlib.h> // free
#include <string.h> // strcmp

#include "net.h"

Network *network = 0;

void Network::error() {
	if(channel) {
		net_closechannel(channel);
		channel = 0;
	}
	if(driver >= 0) {
		net_shutdown();
		driver = -1;
	}
	if(address) {
		free(address);	
		address = 0;
	}
}

Network::Network() {
	int c;

	net_init( );
	net_loadconfig(NULL);

	channel = 0;
	driver = -1;
	address = 0;

	for(c=0; c<NET_CLASS_MAX; c++)
		if(!strcmp(net_classes[c].name, "Internet")) break;

	if(c < NET_CLASS_MAX) {
		NET_DRIVERNAME *drivers;
		int d;
		drivers=net_getdrivernames( net_classes[c].drivers );
		for(d = 0; drivers[d].name; d++)
		if(net_detectdriver( drivers[d].num )) break;
		free(drivers);

		if(drivers[d].name) {
			NET_DRIVERLIST theone;
			NET_DRIVERLIST s;

			driver = drivers[d].num;
			
			theone=net_driverlist_create();
			net_driverlist_add(theone, driver);
			s = net_initdrivers(theone);
			net_driverlist_destroy(theone);

			if(s) {
				channel = 0;
				int port;
				for(port = 7777; channel == 0 && port < 8000; port++) {
					char str[256];
					sprintf(str,":%d", port);
					channel = net_openchannel (driver, str);				
				}
				
				if(channel) {
					char *adr = net_getlocaladdress(channel);
					address = new char[strlen(adr) + 1];
					strcpy(address, adr);
									
				} else {
					error();
				}								
			} else {				
				error();
			}
		} else {			
			error();
		}
	}	else {		
		error();
	}
}

Network::~Network() {
	error();
}

int Network::connect(char *target) {
	int s;
	s = net_assigntarget(channel, target);
   if(s) {   	
   	return -1;
   }
   return 0;
}

#endif