#include "binary_c_python.h"
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>



/*
 * apitest
 *
 * Short test programme to throw random binary systems at binary_c's
 * library via its API.
 *
 * Note that it looks more complicated than it is because I have included
 * code to capture binary_c's stdout stream and output it here.
 *
 * This code sends output to stderr : you should use apitest.sh to run it
 * and hence force output to your terminal's stdout.
 *
 * Output lines:
 *
 * APITEST ....  is information about what this code is doing.
 * STATUS  ....  is information about the binary system.
 * BINARY_C .... is output from binary_c (see iterate_logging.c etc.)
 *               which would have gone to stdout
 *
 * If you define the NO_OUTPUT macro, there will be no output except
 * the memory allocation and test system information. This is useful for speed tests,
 * but note that you may end up in a race condition where the pipe which replaces
 * stdout's buffer fills and hence the code stops.
 *
 * Note:
 * I have tested this with gcc 4.7.2 (Ubuntu 12.10) only.
 */

// #define _CAPTURE
#ifdef _CAPTURE
static void show_stdout(void);
static void capture_stdout(void);
#endif

/* global variables */
int out_pipe[2];
int stdoutwas;

/*
Below are the real calls to the API of binary_c. Currently these are the functions:

// evolution
run_binary
run_binary_custom_logging
run_binary_with_logfile
run_population


// utility
return_arglines
return_help_info
return_help_all_info
return_version_info

// other
create_store

*/


/* =================================================================== */
/* Functions to evolve systems                                         */
/* =================================================================== */


int run_binary(char * argstring,
               char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &argstring,
                        -1);
    
    /* disable logging */
    snprintf(stardata->preferences->log_filename,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");
    snprintf(stardata->preferences->api_log_filename_prefix,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");
    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* do binary evolution */
    binary_c_evolve_for_dt(stardata,
                           stardata->model.max_evolution_time);

    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
    binary_c_free_store_contents(store);
        
    return 0;
}

int run_binary_custom_logging(char * argstring,
               long int custom_logging_func_memaddr,
               char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &argstring,
                        -1);
    
    /* disable logging */
    snprintf(stardata->preferences->log_filename,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");
    snprintf(stardata->preferences->api_log_filename_prefix,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");
    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;
    stardata->preferences->custom_output_function = (void*)(struct stardata_t *)custom_logging_func_memaddr;

    /* do binary evolution */
    binary_c_evolve_for_dt(stardata,
                           stardata->model.max_evolution_time);
        
    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
    binary_c_free_store_contents(store);
        
    return 0;
}

int run_binary_with_logfile(char * argstring,
               char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &argstring,
                        -1);

    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* do binary evolution */
    binary_c_evolve_for_dt(stardata,
                           stardata->model.max_evolution_time);
        
    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
    binary_c_free_store_contents(store);
    return 0;
}

int run_population(char * argstring,
               long int custom_logging_func_memaddr,
               long int store_memaddr,
               char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;

    // load the store from the integer that has been passed
    struct libbinary_c_store_t * store = (void*)store_memaddr;

    /* make new stardata */
    stardata = NULL;
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &argstring,
                        -1);
    
    /* disable logging */
    snprintf(stardata->preferences->log_filename,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");
    snprintf(stardata->preferences->api_log_filename_prefix,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");

    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* Check the value of the custom_logging_memaddr */
    if(custom_logging_func_memaddr != -1)
    {
        stardata->preferences->custom_output_function = (void*)(struct stardata_t *)custom_logging_func_memaddr;
    }

    /* do binary evolution */
    binary_c_evolve_for_dt(stardata,
                           stardata->model.max_evolution_time);
        
    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
        
    // TODO: Ask rob whether to free the memory here or not? or to free it manually.
    return 0;
}


// This one will replace the different ones above. needs to handle multiple input choices and decide what to do.
int run_system(char * argstring,
               long int custom_logging_func_memaddr,
               long int store_memaddr,
               char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;

    // Store:
    /* Check the value of the store_memaddr */
    struct libbinary_c_store_t * store;
    if(store_memaddr != -1)
    {
        // load the store from the integer that has been passed
        // struct libbinary_c_store_t * store = (void*)store_memaddr;
        store = (void*)store_memaddr;
    }
    else
    {
        // struct libbinary_c_store_t * store = NULL;
        store = NULL;
    }

    /* make new stardata */
    stardata = NULL;
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &argstring,
                        -1);
    
    /* disable logging */
    snprintf(stardata->preferences->log_filename,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");
    snprintf(stardata->preferences->api_log_filename_prefix,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");

    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* Check the value of the custom_logging_memaddr */
    if(custom_logging_func_memaddr != -1)
    {
        stardata->preferences->custom_output_function = (void*)(struct stardata_t *)custom_logging_func_memaddr;
    }

    /* do binary evolution */
    binary_c_evolve_for_dt(stardata,
                           stardata->model.max_evolution_time);
        
    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE); // CHeck if this is good for single runs.. TODO: 
        
    // TODO: Ask rob whether to free the memory here or not? or to free it manually.
    return 0;
}


/* =================================================================== */
/* Functions to call other API functionality like help and arglines    */
/* =================================================================== */

int return_arglines(char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    char * empty_str = "";
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &empty_str,
                        -1);

    /* disable logging */
    snprintf(stardata->preferences->log_filename,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");
    snprintf(stardata->preferences->api_log_filename_prefix,
             STRING_LENGTH-1,
             "%s",
             "/dev/null");

    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* List available arguments */
    binary_c_list_args(stardata);

    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
    binary_c_free_store_contents(store);

    return 0;
}


int return_help_info(char * argstring,
               char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &argstring,
                        -1);

    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* Ask the help api */
    binary_c_help(stardata, argstring);
        
    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
    binary_c_free_store_contents(store);
    return 0;
}

int return_help_all_info(char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    char * empty_str = "";
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &empty_str,
                        -1);

    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* Ask the help api */
    binary_c_help_all(stardata);
        
    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
    binary_c_free_store_contents(store);
    return 0;
}

int return_version_info(char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    char * empty_str = "";
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &empty_str,
                        -1);

    /* output to strings */
    stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* Ask the help api */
    binary_c_version(stardata);
        
    /* get buffer pointer */
    binary_c_buffer_info(stardata,buffer,nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata,error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata,TRUE,TRUE,FALSE,FALSE);
    binary_c_free_store_contents(store);
    return 0;
}

/* =================================================================== */
/* Functions to call other functionality                               */
/* =================================================================== */


long int return_store(char * argstring,
               char ** const buffer,
               char ** const error_buffer,
               size_t * const nbytes)
{
    /* memory for N binary systems */
    struct libbinary_c_stardata_t *stardata;
    struct libbinary_c_store_t * store = NULL;

    /* make new stardata */
    stardata = NULL;
    binary_c_new_system(&stardata,
                        NULL,
                        NULL,
                        &store,
                        &argstring,
                        -1);

    /* output to strings */
    // stardata->preferences->internal_buffering = INTERNAL_BUFFERING_STORE;
    // stardata->preferences->batchmode = BATCHMODE_LIBRARY;

    /* get buffer pointer */
    binary_c_buffer_info(stardata, buffer, nbytes);
    
    /* get error buffer pointer */
    binary_c_error_buffer(stardata, error_buffer);
    
    /* set raw_buffer_size = -1 to prevent it being freed */
    stardata->tmpstore->raw_buffer_size = -1;
    
    /* free stardata (except the buffer) */
    binary_c_free_memory(&stardata, TRUE, TRUE, FALSE, FALSE);

    /* convert the pointer */ 
    uintptr_t store_memaddr_int = (uintptr_t)store; // C Version converting ptr to int

    /* Return the memaddr as an int */
    return store_memaddr_int;
}