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

#define BUFF_SZ 128

// Obtain the lenght of string
int my_strlen(char *str, int max_len) {
    if (str == NULL) return -1;

    int i = 0;
    while (*(str + i) != '\0' && i < max_len)
        i++;

    return i;
}

// convert ASCII CAPITAL CASE ALPHABETS into lower case alphabets
void to_lower(char *str, int sz) {
    if (str == NULL) return;

    for (int i = 0; i < sz; i++) {
        if (*(str + i) >= 'A' && *(str + i) <= 'Z') {
            *(str + i) = *(str + i) + 0x20;
        }
    }
}

// remove every non-alphabet letters from string
int strip(char *str, char *dest, int sz) {
    if (str == NULL || dest == NULL) {
        return -1;
    }

    int ret_sz = 0;

    for (int i = 0; i < sz; i++) {
        if (*(str + i) >= 'a' && *(str + i) <= 'z') {
            *(dest + ret_sz) = *(str + i);
            ret_sz++;
        }
    }

    *(dest + ret_sz) = '\0';

    return ret_sz;
}

// check if string is a palindrome
bool kaibun(char *str, int sz) {
    if (str == NULL) return false;

    for (int i = 0; i < (sz - 1)/2; i++) {
        if (*(str + i) != *(str + sz - i - 2)) {
            return false;
        }
    }

    return true;
}

int main(void) {
    // BUFF_SZ letters + null terminator
    char *buff = (char*)malloc(sizeof(char) * (BUFF_SZ + 1)); 
    char *processed_str = (char*)malloc(sizeof(char) * (BUFF_SZ + 1));
    
    printf("Input string: ");
    char* res = fgets(buff, BUFF_SZ, stdin);
    if (res == NULL) {
        printf("Error while reading from stdin\n");
        return 1;
    }

    int len = my_strlen(buff, BUFF_SZ);
    if (len == -1) {
        printf("Error on retrival of string length.");
        return 1;
    }
    to_lower(buff, len);
    len = strip(buff, processed_str, len);

    bool isPalindrome = kaibun(processed_str, len + 1);

    printf("isPalindrome: %s\n", isPalindrome ? "true" : "false");

    return 0;
}
