'' SDL2-Example program:
'' Test program to test dynamic loading with the loadso subsystem.
'' 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 "SDL2/SDL2.bi"

TYPE fntype AS FUNCTION CDECL (BYVAL AS CONST ZSTRING PTR) AS INTEGER

VAR hello = 0, retval = 0
DIM AS ZSTRING PTR libname = NULL
DIM AS ZSTRING PTR symname = NULL

IF __FB_ARGC__ <> 3 THEN
  VAR app = __FB_ARGV__[0]
  SDL_Log(!"USAGE: %s <library> <functionname>\n", app)
  SDL_Log(!"       %s --hello <lib_ with puts()>\n", app)
  END 1
END IF

'/* Initialize SDL */
IF SDL_Init(0) < 0 THEN
  SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, _
    !"Couldn't initialize SDL: %s\n", SDL_GetError())
  END 2
END IF

IF *__FB_ARGV__[1] = "--hello" THEN
  hello = 1
  libname = __FB_ARGV__[2]
  symname = @"puts"
ELSE
  libname = __FB_ARGV__[1]
  symname = __FB_ARGV__[2]
END IF

VAR lib_ = SDL_LoadObject(libname)
IF lib_ = NULL THEN
  SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, _
    !"SDL_LoadObject('%s') failed: %s\n", libname, SDL_GetError())
  retval = 3
ELSE
  VAR fn = CAST(fntype, SDL_LoadFunction(lib_, symname))
  IF fn = NULL THEN
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, _
      !"SDL_LoadFunction('%s') failed: %s\n", symname, SDL_GetError())
    retval = 4
  ELSE
    SDL_Log(!"Found %s in %s at %p\n", symname, libname, fn)
    IF hello THEN
      SDL_Log(!"Calling function...\n")
      fflush(stdout)
      fn(!"     HELLO, WORLD!\n")
      SDL_Log(!"...apparently, we survived.  :)\n")
      SDL_Log(!"Unloading library...\n")
      fflush(stdout)
    END IF
  END IF
  SDL_UnloadObject(lib_)
END IF
SDL_Quit()
END retval
