#include "src/all.c"
#include <stdio.h>
/*
Make sure this file is "micro_main.c" and output is "micro_main.dll"
Use the following command to compile this code:
(For WINDOWS)
    gcc -shared -o micro_main.dll micro_main.c
(For LINUX)
    gcc -shared -fPIC -o micro_main.so micro_main.c
*/

/*
|   This is where you write the code for the microcontroller simulation.
|   "all.h" includes many functions, check that file for more detail.
*/

void play_number(int);

EXPORT void* main(void* p) { 

    // Initialize here.
    SSD_Init();
    LED_Init();
    BZR_Init();

    while(1){
        SSD_SetValue(0);
        DelayAprox10Us(100000);

        SSD_SetValue(24); // Display 18
        play_number(1);
        DelayAprox10Us(20000);
        play_number(8);
        DelayAprox10Us(40000);

        SSD_SetValue(20); // Display 14
        play_number(1);
        DelayAprox10Us(20000);
        play_number(4);
        DelayAprox10Us(40000);

        SSD_SetValue(24); // Display 18
        play_number(1);
        DelayAprox10Us(20000);
        play_number(8);
        DelayAprox10Us(40000);
    }
}

/*
With the microcontroller simulator, convert the "SOS" into numbers, for example A=1.
Display these numbers on the SSD, one number at a time. (Note that the SSD displays numbers as Base16)
At the same time, use the buzzer to play the number as a morse code.
Play the morse code with a LED as well.
*/

void play_number(int num){
    if (num < 0 || num > 9) return;

    int delay_1, delay_2, num_a, i;

    if (num>5) {
        delay_2 = 5000*2;
        delay_1 = delay_2*2;
    }
    else{
        delay_1 = 5000*2;
        delay_2 = delay_1*2;
    }

    num_a = 5-num;

    if (num>5){
        num_a *= -1;
        num_a--;
        num -= 5;
    }

    for (i = 0; i < num; i++)
    {
        LED_SetValue(1,1);
        BZR_SetValue(800, 900, 1);
        DelayAprox10Us(delay_1);
        LED_SetValue(1,0);
        BZR_SetValue(800, 900, 0);
        DelayAprox10Us(delay_1);
    }
    for (i = 0; i < num_a; i++)
    {
        LED_SetValue(1,1);
        BZR_SetValue(800, 900, 1);
        DelayAprox10Us(delay_2);
        LED_SetValue(1,0);
        BZR_SetValue(800, 900, 0);
        DelayAprox10Us(delay_2);
    }
}