'' SDL2-Example program:
'' Test of the SDL character conversation
'' translated by TJF 2013
'/*
  'Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>

  'This software is provided 'as-is', without any express or implied
  'warranty.  In no event will the authors be held liable for any damages
  'arising from the use of this software.

  'Permission is granted to anyone to use this software for any purpose,
  'including commercial applications, and to alter it and redistribute it
  'freely.
'*/

#INCLUDE ONCE "crt/stdio.bi"
#INCLUDE ONCE "SDL2/SDL2.bi"

FUNCTION widelen(BYVAL Dat AS ZSTRING PTR) AS size_t
    DIM AS size_t lngth = 0
    VAR p = CAST(Uint32 PTR, Dat)
    WHILE (*p)
      lngth += 1
      p += 1
    WEND
    RETURN lngth
END FUNCTION

DIM SHARED AS ZSTRING PTR formats(...) = { _
  @"UTF8", _
  @"UTF-8", _
  @"UTF16BE", _
  @"UTF-16BE", _
  @"UTF16LE", _
  @"UTF-16LE", _
  @"UTF32BE", _
  @"UTF-32BE", _
  @"UTF32LE", _
  @"UTF-32LE", _
  @"UCS4", _
  @"UCS-4"}

DIM AS UBYTE buffer(BUFSIZ - 1)
DIM AS ZSTRING PTR test(1)
DIM AS INTEGER errors = 0

'/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO)

IF 0 = __FB_ARGV__[1] THEN __FB_ARGV__[1] = @"utf8.txt"

VAR file = fopen(__FB_ARGV__[1], "rb")
IF 0 = file THEN
  SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, !"Unable to open %s\n", __FB_ARGV__[1])
  END 1
END IF

WHILE fgets(@buffer(0), UBOUND(buffer) + 1, file)
    '/* Convert to UCS-4 */
    'size_t len;
  VAR ucs4 = SDL_iconv_string("UCS-4", "UTF-8", @buffer(0), _
                       SDL_strlen(@buffer(0)) + 1)
  VAR lngth = (widelen(ucs4) + 1) * 4
  FOR i AS INTEGER = 0 TO UBOUND(formats)
    test(0) = SDL_iconv_string(formats(i), "UCS-4", ucs4, lngth)
    test(1) = SDL_iconv_string("UCS-4", formats(i), test(0), lngth)
    IF 0 = test(1) ORELSE SDL_memcmp(test(1), ucs4, lngth) <> 0 THEN
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, !"FAIL: %s\n", formats(i))
      errors += 1
    END IF
    SDL_free(test(0))
    SDL_free(test(1))
  NEXT
  test(0) = SDL_iconv_string("UTF-8", "UCS-4", ucs4, lngth)
  SDL_free(ucs4)
  fputs(test(0), stdout)
  SDL_free(test(0))
WEND
fclose(file)

END (CAST(UBYTE, IIF(errors, errors + 1, 0)))
