/* getrusage emulation for MiNT */

#include <osbind.h>
#include <mintbind.h>
#include <time.h>
#include <resource.h>
#include <errno.h>

extern int __mint;
extern long _childtime;

void
_ms2tval(milliseconds, tval)
	unsigned long milliseconds;
	struct timeval *tval;
{
	tval->tv_sec = milliseconds/1000;
	tval->tv_usec = (milliseconds % 1000) * 1000;
}

void
_add_tval(orig, new)
	struct timeval *orig, *new;
{
	long t;

	t = orig->tv_usec + new->tv_usec;
	if (t > 1000000) {
		orig->tv_sec += t/1000000;
		t = t % 1000000;
	}
	orig->tv_usec = t;
	orig->tv_sec += new->tv_sec;
}

int
getrusage(which, data)
	int which;
	struct rusage *data;
{
	long r;
	long usage[8];

	if (__mint) {
		r = Prusage(usage);
		if (r < 0) {
			errno = -r;
			return -1;
		}
	} else {
		usage[0] = usage[2] = 0;
		usage[1] = clock() - _childtime;
		usage[3] = _childtime;
	}

	if (which == RUSAGE_SELF) {
		_ms2tval(usage[0], &(data->ru_stime));
		_ms2tval(usage[1], &(data->ru_utime));
	}
	else if (which == RUSAGE_CHILDREN) {
		_ms2tval(usage[2], &(data->ru_stime));
		_ms2tval(usage[3], &(data->ru_utime));
	}
	return 0;
}
