#include "stdio.h"
#include "mwmr_channel.h"
#include "mapping_info.h"
#include "hard_config.h"

#if NB_TTY_CHANNELS == 1
#  define printf(...) giet_shr_printf(__VA_ARGS__)
#else
#  define printf(...) giet_tty_printf(__VA_ARGS__)
#endif

#define NMAX 50

/////////////////////////////////////////////
__attribute__ ((constructor)) void producer()
{

    unsigned int 	n;
    unsigned int 	buf;
    mwmr_channel_t*	mwmr;

    // get processor identifiers
    unsigned int    x;
    unsigned int    y;
    unsigned int    lpid;
    giet_proc_xyp( &x, &y, &lpid );

    printf( "*** Starting task producer on processor[%d,%d,%d] at cycle %d\n\n", 
             x, y, lpid, giet_proctime() );

    giet_vobj_get_vbase( "router" , 
                         "mwmr_in", 
                         (void*)&mwmr );

    // main loop : display token value = source index
    for(n = 0 ; n < NMAX ; n++) 
    { 
        buf = n;
        mwmr_write( mwmr, &buf , 1 );
        printf( "transmitted value : %d\n", buf);
    }

    giet_exit( "Producer task completed");

} // end producer()

/////////////////////////////////////////////
__attribute__ ((constructor)) void consumer()
{
    unsigned int 	n;
    unsigned int 	buf;
    mwmr_channel_t*	mwmr;

    // get processor identifiers
    unsigned int    x;
    unsigned int    y;
    unsigned int    lpid;
    giet_proc_xyp( &x, &y, &lpid );

    printf( "*** Starting task consumer on processor[%d,%d,%d] at cycle %d\n\n", 
             x, y, lpid, giet_proctime() );

    giet_vobj_get_vbase( "router" , 
                         "mwmr_out", 
                         (void*)&mwmr );

    // main loop : display token arrival index and value
    for(n = 0 ; n < NMAX ; n++ ) 
    { 
        mwmr_read( mwmr, &buf , 1 );
        printf( "received token %d / value = %d\n", n  , buf);
    }

    giet_exit( "Consumer task completed");

} // end consumer()

///////////////////////////////////////////
__attribute__ ((constructor)) void router()
{
    unsigned int 	buf;
    unsigned int 	n;
    unsigned int	tempo;
    mwmr_channel_t*	mwmr_in ;
    mwmr_channel_t* mwmr_out ;

    // get processor identifiers
    unsigned int    x;
    unsigned int    y;
    unsigned int    lpid;
    giet_proc_xyp( &x, &y, &lpid );

    printf( "*** Starting task router on processor[%d,%d,%d] at cycle %d\n\n", 
             x, y, lpid, giet_proctime() );

    giet_vobj_get_vbase( "router" , 
                         "mwmr_out", 
                         (void*)&mwmr_out );

    giet_vobj_get_vbase( "router" , 
                         "mwmr_in", 
                         (void*)&mwmr_in );
    // main loop
    while(1)
    {
        mwmr_read( mwmr_in , &buf , 1 );
        tempo = giet_rand() >> 6;
        for ( n = 0 ; n < tempo ; n++ ) asm volatile ("");
        printf( "token value : %d / temporisation = %d\n", buf, tempo);
        mwmr_write( mwmr_out, &buf , 1 );
    }
}
