#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cpl_string.h>

int main(int argc, char **argv)
{
    char *pszStr, *pszOut;
    size_t nLen;
    FILE *fp;
    time_t tstart, tend;
    int i, n;

    if (argc < 3)
    {
        fprintf(stderr,
                "USAGE: %s <file_to_convert> <number_of_iterations>\n",
                argv[0]);
        exit(1);
    }

    fp = fopen(argv[1], "rb");
    fseek(fp, 0, SEEK_END);
    nLen = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    pszStr = (char *)CPLCalloc(nLen + 1, sizeof(char));
    fread(pszStr, nLen, sizeof(char), fp);
    pszStr[nLen] = '\0';
    
    n = atoi(argv[2]);

    /* UTF-8 -> ISO-8859-1 */
    tstart = time(NULL);
    for (i = 0; i < n; i++ )
    {
        pszOut = CPLRecodeIconv(pszStr, "UTF-8", "ISO-8859-1");
        VSIFree( pszOut );
    }
    tend = time(NULL);
    printf("%d iterations of CPLRecodeIconv() from UTF-8 to ISO-8859-1 took %d seconds.\n",
           n, (int)(tend - tstart));
    tstart = time(NULL);
    for (i = 0; i < n; i++ )
    {
        pszOut = CPLRecodeStub(pszStr, "UTF-8", "ISO-8859-1");
        VSIFree( pszOut );
    }
    tend = time(NULL);
    printf("%d iterations of CPLRecodeStub() from UTF-8 to ISO-8859-1 took %d seconds.\n",
           n, (int)(tend - tstart));

    /* ISO-8859-1 -> UTF-8 */
    tstart = time(NULL);
    for (i = 0; i < n; i++ )
    {
        pszOut = CPLRecodeIconv(pszStr, "ISO-8859-1", "UTF-8");
        VSIFree( pszOut );
    }
    tend = time(NULL);
    printf("%d iterations of CPLRecodeIconv() from ISO-8859-1 to UTF-8 took %d seconds.\n",
           n, (int)(tend - tstart));
    tstart = time(NULL);
    for (i = 0; i < n; i++ )
    {
        pszOut = CPLRecodeStub(pszStr, "ISO-8859-1", "UTF-8");
        VSIFree( pszOut );
    }
    tend = time(NULL);
    printf("%d iterations of CPLRecodeStub() from ISO-8859-1 to UTF-8 took %d seconds.\n",
           n, (int)(tend - tstart));

    VSIFree( pszStr );
    fclose(fp);

    return 0;
}
