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

#define MAX_LENGTH 50

void textToASCII(char text[]) {
    printf("รหัส ASCII: ");
    for (int i = 0; i < strlen(text); i++) {
        printf("%d", text[i]);
        if (i < strlen(text) - 1) {
            printf(","); // ใส่จุลภาคระหว่างรหัส ASCII
        }
    }
    printf("\n");
}

void asciiToText(char asciiInput[]) {
    char *token = strtok(asciiInput, ",");
    printf("ข้อความที่ได้: ");
    while (token != NULL) {
        int asciiCode = atoi(token); // แปลงรหัส ASCII จากข้อความเป็นจำนวนเต็ม
        printf("%c", asciiCode);
        token = strtok(NULL, ",");
    }
    printf("\n");
}

int main() {
    int choice;
    char input[MAX_LENGTH + 1]; // รองรับข้อความสูงสุด 50 ตัวอักษร

    printf("เลือกโหมด:\n1. แปลงข้อความเป็น ASCII\n2. แปลง ASCII เป็นข้อความ\n");
    printf("กรุณาเลือกโหมด (1 หรือ 2): ");
    scanf("%d", &choice);
    getchar(); // เคลียร์บัฟเฟอร์หลังการอ่านตัวเลข

    if (choice == 1) {
        printf("กรุณาป้อนข้อความ (ไม่เกิน 50 ตัวอักษร): ");
        fgets(input, sizeof(input), stdin);
        input[strcspn(input, "\n")] = '\0'; // ลบ newline ออกจากข้อความ
        if (strlen(input) > MAX_LENGTH) {
            printf("ข้อความเกินขนาดที่กำหนด!\n");
        } else {
            textToASCII(input);
        }
    } else if (choice == 2) {
        printf("กรุณาป้อนรหัส ASCII (คั่นด้วยเครื่องหมายจุลภาค): ");
        fgets(input, sizeof(input), stdin);
        input[strcspn(input, "\n")] = '\0'; // ลบ newline ออกจากข้อความ
        asciiToText(input);
    } else {
        printf("โหมดที่เลือกไม่ถูกต้อง!\n");
    }

    return 0;
}
