
#include "windows.h"
#include "curl.h"

BOOL FirstTime = TRUE;  // Just in order to reproduce the 'bug'

HANDLE fileH = NULL;
DWORD downloadedSz = 0;
int downloadProgress(void *buffer, size_t size, size_t nmemb,void* nothing)
{
    DWORD written = 0;
    if(!WriteFile(fileH,buffer,size*nmemb,&written,NULL))
        return 0;
    downloadedSz += written;

    if(FirstTime && downloadedSz > 4000)    // The first time we download only part of the file
        return 0;

    if(downloadedSz > 8000)                 // We don need the complete file, just a little more to check if it gets what expected
        return 0;

    return written;
}

HANDLE errfh = NULL;
int curlDebug(CURL* c, curl_infotype cinfo, char* str, size_t sz, void* data)
{
    if(errfh==NULL)
        errfh = CreateFile(FirstTime?"c:\\curlDebug1.log":"c:\\curlDebug2.log",GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
    DWORD written = 0;
    if(errfh!=NULL && errfh!=INVALID_HANDLE_VALUE)// && cinfo<CURLINFO_DATA_IN)
        WriteFile(errfh,str,sz,&written,NULL);
    return 0;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    fileH = CreateFile("C:\\DownloadedBitComet.exe",GENERIC_WRITE,0,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
    if(fileH==INVALID_HANDLE_VALUE)
        return -1;
    downloadedSz = GetFileSize(fileH,NULL);

    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if(!curl)
        return -1;
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.bitcomet.com/achive/BitComet_0.44.exe");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, downloadProgress);
    curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curlDebug);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, TRUE);
    if(downloadedSz>0)
    {
        FirstTime = FALSE;
        res = curl_easy_setopt(curl, CURLOPT_RESUME_FROM, downloadedSz);
        if(res==CURLE_OK)
            SetFilePointer(fileH,0,NULL,FILE_END);
    }

    res = curl_easy_perform(curl);

    if(errfh)
        CloseHandle(errfh);
    CloseHandle(fileH);
    curl_easy_cleanup(curl);

    if(FirstTime)
        MessageBox(NULL,"First Attempt Done. Run it now again, please.","LibCurl ResumeTest",MB_OK);
    else
        MessageBox(NULL,"Finished Test. Check Results, Thanks.","LibCurl ResumeTest",MB_OK);

    return TRUE;
}

