/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>

#include <windows.h>
#include <initguid.h>
#include <tchar.h>

#define COBJMACROS
#include "Test.h"

void ReturnCheck(LPTSTR func, HRESULT res)
{
    if(res != S_OK)
    {
        TCHAR buffer[1000];
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, res, 0, buffer, sizeof(buffer), 0);
        _tprintf("%s: %s\n", func, buffer);
        exit(1);
    }
}

int main()
{
    HRESULT res;
    ITest *pTest, *another, *temp;
    ITest2 *pTest2;
    int v, iv, sum;
    BSTR s1, s2, s3, sv;
    CoInitialize(NULL);
    printf("COM/C:\n");
    res = CoCreateInstance(&CLSID_CoTest, NULL, CLSCTX_INPROC_SERVER, &IID_ITest, (void**)&pTest);
    ReturnCheck(_T("CoCreateInstance"), res);
    res = ITest_Add(pTest, 123, 456, &v);
    ReturnCheck(_T("Add"), res);
    printf("123 + 345 = %d\n", v);
    s1 = SysAllocString(L"ABC");
    s2 = SysAllocString(L"XYZ");
    res = ITest_Concat(pTest, s1, s2, &s3);
    ReturnCheck(_T("Concat"), res);
    printf("%d %ls + %d %ls = %d %ls\n", SysStringLen(s1), s1, SysStringLen(s2), s2, SysStringLen(s3), s3);
    SysFreeString(s1);
    SysFreeString(s2);
    SysFreeString(s3);
    ITest_get_IV(pTest, &iv);
    ITest_get_SV(pTest, &sv);
    printf("IV = %d SV = %d %ls\n", iv, SysStringLen(sv), sv);
    SysFreeString(sv);
    ITest_put_IV(pTest, 123);
    ITest_put_SV(pTest, SysAllocString(L"ABC"));
    ITest_get_IV(pTest, &iv);
    ITest_get_SV(pTest, &sv);
    printf("IV = %d SV = %d %ls\n", iv, SysStringLen(sv), sv);
    SysFreeString(sv);
    ITest_Another(pTest, &another);
    res = ITest_Add(another, 123, 456, &v);
    ReturnCheck(_T("Add"), res);
    printf("Another 123 + 345 = %d\n", v);
    ITest_Release(another);
    ITest_Release(pTest);
    res = CoCreateInstance(&CLSID_CoTest, NULL, CLSCTX_INPROC_SERVER, &IID_ITest, (void**)&temp);
    ReturnCheck(_T("CoCreateInstance"), res);
    res = ITest2_QueryInterface(temp, &IID_ITest2, &pTest2);
    ReturnCheck(_T("QueryInterface"), res);
    ITest2_Sum(pTest2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, &sum);
    printf("SUM = %d\n", sum);
    ITest2_Sum(pTest2, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, &sum);
    printf("SUM 1..5 = %d\n", sum);
    ITest2_Sum(pTest2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, &sum);
    printf("SUM 1..10 = %d\n", sum);
    ITest2_Release (pTest2);
    ITest_Release (temp);
    CoUninitialize();
    return 0;
}
