#include "pcdefs.h"
#include "protocol.h"
#include "route.h"
#include "config.h"
#include "funcdef.h"

struct route_st route[NROUTE];	/* our routing table */
extern u_long nmask;

u_long
find_route(ipn)
u_long	ipn;
{
	int	i;

	if ((ipn & nmask) == (Scon.myip & nmask)) {
		if ((ipn & Scon.snetmask) == (Scon.myip & Scon.snetmask))
			return(ipn);
		ipn &= Scon.snetmask;
	} else {
		switch ((u_char)ipn >> 6) {
		    case 0:
		    case 1:
			ipn &= 0x000000ffL;
			break;
		    case 2:
			ipn &= 0x0000ffffL;
			break;
		    case 3:
			ipn &= 0x00ffffffL;
			break;
		}
	}
	for (i = 1; i < NROUTE; i++)
		if (route[i].to == ipn)
			break;

	if (i == NROUTE)
		i = 0;

	return(route[i].real);
}

void
setgate(net, gate)
u_long	net;
u_long	gate;
{
	int	i;

	if (net) {
		switch ((u_char)net >> 6) {
		    case 0:
		    case 1:
			net &= 0x000000ffL;
			break;
		    case 2:
			net &= 0x0000ffffL;
			break;
		    case 3:
			net &= 0x00ffffffL;
			break;
		}
		for (i = 1; i < NROUTE ; i++) {
			if (route[i].to == net) {
				route[i].real = gate;
				break;
			}
			if (!route[i].to) {
				route[i].to = net;
				route[i].real = gate;
				break;
			}
		}
	} else {
		route[0].to = 0;
		route[0].real = gate;
	}
}
