#include <cctype>
#include <cstring>

#include <iostream>
#include <string>

using namespace std;

string d_pattern;
string d_first;

bool vMatch(string const &hdr)
{
    size_t length = d_pattern.length();
    int lastIdx = hdr.length() - length;

    if (lastIdx < 0)
        return false;

    char const *cHdr = &hdr.front();
    char const *cPattern = &d_pattern.front();

    size_t hdrIdx = 0;
    while (true)
    {
        hdrIdx = hdr.find_first_of(d_first, hdrIdx);
        if (
            hdrIdx == string::npos      // first pattern char. not found
            or 
            static_cast<int>(hdrIdx) > lastIdx // pattern longer than the rest
        )
            return false;               // then no match

                                        // case insensitive match 
        if (strncasecmp(cPattern, cHdr + hdrIdx, length) == 0)
            return true;
        
        ++hdrIdx;                       // continue at the next char.
    }
}


string hdr = R"_(
Received: from bounce.tanium.com (bounce.tanium.com [192.28.145.4])
    by filter1-ams.surfmailfilter.nl (Halon) with ESMTPS
    id ec5f5ae8-b10d-11ed-8e4f-005056a3ec54;
    Mon, 20 Feb 2023 12:01:28 +0100 (CET)
)_";

int main(int argc, char **argv)
{
    if (argc == 1)
    {
        cout << "arg1: pattern, opt arg2 #iterations (default 1), "
                                                        "opt arg3: hdr\n";
        return 0;
    }

    d_pattern = argv[1];
    char ch = d_pattern.front();
    d_first = ch;
    if (isalpha(ch))
        d_first += islower(ch) ? toupper(ch) : tolower(ch);
    cout << "first: " << d_first << '\n';

    size_t end = argc < 3 ? 1 : stoul(argv[2]); 
    if (argc == 4)
    {
        hdr = argv[3];
        cout << "hdr = " << hdr << '\n';
    }

    bool ret = false;
    size_t idx = 0; 
    for (; idx != end; ++idx)
        ret = vMatch(hdr);

    cout << "iterations: " << idx << "\n"
            "match: " << ret << '\n';
}




