#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/subs/comsub.c,v 2.0 1995/01/25 19:58:54 empire Exp $";
#endif

/*
 * comsub.c
 *
 * commodity read/write stuff.
 *
 * Dave Pare, 1986
 */

#include "misc.h"
#include "player.h"
#include "var.h"
#include "nat.h"

#include <sys/uio.h>

int	commf;

int	c_comm[MAXNOC][I_MAX+1];
float	c_price[MAXNOC][I_MAX+1];
float	c_mult[MAXNOC][MAXNOC];

static	struct iovec commvec[3] = {
	(caddr_t)c_comm,	sizeof(c_comm),
	(caddr_t)c_price,	sizeof(c_price),
	(caddr_t)c_mult,	sizeof(c_mult),
};
static	int nvec = sizeof(commvec)/sizeof(struct iovec);

/*
 * comm file is the list of "deity commodities"
 * lying around.  Perhaps a better way of doing this
 * might be at each update seeing what is on sale,
 * then buying it, then distributing things amongst the
 * people wanting the items.
 *
 * Of course that would be a gigantic pain...
 */

int
commread()
{
	int	n;

	(void) lseek(commf, (off_t) 0, 0);
	if ((n = readv(commf, commvec, nvec)) !=
	    sizeof(c_comm) + sizeof(c_price) + sizeof(c_mult)) {
		logerror("commread: readv returns %d", n);
		return -1;
	}
	return 0;
}

int
commwrite()
{
	(void) lseek(commf, (off_t) 0, 0);
	if (writev(commf, commvec, nvec) != 
	    sizeof(c_comm) + sizeof(c_price) + sizeof(c_mult)) {
		logerror("commwrite: writev failed");
		return -1;
	}
	return 0;
}

int
commlock() 
{
	return file_lock(commf);
}

int
communlock()
{
	return file_unlock(commf);
}

/*
 * returns amount of commodity, and price to the user
 */
int
commamt(trader, product, priceval)
	natid	trader;
	int	product;
	float	*priceval;
{
	*priceval = c_price[trader][product] * c_mult[trader][player->cnum];
	return c_comm[trader][product];
}

commset(trader, product, amt)
	natid	trader;
	int	product;
	int	amt;
{
	c_comm[trader][product] += amt;
}

double
multread(trader, tradee)
	natid	trader;
	natid	tradee;
{
	return c_mult[trader][tradee];
}

multset(tradee, newmult)
	natid	tradee;
	float	newmult;
{
	c_mult[player->cnum][tradee] = newmult;
}

commprice(product, newprice)
	int	product;
	float	*newprice;
{
	c_price[player->cnum][product] = *newprice;
}
