/*
 * Copyright (C) 2000-2003 ASANO Masahiro
 */

#include "time.h"
#include "unistd.h"
#include "crash.h"

PRIVATE addr_t date_cmd();
const commandtable_t command_date =
	{"date", date_cmd, "[hextime]", "convert time by strftime(3)"};

PRIVATE addr_t
date_cmd()
{
	int c;
	time_t ti;
	char buf[64];
	const char *fmt = "%c";

	while ((c = getopt(argcnt, args, "f:")) != EOF) {
		switch (c) {
		case 'f':
			fmt = optarg;
			break;
		default:
			THROW(usage);
		}
	}

	if (optind == argcnt) {
		ti = time(NULL);
		strftime(buf, sizeof(buf), fmt, localtime(&ti));
		mprintf("%08lx:  %s\n", ti, buf);
	} else {
		while (args[optind]) {
			ti = (time_t)getvalue(args[optind]);
			strftime(buf, sizeof(buf), fmt, localtime(&ti));
			mprintf("%08lx:  %s\n", ti, buf);
			optind++;
		}
	}
	return 0;
}

PRIVATE addr_t cmdjiffies();
const commandtable_t command_jiffies =
	{"jiffies", cmdjiffies, "[jiffies]", "print jiffies by human readable format"};
extern void mprint_HZ();

extern addr_t jiffies_addr;

PRIVATE addr_t
cmdjiffies()
{
	int c;
	long jiffies, jif;

	while ((c = getopt(argcnt, args, "")) != EOF) {
		switch (c) {
		default:
			THROW(usage);
		}
	}

	GETADDR(jiffies);
	memread(jiffies_addr, sizeof(jiffies), &jiffies, "jiffies");

	mprintf(SPTR "      DAY HH:MM:SS.mmm\n",
		"JIFFIES");
	mprintf(FPTR "     ", jiffies);
	mprint_jif(jiffies);
	mprintf("       (HZ=");
	mprint_HZ();
	mprintf(")\n");
	while (args[optind]) {
		jif = getvalue(args[optind]);
		mprintf(FPTR "     ", jif);
		mprint_jif(jif);
		mprintf("     ");
		if (jif >= jiffies) {
			mprintf("+");
			mprint_jif(jif - jiffies);
		} else {
			mprintf("-");
			mprint_jif(jiffies - jif);
		}
		mprintf("\n");
		optind++;
	}

	return 0;
}
