#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include "lib.h"
#include "sharedlib.h"

#define BITS 8

volatile uint8_t *buffer = NULL;
volatile size_t buffer_len = 0;
volatile size_t current_index = 0;
volatile uint8_t byte_to_send = 0;

void signal_handler(int signo) 
{
    if (signo == SIGALRM) 
    {
        if (current_index < buffer_len) 
        {
            byte_to_send = buffer[current_index++];
        } else 
        {
            current_index = 0;
        }
    }
}

int main(int argc, char *argv[]) 
{
    if (argc < 3) 
    {
        fprintf(stderr, "Usage: %s <string> <sample_interval>\n", argv[0]);
        return 1;
    }

    buffer = (uint8_t *) argv[1];
    buffer_len = strlen(argv[1]);
    int sample_interval = atoi(argv[2]);

    // set up an alarm signal that triggers every timeframe
    signal(SIGALRM, signal_handler);
    ualarm(sample_interval, sample_interval);

    // during the timeframe, continuously send the signal
    while (1) 
    {
        for (int i = 0; i < BITS; i++) 
        {
            if (byte_to_send & (1 << i)) 
            {
                maccess((void *) myStupidNOPFunction + (i<<9));
            }
            else
            {
                flush((void *) myStupidNOPFunction + (i<<9)); 
            }
        }
    }

    return 0;
}