#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PREFIX "map "
#define NEWFILE_PREFIX "mapcommand "

int main(int argc, char *argv[]) {
    /* Check if a file was provided */
    if (argc < 2) {
        printf("Usage: Drag and drop a file onto this program.\n");
        return 1;
    }

    /* Open the input file (the first argument) */
    char *inputPath = argv[1];
    FILE *infile = fopen(inputPath, "r");
    if (!infile) {
        perror("Error opening input file");
        return 1;
    }

    /* Extract the file name from the full path.
       We look for the last occurrence of '\' or '/' to separate the directory. */
    char *filename = strrchr(inputPath, '\\');
    if (!filename) {
        filename = strrchr(inputPath, '/');
    }
    if (filename)
        filename++;  // Move past the slash
    else
        filename = inputPath;  // No directory found, use entire string

    /* Prepare the directory portion (if any) */
    int dirLength = 0;
    char directory[1024] = "";
    if (filename != inputPath) {
        dirLength = (int)(filename - inputPath);
        if (dirLength > 1023)
            dirLength = 1023;
        strncpy(directory, inputPath, dirLength);
        directory[dirLength] = '\0';
    }

    /* Build the output file path.
       The new file will be in the same directory with "mapcommand " prepended to its name. */
    char outputPath[2048];
    if (dirLength > 0) {
        snprintf(outputPath, sizeof(outputPath), "%s%s%s", directory, NEWFILE_PREFIX, filename);
    } else {
        snprintf(outputPath, sizeof(outputPath), "%s%s", NEWFILE_PREFIX, filename);
    }

    /* Open the output file for writing */
    FILE *outfile = fopen(outputPath, "w");
    if (!outfile) {
        perror("Error creating output file");
        fclose(infile);
        return 1;
    }

    /* Read the input file line by line,
       prepend "map " to each line, and write it to the output file */
    char line[4096];
    while (fgets(line, sizeof(line), infile)) {
        fputs(PREFIX, outfile);
        fputs(line, outfile);
    }

    fclose(infile);
    fclose(outfile);

    return 0;
}
