#include <windows.h>
#include <shobjidl.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(hr)) {
        fprintf(stderr, "CoInitializeEx failed: 0x%lx\n", hr);
        exit(1);
    }

    char file[MAX_PATH] = {0};
    IFileOpenDialog *pFileOpen = NULL;
    IShellItem *pItem = NULL;
    PWSTR pszFilePath = NULL;

    hr = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
                          &IID_IFileOpenDialog, (void**)&pFileOpen);

    if (SUCCEEDED(hr)) {
        COMDLG_FILTERSPEC rgSpec[] = {{L"All Files", L"*.*"}};
        pFileOpen->lpVtbl->SetFileTypes(pFileOpen, ARRAYSIZE(rgSpec), rgSpec);

        pFileOpen->lpVtbl->SetTitle(pFileOpen, L"Select File");

        DWORD dwFlags;
        pFileOpen->lpVtbl->GetOptions(pFileOpen, &dwFlags);
        pFileOpen->lpVtbl->SetOptions(pFileOpen, dwFlags | FOS_FILEMUSTEXIST | FOS_PATHMUSTEXIST);

        hr = pFileOpen->lpVtbl->Show(pFileOpen, NULL);

        if (SUCCEEDED(hr)) {
            hr = pFileOpen->lpVtbl->GetResult(pFileOpen, &pItem);

            if (SUCCEEDED(hr)) {
                hr = pItem->lpVtbl->GetDisplayName(pItem, SIGDN_FILESYSPATH, &pszFilePath);

                if (SUCCEEDED(hr)) {
                    wcstombs(file, pszFilePath, MAX_PATH);
                }
            }
        }
    }

    // Clean up COM objects and memory.
    if (pszFilePath) {
        CoTaskMemFree(pszFilePath);
    }
    if (pItem) {
        pItem->lpVtbl->Release(pItem);
    }
    if (pFileOpen) {
        pFileOpen->lpVtbl->Release(pFileOpen);
    }
    CoUninitialize();

    // Check if a file was successfully selected.
    if (FAILED(hr) || file[0] == '\0') {
        puts("File selection cancelled or failed.");
        exit(1);
    }

    FILE *f = fopen(file, "r");
    if (!f) {
        perror("fopen(...)");
        exit(1);
    }

    long input;
    if (fscanf(f, "%ld", &input) != 1) {
        puts("fscanf(...) failed to scan input number");
        fclose(f);
        exit(1);
    }

    printf("%ld\n", 2 * input);

    fclose(f);
    return 0;
}