// C port of decodeurl.cpp
#include <curl/curl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define ENCODED_SIZE 8192

int main(int argc, char* argv[]) {
    int c;
    if (argc != 3) {
        printf("usage: %s <input> <output>\n", argv[0]);
        return 1;
    }
    char encoded[ENCODED_SIZE] = {'\0'};
    CURL* curl = curl_easy_init();
    char data[256];
    FILE* in = fopen(argv[1], "r");  // this is unsafe, but meh
    FILE* out = fopen(argv[2], "w");
    if (in == NULL || out == NULL) {
        printf("Failed to open file(s)!\n");
        return 1;
    }
    char* p = &encoded[strlen(encoded)];
    while ((c = fgetc(in)) != EOF) {
        *p++ = c;
        if (p == &encoded[ENCODED_SIZE-1]) break;
    }
    *p = '\0';
    rewind(in);  // we probably don't need this!!
    char* decoded = curl_easy_unescape(curl, encoded, 0, NULL);
    fprintf(out, "%s", decoded);
    // fwrite(decoded, sizeof(char), sizeof(decoded), in);
    curl_easy_cleanup(curl);
    fclose(in);
    fclose(out);
    return 0;
}
