/*
    Change file extension.
    For GNU/Linux 64 bit version.
    Version: 1 (C port).
    Written on C (https://en.wikipedia.org/wiki/C_(programming_language))
    Original Pascal version Copyright (C) 2024 Artyomov Alexander
    C port Copyright (C) 2026 Artyomov Alexander by use chat.deepseek.com

    http://self-made-free.ru/
    aralni@mail.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

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

int main(int argc, char *argv[]) {
    char *filename;
    char *newext;
    char *result;
    char *lastdot;
    int do_rename = 0;
    size_t len;
    long f;

    // Проверка количества параметров
    if (argc < 3) {
        printf("Change file extension. Version 1 (C port)\n");
        fprintf(stderr, "Use: chext filename.ext newext [f]\n");
        return 1;
    }

    filename = argv[1];
    newext = argv[2];

    // Проверка флага 'f'
    if (argc > 3 && strcmp(argv[3], "f") == 0) {
        do_rename = 1;
    }

    len = strlen(filename);
    
    // Ищем последнюю точку в имени файла
    lastdot = NULL;
    for (f = len - 1; f >= 0; f--) {
        if (filename[f] == '.') {
            lastdot = &filename[f];
            break;
        }
    }

    // Выделяем память для результата
    result = malloc(len + strlen(newext) + 2); // +2 для точки и завершающего нуля
    if (result == NULL) {
        fprintf(stderr, "Memory allocation error\n");
        return 1;
    }

    if (lastdot != NULL) {
        // Копируем часть до последней точки
        size_t prefix_len = lastdot - filename;
        strncpy(result, filename, prefix_len);
        result[prefix_len] = '\0';
        // Добавляем новое расширение
        strcat(result, ".");
        strcat(result, newext);
    } else {
        // Нет точки - добавляем точку и новое расширение
        sprintf(result, "%s.%s", filename, newext);
    }

    if (do_rename) {
        if (rename(filename, result) != 0) {
            fprintf(stderr, "Error: Cannot rename file '%s'\n", filename);
            free(result);
            return 1;
        }
    } else {
        printf("%s\n", result);
    }

    free(result);
    return 0;
}