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

#define MAX_LEN 100

int main() {
    Node *head = NULL;
    // Double buffer to support up to 100 chars in find and replace command
    char buffer[MAX_LEN * 2];

    bool stopLoop = false;
    while (!stopLoop) {
        char *result = fgets(buffer, MAX_LEN * 2, stdin);
        if (result == NULL) {
            // If we get null, there has been an error reading from stdin
            fprintf(stderr, "Error reading from stdin\n");
            return EXIT_FAILURE;
        }
        buffer[strcspn(buffer, "\r\n")] = 0;
        if (buffer[0] == 'a') {
            buffer[MAX_LEN - 1] = '\0'; // Prevent buffer overflow
            add(&head, buffer + 2);
        } else if (buffer[0] == 'd') {
            buffer[MAX_LEN - 1] = '\0'; // Prevent buffer overflow
            delete(&head, buffer + 2);
        } else if (buffer[0] == 'f') {
            char *data = buffer + 2;
            char input1[MAX_LEN], input2[MAX_LEN];
            // sscanf assigns a null terminator to the end of the string, so don't need to do it manually
            sscanf(data, "%99s %99s", input1, input2);
            // Could check if the replacement was successful by using return value of function, but I don't have to
            findAndReplace(head, input1, input2);
        } else if (buffer[0] == 'p') {
            printList(head);
        } else if (buffer[0] == 's') {
            stopLoop = stop(&head);
        }
    }
    return EXIT_SUCCESS;
}