#include "wrg526api.h"
#include <dlfcn.h>
#include <stdio.h>
#include <errno.h>

G5_FIND_RADIOS G5_FindRadios=NULL;
G5_OPEN_RADIOS G5_OpenRadios=NULL;
G5_CLOSE_RADIOS G5_CloseRadios=NULL;
G5_SET_POWER G5_SetPower=NULL;
G5_SET_FREQUENCY G5_SetFrequency=NULL;
G5_SET_RF_ATTN G5_SetRFAttn=NULL;
G5_SET_IF_GAIN G5_SetIFGain=NULL;
G5_SET_PHASE G5_SetPhase=NULL;
G5_SET_PLL_SPEED G5_SetPllSpeed=NULL;
G5_GET_HW_STATUS G5_GetHwStatus=NULL;
G5_UPDATE_HW G5_UpdateHw=NULL;

void *WRG526API=NULL;

#define GET_PROC(t,f)               \
    f=(t)dlsym(WRG526API,"" #f);    \
    if(f==NULL)                     \
    {                               \
                                    \
        fprintf(stderr,"Unable to load valid wrg526api.so library.\n"); \
        fprintf(stderr,"Unable to find " #f " procedure.\n");\
        dlclose(WRG526API);         \
        WRG526API=NULL;             \
        return 0;                   \
    }


uint8_t LoadG526API(void)
{
    if(WRG526API==NULL)
    {
        WRG526API=dlopen("wrg526api.so",RTLD_LAZY);

        if(WRG526API==NULL)
        {
            fprintf(stderr,"Unable to load wrg526api.so shared library  (%s).\n",dlerror());
            return 0;
        }
        else
        {
            GET_PROC(G5_FIND_RADIOS,G5_FindRadios)
            GET_PROC(G5_OPEN_RADIOS,G5_OpenRadios)
            GET_PROC(G5_CLOSE_RADIOS,G5_CloseRadios)
            GET_PROC(G5_SET_POWER,G5_SetPower)
            GET_PROC(G5_SET_FREQUENCY,G5_SetFrequency)
            GET_PROC(G5_SET_RF_ATTN,G5_SetRFAttn)
            GET_PROC(G5_SET_IF_GAIN,G5_SetIFGain)
            GET_PROC(G5_SET_PHASE,G5_SetPhase)
            GET_PROC(G5_SET_PLL_SPEED,G5_SetPllSpeed)
            GET_PROC(G5_GET_HW_STATUS,G5_GetHwStatus)
            GET_PROC(G5_UPDATE_HW,G5_UpdateHw)

            return 1;
        }
    }
    else
    {
        return 1;
    }
}

void UnloadG526API(void)
{
    if(WRG526API!=NULL)
    {
        dlclose(WRG526API);
        WRG526API=NULL;
    }
}

