/***************************************************************************
 *   copyright           : (C) 2002 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.de                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <stdio.h>

//own headers
#include <charsets.h>
#include <helper.h>
#include <gtincl.h>

#if defined(OS2)
#define  INCL_DOSNLS
#include <os2.h>
#define DOS_API
static char localcp[30];
char* get_system_charset_raw() {
  int rc;
  ULONG aulCpList[8] = {0};               /* Code page list        */
  ULONG ulBufSize    = 8 * sizeof(ULONG); /* Size of output list   */
  ULONG ulListSize   = 0;                 /* Size of list returned */
  
  rc = DosQueryCp(ulBufSize,aulCpList,&ulListSize);
  /* dirty solution, but it work ... */
  snprintf(localcp,sizeof(localcp)-1,"CP%u",(int)aulCpList[0]);
  return localcp;
}

#elif defined(WINDOWS_API)
#include <windows.h>
static char localcp[30];
char* get_system_charset_raw() {
  snprintf(localcp,sizeof(localcp)-1,"CP%u",GetConsoleCP());
  return localcp;
}

#else
#include <config.h>
#ifdef HAVE_LANGINFO_H
#  include <langinfo.h>
#endif
char* get_system_charset_raw() {
#  ifdef NO_NL_LANGINFO
  return "ANSI_X3.4-1968";
#  else //NO_NL_LANGINFO
#    ifdef HAVE_LIBICONV
  /* The default implementation uses nl_langinfo(CODESET)
   * If this gives you problems with your mixture
   * of libc and libiconv, fix it here.
   */
#    endif
  return nl_langinfo(CODESET);
#  endif //NO_NL_LANGINFO
}
#endif

static char* system_charset;

void charset_init (char* charset, int announce) {
  //str_dup returns NULL on NULL input
  system_charset = str_dup(charset);
  if (announce) {
    fprintf(stderr,_("Using \"%s\" as system character set."),get_system_charset());
    fprintf(stderr,"\n");
  }
  gettext_set_codeset(get_system_charset());
}

char* get_system_charset () {
  if (system_charset != NULL) return system_charset;
  else return get_system_charset_raw();
}
