/*
 * To build on Debian-based systems:
 *
 * $ gcc icu-test.c -licui18n -licuuc -o icu-coll-versions
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include "unicode/ustring.h"
#include "unicode/ucol.h"

#define DISPLAY_LOCALE	"en_US"
#define ICU_DISPLAY_LEN	512

char *austrdup(const UChar* unichars);
void listLocales(void);

char *
austrdup(const UChar* unichars)
{
	int			length;
	char	   *newString;

	length = u_strlen (unichars);
	newString = (char*) malloc(sizeof(char) * 4 * (length + 1));
	if (!newString)
		return NULL;

	u_austrcpy(newString, unichars);

	return newString;
}

void
listLocales(void)
{
	int32_t		available;
	UErrorCode	status = U_ZERO_ERROR;
	int			i;

	/* Print header */
	printf("Collator                                          | ICU Version | UCA Version\n");
	printf("-----------------------------------------------------------------------------\n");

	available = uloc_countAvailable();
	for (i = 0; i < available; i++)
	{
		UCollator *collator = NULL;
		UVersionInfo versionIcu;
		UVersionInfo versionUca;
		UChar		 displayName[512];
		const char *locale;
		int32_t		displayLength;

		/* Get locale*/
		locale = uloc_getAvailable(i);
		/* Open collator from that locale */
		collator = ucol_open(locale, &status);
		if (status > U_ZERO_ERROR)

	   if (U_FAILURE(status))
		{
			printf("error with locale %s for ucol_open: code %d\n", locale, (int) status);
			ucol_close(collator);
			status = U_ZERO_ERROR;
			continue;
		}
		/* Get ICU version info for same collator */
		ucol_getVersion(collator, versionIcu);
		/* "Version [argument] is the UCA version number (3.1.1, 4.0)" */
		ucol_getUCAVersion(collator, versionUca);
		displayLength = ucol_getDisplayName(locale, DISPLAY_LOCALE,
											displayName, ICU_DISPLAY_LEN,
											&status);
		if (displayLength > ICU_DISPLAY_LEN)
		{
			printf("error with locale %s for ucol_getDisplayName: could not fit %d\n", locale, (int) displayLength);
			ucol_close(collator);
			status = U_ZERO_ERROR;
			continue;
		}

	   if (U_FAILURE(status))
		{
			printf("error with locale %s for ucol_getDisplayName: code %d\n", locale, (int) status);
			ucol_close(collator);
			status = U_ZERO_ERROR;
			continue;
		}
		/* Print locale's collator details */
		printf("%-50s| %02X-%02X-%02X-%02X | %02X-%02X-%02X-%02X\n",
			   austrdup(displayName),
			   (unsigned int) versionIcu[0],
			   (unsigned int) versionIcu[1],
			   (unsigned int) versionIcu[2],
			   (unsigned int) versionIcu[3],
			   (unsigned int) versionUca[0],
			   (unsigned int) versionUca[1],
			   (unsigned int) versionUca[2],
			   (unsigned int) versionUca[3]);

		ucol_close(collator);
	}
}

int main(int argc, char **argv)
{
	UErrorCode	status;

	listLocales();

	return 0;
}
