date *
jdate(int ndays, date *dt)
{
	date    idt;
	int     r;

	idt.y = ndays / 365;
	idt.m = 0;
	idt.d = 0;
	while ((r = ndaysji(&idt)) > ndays)
		idt.y--;

	r = ndays - r;
	for (idt.m = 11; month1[idt.m] > r; idt.m--);

	idt.d = r - month1[idt.m];

	printf("DEBUG: idt.y=%d idt.m=%d idt.d=%d\n", idt.y, idt.m, idt.d);

	if (idt.m < 0 || idt.m > 11 || idt.d < 0) {
		printf("ERROR: Invalid internal date!\n");
		return NULL;
	}

	return (idt2date(dt, &idt));
}

date *
gdate(int ndays, date *dt)
{
	int const *montht;
	date    idt;
	int     r;

	idt.y = ndays / 365;
	idt.m = 0;
	idt.d = 0;
	while ((r = ndaysgi(&idt)) > ndays)
		idt.y--;

	ndays = ndays - r;
	montht = (idt.y == 1582) ? month1s : month1;

	for (idt.m = 11; montht[idt.m] > ndays; idt.m--);

	idt.d = ndays - montht[idt.m];

	if (idt.y == jiswitch.y && idt.m == jiswitch.m && jiswitch.d < idt.d)
		idt.d += 10;

	printf("DEBUG: idt.y=%d idt.m=%d idt.d=%d\n", idt.y, idt.m, idt.d);

	if (idt.m < 0 || idt.m > 11 || idt.d < 0) {
		printf("ERROR: Invalid internal date!\n");
		return NULL;
	}

	return (idt2date(dt, &idt));
}

static date *
date2idt(date *idt, date *dt)
{
	idt->d = dt->d - 1;
	if (dt->m > 2) {
		idt->m = dt->m - 3;
		idt->y = dt->y;
	} else {
		idt->m = dt->m + 9;
		idt->y = dt->y - 1;
	}

	if (idt->m < 0 || idt->m > 11 || idt->y < 0) {
		printf("ERROR: Invalid date2idt conversion! dt.y=%d dt.m=%d dt.d=%d\n", dt->y, dt->m, dt->d);
		return NULL;
	}

	return idt;
}

static date *
idt2date(date *dt, date *idt)
{
	dt->d = idt->d + 1;
	if (idt->m < 10) {
		dt->m = idt->m + 3;
		dt->y = idt->y;
	} else {
		dt->m = idt->m - 9;
		dt->y = idt->y + 1;
	}

	if (dt->m > 12) {
		printf("ERROR: Month exceeds 12! Adjusting.\n");
		dt->m = 12;
	}

	printf("DEBUG: Converted date: dt.y=%d dt.m=%d dt.d=%d\n", dt->y, dt->m, dt->d);

	if (dt->m < 1)
		return NULL;
	else
		return dt;
}
