#include <fstream>
#include <iostream>
#include <string>
#include <filesystem>

using namespace std;
namespace fs = filesystem;

//using namespace FBB;

namespace
{
    void latexMod(string const &filename)       // called from tmp/docs/latex
    {
        fs::copy_file("../../../celeb/celeb30.eps", "celeb30.eps",
                      fs::copy_options::skip_existing);

        ifstream latex{ filename };              // available .latex file
        ofstream mod{ filename + ".mod" };      // modified .latex file

        string line;
        while (true)
        {
            getline(latex, line);               // find the \maketitle line
            if (line.find("ISBN") != string::npos) // stop at the ISBN line
                break;
            mod << line << '\n';
        }
        
        ifstream table{ "../../../celeb/celeb30.latex" };
        table.ignore(1000, '\n');               // skip the 1st (comment) line

        mod << table.rdbuf() << latex.rdbuf();
        mod.close();

        fs::rename(filename + ".mod", filename);
    }


    void htmlMod(string const &filename)       // called from tmp/docs/html
    {
        fs::copy_file("../../../celeb/celeb30.gif", "celeb30.gif",
                      fs::copy_options::skip_existing);

        ifstream html{ filename };              // available .html file
        ofstream mod{ filename + ".mod" };      // modified .html file

        string line;
        do
        {
            getline(html, line);                    // find the </div> line
            mod << line << '\n';
        }
        while (line.find("</div>") == string::npos);    // stop after </div>
        
        ifstream table{ "../../../celeb/celeb30.html" };
        table.ignore(1000, '\n');               // skip the 1st (comment) line

        mod << table.rdbuf() << html.rdbuf();
        mod.close();

        fs::rename(filename + ".mod", filename);
    }
}

int main(int argc, char **argv)
{
    string arg{ argv[1] };

    // arg[1] ends in html or latex          called from tmp/docs/latex

    if (arg.find(".latex") != string::npos)
        latexMod(arg);
    else
        htmlMod(arg);
}



