/***   [others.c]
*
*	その他いろいろ ﾖ		(C)ささがわ
*
*	For GNU C Compiler (GCC)   Version 1.39
*
***/

#include <string.h>
#include <stdio.h>
#include <jctype.h>
#include <ctype.h>
#include <bios.h>
#include <snd.h>
#include <mos.h>
#include "graph.h"

extern int	PAL_Black;
static int	_TIMER_end;

/* fpathで示されるﾌﾙﾊﾟｽを文字数がnx以下になるようにし, bufへ格納 */
/* 戻り値は, bufへ格納した先頭のｵﾌｾｯﾄ                            */
int Cont_path(const char *fpath, int nx, char *buf) {
	int		len, ret;
	
	if ((len = strlen(fpath)) > nx) {
		int		n = 0;
		
		while (n <= nx - 5)			/* nx - <ﾋﾟﾘｵﾄﾞの数> - 2 */
			while (fpath[len - ++n] != '\\');
		if (n > nx - 5)
			while (fpath[len - --n] != '\\');
		ret = len - n;
	} else {
		ret = 0;
	}
	
	if (ret > 0) {
		strncpy(buf, fpath, 2);
		strcpy(buf + 2, "...");
		strcpy(buf + 5, fpath + ret);
	} else {
		strcpy(buf, fpath);
	}
	
	return ret;
}

/* strで示される文字列を小文字に modeが1のとき先頭だけ大文字に (日本語対応) */
void strlow(int mode, unsigned char *str) {
	int		i = 0;
	
	if (mode && str[i]) {
		if (iskanji(*((unsigned char *)str + i)))
			i++;
		else
			str[i] = toupper(str[i]);
		i++;
	}
	while (str[i]) {
		if (iskanji(*((unsigned char *)str + i)))
			i++;
		else
			str[i] = tolower(str[i]);
		i++;
	}
}

/* 数値valにコンマを付けて, 文字列としてbufへ格納 */
void Konma(unsigned val, char *buf) {
	int		i, flag;
	
	if (i = val / 1000000) {
		sprintf(buf, "%3u,", i);
		flag = 1;
	} else {
		sprintf(buf, "    ");
		flag = 0;
	}
	if ((i = (val % 1000000) / 1000) != 0 || flag != 0) {
		if (flag)
			sprintf(buf + 4, "%03u,", i);
		else
			sprintf(buf + 4, "%3u,", i);
		
		flag = 1;
	} else {
		sprintf(buf + 4, "    ");
	}
	if (flag)
		sprintf(buf + 8, "%03u", val % 1000);
	else
		sprintf(buf + 8, "%3u", val % 1000);
}

/* y:西暦(-1980) m:月 d:日 として曜日を返す万年ｶﾚﾝﾀﾞｰ (うるう年にも対応ﾖ) */
const unsigned char *Getyoubi(int y, int m, int d) {
	int		days;
	static const short	Month[] = {
		0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
	};
	static const unsigned char	Youbi[][3] = {
		"木", "金", "土", "日", "月", "火", "水"
	};
	
	days = (y + 11) / 4 * 1461 + ((y + 11) % 4) * 365 - 365;	/* 11 = 1980 - 1969 */
	days += Month[m - 1] + d - 1;
	if (!((1980 + y) % 4) && m >= 3)
		days++;
	
	return Youbi[days % 7];
}

void TIMER_set(int a) {
	extern void	_TIMER_reset(int);
	extern void	_TIMER_sub(void);
	
	_TIMER_end = 0;
	_TIMER_reset(a);
	SND_int_timer_a_set((void *)_TIMER_sub);
	SND_fm_timer_a_set(1, 500);		/* 10ms */
}

int TIMER(void) {
	int		r = 0;
	extern int	_TIMER_flag;
	
	if (_TIMER_end)	return 1;
	
	if (_TIMER_flag) {
		SND_fm_timer_a_set(0, 0);
		SND_int_timer_a_set(NULL);
		_TIMER_end = 1;
		r = 1;
	}
	
	return r;
}

int strLE(const char *str, int l) {
	int		i = 0;
	
	while (i < l && str[i]) {
		if (iskanji(((const unsigned char *)str)[i])) {
			if (i + 1 < l)
				i++;
			else
				break;
		}
		i++;
	}
	
	return i;
}
