#include <curl/curl.h>
#include <curl/easy.h>

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

void usage();
char *get_default_filepath(char *);


int
main(int argc, char** argv)
{
	char *filepath = NULL;
	char *url = NULL;

	if(argc == 2){
		url = argv[1];
		filepath = get_default_filepath(url); //filepath is a pointer inside url
	}else if(argc == 3){
		url = argv[1];
		filepath = argv[2];
	}else
		usage();

	printf("url:%s\nfilepath:%s\n", url, filepath);
	
	CURL *curl = curl_easy_init();
	CURLcode res;

	if(!curl)
	{
		fprintf(stderr, "Curl init failled, baling!");
		exit(1);
	}

	FILE *file;
	file = fopen(filepath,"wb");

	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);	


	if(!file){
		fprintf(stderr, "Could not open file!");
		exit(1);
	}

	res = curl_easy_perform(curl);

	if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));	
	else
            fprintf(stdout, "curl returned %s; Downloaded %s \n", curl_easy_strerror(res), filepath);	

	fclose(file);
	curl_easy_cleanup(curl);
	return 0;
}


char* get_default_filepath(char *url) {
    char *filepath = strdup(url);
    char *tmp = strtok(filepath, "/");
    while(tmp != NULL) {
        filepath = tmp;
        tmp = strtok(NULL, "/");
    }
    return filepath;
}

void
usage(){
	puts("usage: <url> <file path>(optional, default is ./<filename on url>)");
	exit(0);
}


