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

//#define _DEBUG

const char data[] = "adssdfl;jk$OTAQ1#adssdfl;jk$OTAQ1#123,command,command"
"*FFFF1234\r\nadssdfl;jk$OTAQ1#adssdfl;jk$OTAQ1#123,command,command*FFFF1234";    // Simulated serial string.
const char initial_token = '$'; // Start token on the datastring for our formated string. The format is "$....*FFFF".
const int max_size = 64;        // Maximum niber of bytes which can be part of a message.
char buffer[256];               // Temporary buffer to keep track of date from the serial port.
//char mesage[256];               // Message if any is found with the structure as described above.
bool initial_flag = false;      // Flag to indicate if an initial token has been found.
int counter = 0;                // counter to keep trak of the position in the buffer.

// Parses the messge into its components
void Parse(char* message)
{
    char limits[] = "$#,*";     // Use '$', '#', ',' and '*' are the parsing. 
    char* token = strtok(message, limits);
    while (token != NULL)
    {
        printf("%s\r\n", token);
        token = strtok(NULL, limits);
    }
}

// Identify the message from the strings of char's
void ReadMessage(char c)
{
    // if initialization flag is true then add teh character to teh buffer
        if (initial_flag)
        {
            buffer[counter] = c;    // Add the current character to the buffer.
            counter++;              // increase counter.
            char sum[5] = {0};
            char message[256] = {0};
#ifdef _DEBUG
            printf("%s\r\n", buffer);
#endif
            if(sscanf(buffer, "$%[^*]*%4s", message, sum) == 2){
                int _size  = strlen(sum);
#ifdef _DEBUG 
                printf("number of chars in sum %d\r\n", _size);
#endif
                if (_size == 4) // We have dound some data with the desired format.
                {    
                    // Do something with the string
                    printf("Check sum is: %s\r\n", buffer);
                    printf("Message is: %s\r\n", message);
                    Parse(buffer);
                    initial_flag = false;
                }
            }
        }
        // Check if enconter initial chracter. If this is found at any time reinitialize buffer. and set flag accordingly.
        if (c == initial_token)
        {
            printf("Initial token encounter\r\n");
            initial_flag = true;        // Set initialisation flag to true.s
            memset(buffer, 0, 255);     // Setbuffer data to 0.
            buffer[0] = initial_token;  // Put initial toekn in the buffer.
            counter = 1;                // initialize counter to 1 as 0 zero position has already been initialized.
        }
        if (counter >= max_size)        // If number of character in buffer is maximum the de-initialize the flag.
            initial_flag = false;
}

// Main
int main()
{
    int length = strlen(data);              // Get the dta length on the "serial" buffer. Is just for simulation.
    printf("Reading %d from data string\r\n", length);  // Print the length of data for awareness.
    for (size_t i = 0; i < length; i++) {   // Simulated readint one one caracter at the time from the serial port.
        char c = data[i];                   // Get the char form the buffer.
        ReadMessage(c);                     // Add the char to the message buffer and check it it can be parsed.
    }

}