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

#include "observation.h"

typedef struct B_UserItem 
    BFX_EXTRUSION_DECL(B_UserItem)
{
    BFX_INTRUSION(B_UserItem)
    int userdata[64];
}
B_UserItem;

BFX_EXTRUSION_FOLLOWUP(B_UserItem)

#if defined(NDEBUG) || (defined(__cforall) && !defined(__CFA_DEBUG__))
    enum { DefaultNumNodes = 1000, DefaultExperimentDurSec = 1, DefaultCheckDonePeriod = 1000, DefaultExperimentDurOpCount = -1, DefaultSeed = 5 };
    #define TRACE(tp)
#else 
    enum { DefaultNumNodes = 10, DefaultExperimentDurSec = 1, DefaultCheckDonePeriod = 2, DefaultExperimentDurOpCount = 20, DefaultSeed = 5 };
    static const char * tp_filter
    // = "";
    // = "+ea";
        = "*";
    #define TRACE(tp) \
        if (strcmp("*", tp_filter) == 0 || strchr(tp_filter, tp)) { \
            printf("%c", tp); \
            bobs_report(); \
        }
#endif

static B_UserItem *ui = NULL;

static BFX_LISTED_ELEM_T(B_UserItem) *listedItems = NULL;
static BFX_LISTED_ELEM_T(B_UserItem) observedItem;

static BFX_LIST_HEAD_T(B_UserItem) lst;


MAYBE_EXTERN_C (

    volatile size_t       bobs_ops_completed      = 0;
    volatile unsigned int bobs_prog_inserting     = 0;
    volatile unsigned int bobs_prog_removing      = 0;
    volatile unsigned int bobs_prog_rollover_flag = 0;

    void bobs_seek(unsigned int i) {
        observedItem = listedItems[i];
    }

    void bobs_moveNext() {
        observedItem = BFX_GET_AFTER(B_UserItem, lst, observedItem);
    }

    void bobs_movePrev() {
        observedItem = BFX_GET_BEFORE(B_UserItem, lst, observedItem);
    }

    int bobs_hasCurrent() {
        return BFX_IS_VALID_POS(B_UserItem, lst, observedItem);
    }

    void * bobs_getCurrentLoc() {
        return BFX_DEREF_POS(B_UserItem, lst, observedItem);
    }
    int bobs_getCurrentVal() {
        B_UserItem * curUI = BFX_DEREF_POS(B_UserItem, lst, observedItem);
        return curUI->userdata[17];
    }

    enum bobs_op_movement_t bobs_op_movement = OP_MOVEMENT;
    enum bobs_op_polarity_t bobs_op_polarity = OP_POLARITY;
)

unsigned int uDefaultPreemption() {
        return 0;
}

int main(int argc, const char *argv[]) {

    const char * usage_args = "[ExperimentDurSec [CheckDonePeriod [NumNodes [ExperimentDurOpCount [Seed]]]]]";
    const int static_arg_posns = 5;

    unsigned int ExperimentDurSec     = DefaultExperimentDurSec;
    unsigned int CheckDonePeriod      = DefaultCheckDonePeriod;
    unsigned int NumNodes             = DefaultNumNodes;
    size_t       ExperimentDurOpCount = DefaultExperimentDurOpCount;
    unsigned int Seed                 = DefaultSeed;

    switch (((argc - 1) < static_arg_posns) ? (argc - 1) : static_arg_posns) {
      case 5: Seed = atoi(argv[5]);
      case 4: ExperimentDurOpCount = atol(argv[4]);
      case 3: NumNodes = atoi(argv[3]);
      case 2: CheckDonePeriod = atoi(argv[2]);
      case 1: ExperimentDurSec = atoi(argv[1]);
    }

    if (ExperimentDurSec == 0 || CheckDonePeriod == 0 || NumNodes == 0 || ExperimentDurOpCount == 0 || Seed == 0 ) {
        printf("usage: %s %s\n", argv[0], usage_args);
        return -1;
    }

  #ifdef DISABLE_CLOCK_RECHECK
    if (ExperimentDurSec != -1) {
        printf("Error: experiment compiled as fixed-work only.  ExperimentDurSec (currently %d) must be set to -1.\nUsage: %s %s\n", ExperimentDurSec, argv[0], usage_args);
        return -1;
    }
  #endif

  #ifdef DISABLE_SHUFFLING_INDIRECTION
    #define INSERTPOS(insertNum) insertNum
  #else
    // To ensure random memory order of nodes being inserted, do so according to a shuffled ordering of them.
    unsigned int * insertOrdShuf = (unsigned int *) malloc( (size_t)NumNodes * sizeof(unsigned int) );
    if (!insertOrdShuf) {
        printf("malloc request for %zd bytes for insertOrdShuf refused\n", (size_t)NumNodes * (size_t)sizeof(unsigned int));
        return 1;
    }
    // Fill with the ordinals (iota)
    for (int i = 0; i < NumNodes; i++) {
        insertOrdShuf[i] = i;
    }
    // Dummy "Seed" of -1 means skip the shuffle: measure overhead of insertOrdShuf indirection
    if (Seed != -1) {
        // Shuffle
        srand(Seed);
        for (unsigned int i = 0; i < NumNodes; i++) {
            unsigned int nodesRemaining = NumNodes - i;
            unsigned int swapWith = i + rand() % nodesRemaining;
            unsigned int tempValue = insertOrdShuf[swapWith];
            insertOrdShuf[swapWith] = insertOrdShuf[i];
            insertOrdShuf[i] = tempValue;
        }
    }
    #define INSERTPOS(insertNum) insertOrdShuf[insertNum]
  #endif

    ui = (B_UserItem*) malloc( (size_t)NumNodes * (size_t)sizeof(B_UserItem) );
    if (!ui) {
        printf("malloc request for %zd bytes for ui refused\n", (size_t)NumNodes * (size_t)sizeof(B_UserItem));
        return 1;
    }
    memset(ui, 0, (size_t)NumNodes * (size_t)sizeof(B_UserItem));

    listedItems = (BFX_LISTED_ELEM_T(B_UserItem)*)malloc( (size_t)NumNodes * (size_t)sizeof(BFX_LISTED_ELEM_T(B_UserItem)) );
    if (!listedItems) {
        printf("malloc request for %zd bytes for listedItems refused\n", (size_t)NumNodes * (size_t)sizeof(BFX_LISTED_ELEM_T(B_UserItem)));
        return 1;
    }
    memset(listedItems, 0, (size_t)NumNodes * (size_t)sizeof(BFX_LISTED_ELEM_T(B_UserItem)));

    // Fill with demo data
    for (unsigned int i = 0; i < NumNodes; i++) {
        B_UserItem * curUI = & ui[INSERTPOS(i)];
        curUI->userdata[17] = i;
    }

    BFX_INIT(B_UserItem, lst);

    bobs_init(NumNodes);

    // BOP_ADDFOO(lst, iters, insNo, item)
    // BOP_REMFOO(lst, iters, remNo)
    //   lst    lvalue of the list head being added to / removed from
    //   iters  array of ADD return values, in logical-insert order; on ADD, is valid at [0..insNo)
    //   insNo  counter of the ADD calls (logical insert number)
    //   remNo  counter of the REM calls (logical remove number)
    //   item   lvalue of the item being added
    // Logical insert number 0 and remove number n-1 are given with a distinguished hook.
    // Logical insert numbers [1,n) and remove numbers [0,n-1) are pumped by the basic SUT hooks.
    // This pattern lets BOP cartridges that measure element-level operations know statically when there is a reference element in the list.
    // The driver owns the relationship between a logical insert number and the location of the `item` argument within `ui`.  (Scattered for randomness.)
    // The BOP cartridge owns the relationship between logical remove number and any choice of an item in iters.  (Defines stack vs queue.)

    // Default init/teardown is insert/remove
    // Cartridges whose SUT insert/remove actions work on empty lists need not provide special-case ones.
    #ifndef BOP_INIT
    #define BOP_INIT(lst, iters, insNo, item) BOP_INSERT(lst, iters, insNo, item)
    #endif
    #ifndef BOP_TEARDOWN
    #define BOP_TEARDOWN(lst, iters, remNo) BOP_REMOVE(lst, iters, remNo)
    #endif

    double elapsed_sec = 0;
    clock_t start = clock();

    size_t privateOpsCompleted = 0;

    while (elapsed_sec <= (double) ExperimentDurSec && privateOpsCompleted < ExperimentDurOpCount) {
        for ( int t = 0; t < CheckDonePeriod; t += 1 ) {
            TRACE('a')
            listedItems[0] =
                BOP_INIT(lst, listedItems, 0, ui[INSERTPOS(0)]);
            TRACE('b')
            for ( int privateCurInsert = 1;
                  (bobs_prog_inserting = privateCurInsert, privateCurInsert < NumNodes);
                  privateCurInsert += 1
                ) {
                TRACE('-')
                listedItems[privateCurInsert] =
                    BOP_INSERT( lst, listedItems, privateCurInsert, ui[INSERTPOS(privateCurInsert)] );
                TRACE('+')
            }
            TRACE('c')
            for ( int privateCurRemove = 1;
                  (bobs_prog_removing = privateCurRemove, privateCurRemove < NumNodes);
                  privateCurRemove += 1
                ) {
                TRACE('-')
                BOP_REMOVE( lst, listedItems, privateCurRemove-1 );
                TRACE('+')
            }
            TRACE('D')
            BOP_TEARDOWN(lst, listedItems, NumNodes-1);
            TRACE('d')

            privateOpsCompleted += NumNodes;

            bobs_prog_rollover_flag = 1;
            TRACE('e')
            bobs_prog_inserting = 0;
            bobs_prog_removing = 0;            
            bobs_ops_completed = privateOpsCompleted;
            TRACE('f')
            bobs_prog_rollover_flag = 0;
            TRACE('g')
        }
      #ifndef DISABLE_CLOCK_RECHECK
        clock_t end = clock();
        elapsed_sec = ((double)(end - start)) / ((double)CLOCKS_PER_SEC);
      #endif
    }
    #ifdef DISABLE_CLOCK_RECHECK
    {
        clock_t end = clock();
        elapsed_sec = ((double)(end - start)) / ((double)CLOCKS_PER_SEC);
    }
    #endif

    double mean_op_dur_ns = elapsed_sec / ((double)bobs_ops_completed) * 1000 * 1000 * 1000;
    printf("%s,%zd,%f,%f\n", argv[0], bobs_ops_completed, elapsed_sec, mean_op_dur_ns);

    free(ui);
    free(listedItems);
    free(insertOrdShuf);
}
