#include <stdio.h>

/* UTF8の次の文字をoutに格納し、そのバイト数を返す。
 * 不正バイト列のチェックは行わない。
 * (bufの先頭がナル文字でなければ)outにナル文字は格納しない。
 */
int get_next_utf8_char(char *out, const char *buf) {
	int bytes = 1;
	int i;
	if ((buf[0] & 0x80) == 0x00) {
		bytes = 1;
	} else {
		int now_mask = 0xE0;
		int now_puttern = 0xC0;
		for (i = 2; i <= 6; i++) {
			if ((buf[0] & now_mask) == now_puttern) {
				bytes = i;
				break;
			}
			now_mask = (now_mask >> 1) | 0x80;
			now_puttern = (now_puttern >> 1) | 0x80;
		}
	}
	for (i = 0; i < bytes; i++) out[i] = buf[i];
	return bytes;
}

void split_string(const char *input, char *mess1, char *mess2, int length) {
	int i;
	for (i = 0; *input != '\0' && i < length; i++) {
		int length = get_next_utf8_char(mess1, input);
		mess1 += length;
		input += length;
	}
	*mess1 = '\0';

	while (*input != '\0') {
		int length = get_next_utf8_char(mess2, input);
		mess2 += length;
		input += length;
	}
	*mess2 = '\0';
}

int main(void) {
	const int sample_length[] = {0, 5, 7, 11, 12, 30, -1};
	const char* samples[] = {
		"123456789１０１１１２１３１４",
		"Cat「にゃーん!!」",
		"𦥑𦥑𦥑𦥑𦥑Cafè du Lapin𦣪𦣪𦣪𦣪𦣪",
		NULL
	};
	char mess1[100], mess2[100];
	int i, j;

	for (i = 0; sample_length[i] >= 0; i++) {
		printf("length = %d\n", sample_length[i]);
		for (j = 0; samples[j] != NULL; j++) {
			split_string(samples[j], mess1, mess2, sample_length[i]);
			printf("(input, mess1, mess2) = (\"%s\", \"%s\", \"%s\")\n",
				samples[j], mess1, mess2);
		}
	}
	return 0;
}
