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

#include "tap.h"
#include "pstap.h"

#define ORIGINAL "This is, a, test case, to check."
#define CORRECTED "This is a test case to check."

int main (void)
{
    plan_tests(16);

    diag("psStringSubstitute() tests");

    // Return input for NULL key
    {
        psString input = psStringCopy(ORIGINAL);
        psStringSubstitute(&input, ",", NULL);
        ok(input && strcmp(input, ORIGINAL) == 0, "output = %s", input);
        psFree(input);
        //        ok(psMemCheckLeaks(0, NULL, stdout, false) == 0, "Memory Leaks");
        mem();
    }

    // Return input for empty key
    {
        psString input = psStringCopy(ORIGINAL);
        psStringSubstitute(&input, "XXX", "");
        ok(input && strcmp(input, ORIGINAL) == 0, "output = %s", input);
        psFree(input);
        //        ok(psMemCheckLeaks(0, NULL, stdout, false) == 0, "Memory Leaks");
        mem();
    }

    // Return corrected version for NULL replace
    {
        psString input = psStringCopy(ORIGINAL);
        psStringSubstitute(&input, NULL, ",");
        ok(input && strcmp(input, CORRECTED) == 0, "output = %s", input);
        psFree(input);
        mem();
    }

    // Return corrected version for empty replace
    {
        psString input = psStringCopy(ORIGINAL);
        psStringSubstitute(&input, "", ",");
        ok(input && strcmp(input, CORRECTED) == 0, "output = %s", input);
        psFree(input);
        mem();
    }

    // Return NULL for NULL input
    {
        int status = psStringSubstitute(NULL, "XXX", ",");
        ok(status == 0, "status = %d", status);
        mem();
    }

    // Return emptry string for empty input
    {
        psString input = psStringCopy("");
        psStringSubstitute(&input, "XXX", ",");
        ok(input && strcmp(input, "") == 0, "output = %s", input);
        psFree(input);
        mem();
    }

    // Change commas to bangs
    {
        psString input = psStringCopy(ORIGINAL);
        psStringSubstitute(&input, "!", ",");
        ok(input && strcmp(input, "This is! a! test case! to check.") == 0, "output = %s", input);
        psFree(input);
        mem();
    }

    // Long replacement text --- should allocate new space
    {
        psString input = psStringCopy(ORIGINAL);
        psStringSubstitute(&input, "; This string is too long to fit in input(35 chars)", ".");
        ok(input && strcmp(input, "This is, a, test case, to check; "
                           "This string is too long to fit in input(35 chars)") == 0,
           "output = %s", input);
        psFree(input);
        mem();
    }


    return exit_status();
}
