/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "CptecAccess.h"

#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>

#include "MvMiscellaneous.h"

void CptecAccess::serve(MvRequest& in, MvRequest& out)
{
    std::cout << "CPTEC Access::serve in..." << std::endl;
    in.print();

    int i;

    // Get some input arguments
    if (!get_common_input_info(in))
        return;

    // Build path
    if (!build_path(in))
        return;

    // Build filename(s) (full path)
    std::vector<std::string> vfiles;
    if (!build_filenames(in, vfiles)) {
        std::string error = "Cptec Access-> FILE(S) NOT FOUND: ";
        if (!vfiles.empty())
            error += vfiles[0].c_str();
        setError(1, error.c_str());
        return;
    }

    // Build output file
    if (!build_output_file(in, vfiles, out))
        return;

    std::cout << "CPTEC Access::serve out..." << std::endl;
    out.print();

    return;
}

bool CptecAccess::get_common_input_info(const MvRequest& in)
{
    // Get all values related to parameter DATE
    if (!in.getValue("DATE", sdates_, false))
        return false;

    // Get all values related to parameter TIME
    // OBS: this version only allowed one time value, but
    // the algorithm below accepts many values
    int ntimes = in.countValues("TIME");
    itimes_.clear();
    itimes_.reserve(ntimes);
    for (int i = 0; i < ntimes; ++i)
        itimes_.push_back((int)in("TIME", i) / 100);  // hhmm

    // Get grid resolution
    // if (strcmp((const char*)in("GRID"), "OFF") == 0)
    //     resX_ = resY_ = 0.;
    // else {
    //     resX_ = (double)in("GRID", 0);
    //     resY_ = (double)in("GRID", 1);
    // }

    return true;
}

bool CptecAccess::build_path(MvRequest& in)
{
    // Build the path
    // 1. Date/time related string
    const char* date = in("DATE");
    const char* time = in("TIME");
    std::string yyyymm(date, 6);
    std::string dd(date, 6, 2);
    std::string hh(time, 2);
    std::string sdate = yyyymm + '/' + dd + hh;

    // eta 20
    //  /rede/eva01/modoper/tempo/regional/etap_20km/grbctl/2012/Jan/11
    //  /rede/tupa_tempo/Eta/ams_15km/temp/201202/1700/grib

    // eta 15 - 1h
    //  /rede/contg02/stornext/oper/tempo/Eta/ams_15km/temp/201201/1100/grib

    // 2. Fixed part of the path. Try to get it from the
    // environment variable: METVIEW_CPTEC_ACCESS_PATH.
    // If not defined, use a default value.
    const char* fpath = getenv("METVIEW_CPTEC_ACCESS_PATH");
    spath_ = fpath ? fpath : "/data";

    // 3. Part of the path related to the model
    std::string stype, smodel, sobs;
    if (!in.getValue("TYPE", stype, false))
        return false;

    smodel.empty();
    sobs.empty();
    in.getValue("MODEL", smodel, true);
    in.getValue("OBSERVATION", sobs, true);

    if (stype == "MODEL") {
        if (smodel == "BAM") {
            model_res_ = "TQ0666L064";
            spath_ += "/BAM/" + model_res_ + "/";
        }
        else if (smodel == "BAM_HIBRIDO") {
            model_res_ = "TQ0666L064";
            spath_ += "/BAM_hibrido/" + model_res_ + "/";
        }
    }
#if 0
        else if (strcmp(model, "ETA151") == 0)
            spath_ += "/Eta/ams_15km/temp/" + sdate + "/grib/";
        else if (strcmp(model, "ETANOR") == 0)
            spath_ += "/Eta/nor_10km/" + sdate + "/grbctl/";
        else if (strcmp(model, "ETAVALE") == 0)
            spath_ += "/Eta/smar_5km/" + sdate + "/grbctl/";
        else if (strcmp(model, "GLOBAL299") == 0)
            spath_ += "/MCGA/TQ0299L064/" + sdate + "/pos/";
        else if (strcmp(model, "GLOBAL213") == 0)
            spath_ += "/MCGA/TQ0213L042/" + sdate + "/pos/";
        else if (strcmp(model, "BRAMS05") == 0)
            spath_ += "/BRAMS/ams_05km/" + sdate + "/grads/";
        else if (strcmp(model, "MCGA3DVAR") == 0)
            spath_ += "/G3DVAR/" + sdate + "/mcga/pos/dataout/";
    }
#endif
    else if (stype == "OBSERVATION") {
        spath_ += "/BUFR/";
#if 0
        if (strcmp(observation, "SYNOP") == 0)
            spath_ = "/rede/dds_trabalho/GEMPAK_BUFR/";
        else if (strcmp(observation, "PREPBUFR") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "EMA_INMET") == 0)
            spath_ = "/rede/dds_trabalho/HDS/BUFR/";
        else if (strcmp(observation, "SYNOP") == 0)
            spath_ = "/rede/dds_trabalho/GEMPAK_BUFR/";
        else if (strcmp(observation, "SHIP") == 0)
            spath_ = "/rede/dds_trabalho/GEMPAK_BUFR/";
        else if (strcmp(observation, "UPPERAIR") == 0)
            spath_ = "/rede/dds_trabalho/GEMPAK_BUFR/";
        else if (strcmp(observation, "AIRCRAFT") == 0)
            spath_ = "/rede/dds_trabalho/GEMPAK_BUFR/";
        else if (strcmp(observation, "1bamua") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "1bamub") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "1bhrs3") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "airsev") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "gpsro") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "mtiasi") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "satwnd") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
        else if (strcmp(observation, "SAnl") == 0)
            spath_ = "/rede/tupa_tempo/externos/Download/NCEP/" + sdate + "/";
    }
#endif
    }
    else {
        std::string error = "CptecAccess-> ERROR: MODEL not recognized ";
        setError(1, error.c_str());
        return false;
    }

    return true;
}

bool CptecAccess::build_filenames(MvRequest& in, std::vector<std::string>& vfn)
{
    // Part of the filename related to the model
    std::string stype = (const char*)in("TYPE");
    if (stype == "MODEL") {
        if (!build_model_filenames(in, vfn))
            return false;
    }
    else if (stype == "OBSERVATION") {
        if (!build_observation_filenames(in, vfn))
            return false;
    }
    else {
        std::string error = "CptecAccess-> ERROR: TYPE not recognized ";
        setError(1, error.c_str());
        return false;
    }

    for (auto it : vfn)
        std::cout << "FILENAMES: " << it << std::endl;

    return true;
}

bool CptecAccess::build_model_filenames(MvRequest& in, std::vector<std::string>& vfn)
{
    std::string smodel = (const char*)in("MODEL");

    // Get STEP values (hours)
    // If STEP is not given or its single value is ALL then variable
    // isteps_ is empty
    isteps_.clear();
    if ((const char*)in("STEP")) {
        int n = in.countValues("STEP");
        if (n == 1 && strcmp((const char*)in("STEP", 0), "ALL") == 0) {
            // input value is ALL -> continue
        }
        else {
            isteps_.reserve(n);
            for (int i = 0; i < n; ++i)
                isteps_.push_back((int)in("STEP", i));
        }
    }

    // Build filenames
    if (smodel == "BAM") {
        if (!build_bam_filenames(vfn))
            return false;
    }
    else if (smodel == "BAM_HIBRIDO") {
        if (!build_bam_filenames(vfn))
            return false;
    }
    else {
        std::string error = "Cptec_Access-> ERROR: MODEL " + smodel + " not implemented yet";
        setError(1, error.c_str());
        return false;
    }
#if 0
    int i, j;

        if (model == "ETA151") {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = "eta_15km_";
                    cs             = cs + buf + '+';

                    // Forecast time stamp string
                    for (k = 0; k < nsteps; k++) {
                        // Forecast date
                        MvDate dfore = danal + steps[k] / 24.;
                        dfore.Format("yyyymmddHH", buf);
                        vfn.push_back(cs + buf + ".grb");
                    }
                }
            }
        }
        else if (model == "ETANOR") {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = "eta_10km_";
                    cs             = cs + buf + '+';

                    // Forecast time stamp string
                    for (k = 0; k < nsteps; k++) {
                        // Forecast date
                        MvDate dfore = danal + steps[k] / 24.;
                        dfore.Format("yyyymmddHH", buf);
                        vfn.push_back(cs + buf + ".grb");
                    }
                }
            }
        }
        else if (strcmp(model, "ETAVALE") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = "eta_05km_";
                    cs             = cs + buf + '+';

                    // Forecast time stamp string
                    for (k = 0; k < nsteps; k++) {
                        // Forecast date
                        MvDate dfore = danal + steps[k] / 24.;
                        dfore.Format("yyyymmddHH", buf);
                        vfn.push_back(cs + buf + ".grb");
                    }
                }
            }
        }
        else if (strcmp(model, "GLOBAL299") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = "GPOSNMC";
                    cs             = cs + buf;

                    // Forecast time stamp string
                    for (k = 0; k < nsteps; k++) {
                        // Forecast date
                        MvDate dfore = danal + steps[k] / 24.;
                        dfore.Format("yyyymmddHH", buf);
                        vfn.push_back(cs + buf + "P.fct.TQ0299L064.grb");
                    }
                }
            }
        }
        else if (strcmp(model, "GLOBAL213") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = "GPOSNMC";
                    cs             = cs + buf;

                    // Forecast time stamp string
                    for (k = 0; k < nsteps; k++) {
                        // Forecast date
                        MvDate dfore = danal + steps[k] / 24.;
                        dfore.Format("yyyymmddHH", buf);
                        vfn.push_back(cs + buf + "P.fct.TQ0213L042.grb");
                    }
                }
            }
        }
        else if (strcmp(model, "MCGA3DVAR") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = "GPOSCPT";
                    cs             = cs + buf;

                    // Forecast time stamp string
                    for (k = 0; k < nsteps; k++) {
                        // Forecast date
                        MvDate dfore = danal + steps[k] / 24.;
                        dfore.Format("yyyymmddHH", buf);
                        vfn.push_back(cs + buf + "P.fct.TQ0299L064.grb");
                    }
                }
            }
        }
        else if (strcmp(model, "BRAMS05") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = "JULES_BRAMS05km_";
                    cs             = cs + buf + "_";

                    // Forecast time stamp string
                    for (k = 0; k < nsteps; k++) {
                        // Forecast date
                        MvDate dfore = danal + steps[k] / 24.;
                        dfore.Format("yyyymmddHH", buf);
                        vfn.push_back(cs + buf + ".grib2");
                    }
                }
            }
        }
#endif
    return true;
}


bool CptecAccess::build_observation_filenames(MvRequest& in,
                                              std::vector<std::string>& vfn)
{
    // Get observation type
    std::string sobs = (const char*)in("OBSERVATION");
    metview::toLower(sobs);

    // Build filenames
    std::string sdate_dir, fname;
    std::string fn_suffix = ".bufr";
    std::stringstream ss;
    for (auto it_date : sdates_) {
        sdate_dir = it_date.substr(0, 6) + "/" + it_date.substr(6, it_date.length()) + "/";
        for (auto it_time : itimes_) {
            ss.str("");
            ss << std::setw(2) << std::setfill('0') << it_time;
            fname = it_date + ss.str() + "_" + sobs + fn_suffix;
            vfn.push_back(spath_ + sdate_dir + fname);
        }
    }

#if 0
        if (strcmp(observation, "PREPBUFR") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //gdas1.t00z.1bamua.tm00.bufr_d.20121129   vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.prepbufr.nr." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "1bamua") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.1bamua.tm" + rodada + ".bufr_d." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "1bamub") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.1bamub.tm" + rodada + ".bufr_d." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "1bhrs3") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.1bhrs3.tm" + rodada + ".bufr_d." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "airsev") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.airsev.tm" + rodada + ".bufr_d." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "gpsro") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.gpsro.tm" + rodada + ".bufr_d." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "mtiasi") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.mtiasi.tm" + rodada + ".bufr_d." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "satwnd") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas1.t" + rodada + "z.satwnd.tm" + rodada + ".bufr_d." + anomesdia);
                }
            }
        }
        else if (strcmp(observation, "SAnl") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    //vfn.push_back("gdas1.T" + rodada + "Z.prepbufr.nr." + anomesdia + rodada);
                    vfn.push_back("gdas2.T" + rodada + "Z.SAnl." + anomesdia + rodada);
                }
            }
        }
        else if (strcmp(observation, "EMA_INMET") == 0) {
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmdd", buf);
                    danal.Format("HH", buf2);
                    std::string rodada    = buf2;
                    std::string anomesdia = buf;
                    vfn.push_back("ISAI_" + anomesdia + rodada + ".wmo");
                }
            }
        }
        else {
            std::string tobs = (const char*)in("OBSERVATION");
            std::transform(tobs.begin(), tobs.end(), tobs.begin(), ::tolower);

            // Build all filenames
            // char buf[12];
            for (i = 0; i < ndates; i++) {
                MvDate dd(sdates_[i]);
                for (j = 0; j < ntimes; j++) {
                    // Analise time stamp string
                    MvDate danal = dd + itimes_[j] / 24.;
                    danal.Format("yyyymmddHH", buf);
                    std::string cs = buf;
                    vfn.push_back(cs + "_" + tobs + ".bufr");
                }
            }
        }
#endif
    return true;
}

bool CptecAccess::build_bam_filenames(std::vector<std::string>& vfn)
{
    // // Level list is ALL
    // std::vector<std::string> vlevels = vlev;
    // if (sltype != "sfc" && vlevels.empty())
    //     vlevels = {"1000", "850", "500", "250"};

    // // Convert all parameter names to uppercase; so users can provide input
    // // parameter names in lower or uppercase
    // std::vector<std::string> vparams = sparams_;
    // for (std::string& s : vparams)
    //     metview::toUpper(s);

    // Build filenames
    std::string sdate_dir, sdate_hr_dir, fname_p, fname_f;
    std::string fn_prefix = "GPOSNMC";
    std::string fn_suffix = "P.fct." + model_res_ + ".grb";
    std::stringstream ss;
    for (auto it_date : sdates_) {
        sdate_dir = it_date.substr(0, 6) + "/" + it_date.substr(6, it_date.length());
        for (auto it_time : itimes_) {
            ss << std::setw(2) << std::setfill('0') << it_time;
            sdate_hr_dir = sdate_dir + ss.str() + "/";
            fname_p = fn_prefix + it_date + ss.str();
            MvDate danalise(stoi(it_date));
            for (auto it_step : isteps_) {
                MvDate dverify = danalise + (float)(it_step / 24.);
                char buf[11];
                dverify.Format("yyyymmddHH", buf);
                fname_f = fname_p + buf + fn_suffix;
                vfn.push_back(spath_ + sdate_hr_dir + fname_f);
            }
        }
    }

    return vfn.empty() ? false : true;
}

bool CptecAccess::build_output_file(MvRequest& in, std::vector<std::string>& vfn, MvRequest& out)
{
    std::string stype = (const char*)in("TYPE");
    std::string outfname;
    std::string verb;

    // Handling model data
    if (stype == "MODEL") {
        if (!build_model_output_file(in, vfn, outfname))
            return false;

        verb = "GRIB";
    }

    // Handling observation data
    else if (stype == "OBSERVATION") {
        if (!build_observation_output_file(in, vfn, outfname))
            return false;

        verb = "BUFR";
    }

    // Check output file
    if (outfname.empty()) {
        std::string error = "CptecAccess-> ERROR: Output file empty";
        setError(1, error.c_str());
        return false;
    }

    // Create output request
    out.setVerb(verb.c_str());
    out("PATH") = outfname.c_str();

    return true;
}

bool CptecAccess::build_model_output_file(MvRequest& in, std::vector<std::string>& vfn, std::string& outfname)
{
    // Get LEVEL_TYPE value
    slevel_type_ = (const char*)in("LEVEL_TYPE");
    // std::string sltype;
    // if (slevel_type_ == "10_METER")
    //     sltype = "sfc";
    // else
    //     sltype = slevel_type_;

    // Get LEVEL_LIST values: int and string formats
    // If LEVEL_LIST is not given or its single value is ALL then variable
    // ilevels_ is empty
    ilevels_.clear();
    if ((const char*)in("LEVEL_LIST")) {
        int n = in.countValues("LEVEL_LIST");
        if (n == 1 && strcmp((const char*)in("LEVEL_LIST", 0), "ALL") == 0) {
            // input value is ALL -> continue
        }
        else {
            ilevels_.reserve(n);
            for (int i = 0; i < n; ++i)
                ilevels_.push_back((int)in("LEVEL_LIST", i));
        }
    }
    //    std::vector<std::string> slevels;
    //    left_pad_string(ilevels_, 0, slevels);

    // Get PARAMETER values
    if (!in.getValue("PARAMETER", sparams_, false))
        return false;

    std::string smodel = (const char*)in("MODEL");
    if (smodel == "BAM") {
        outfname = build_bam_output_file(vfn);
    }
    else if (smodel == "BAM_HIBRIDO") {
        outfname = build_bam_output_file(vfn);
    }

#if 0
    // Get the requested PARAMs
    const char* caux;
    int nparams = in.iterInit("PARAMETER");
    std::map<std::string, int> params;
    std::string param;
    for (i = 0; i < nparams; ++i) {
        in.iterGetNextValue(caux);
        param         = caux;
        params[param] = 1;
    }

    // Get the requested LEVELs
    int nlevels = in.iterInit("LEVEL_LIST");
    std::map<long, int> levels;
    double dlevel;
    for (i = 0; i < nlevels; ++i) {
        in.iterGetNextValue(dlevel);
        levels[(long)dlevel] = 1;
    }

    // Build the requested fieldset
    // For each input file filter the requested fields by PARAM/LEVEL
    // and add them to the output GRIB file

    // Auxilliary variables for GribApi
    char shortName[20];
    size_t len;
    int error       = 0;
    grib_handle* h  = nullptr;
    grib_context* c = grib_context_get_default();

    // Create the output file name
    std::string outname(marstmp());
    for (i = 0; i < (signed)vfiles.size(); ++i) {
        // Full filename
        std::string ffile = spath_ + vfiles[i];

        // Open the input file
        FILE* f = fopen(ffile.c_str(), "r");
        if (!f) {
            std::string error = "CptecAccess-> FILE NOT FOUND: ";
            error += ffile.c_str();
            setError(1, error.c_str());
            return;
        }

        // Loop on all GRIB messages in file
        long level;
        while ((h = grib_handle_new_from_file(c, f, &error)) != nullptr) {
            len = 20;
            grib_get_string(h, "shortName", shortName, &len);
            param = std::string(shortName);
            grib_get_long(h, "level", &level);
            if (params.find(param) != params.end()) {
                if (levels.find(level) != levels.end()) {
                    grib_write_message(h, outname.c_str(), "a");
                }
            }

            grib_handle_delete(h);
        }

        // Create output request
        out.setVerb("GRIB");
        out("PATH") = outname.c_str();

        fclose(f);
    }
#endif
    return true;
}

bool CptecAccess::build_observation_output_file(MvRequest& in, std::vector<std::string>& vfn, std::string& outfname)
{
    // Open output file
    outfname = marstmp();
    std::ofstream dst(outfname.c_str(), std::ios::binary);

    // Build the requested bufr
    // Add requested bufr files to a single output file
    for (auto fname : vfn) {
        std::ifstream src(fname.c_str(), std::ios::binary);
        dst << src.rdbuf();
        src.close();
    }
    dst.close();

    return true;
}

std::string CptecAccess::build_bam_output_file(std::vector<std::string>& vfn)
{
    // Convert all parameter names to uppercase; so users can provide input
    // parameter names in lower or uppercase
    for (auto& s : sparams_)
        metview::toUpper(s);

    // Build the requested fieldset
    // Add requested messages to the output file
    // For each input file filter the requested fields by TYPE/PARAM/LEVEL
    // and add them to the output GRIB file
    int count = 0;
    std::string outname(marstmp());
    for (auto fname : vfn) {
        // Auxilliary variables for GribApi
        char caux[40];
        size_t len;
        int ierror = 0;
        grib_handle* h = nullptr;
        grib_context* c = grib_context_get_default();

        // Open input grib file
        FILE* f = fopen(fname.c_str(), "r");
        if (!f) {
            std::string error = "CptecAccess-> FILE NOT FOUND: ";
            error += fname.c_str();
            setError(1, error.c_str());
            return std::string();
        }

        // Search and save requested messages
        long ilevel;
        std::string sparam, levelType;
        while ((h = grib_handle_new_from_file(c, f, &ierror)) != nullptr) {
            len = 40;
            grib_get_string(h, "shortName", caux, &len);
            sparam = std::string(caux);
            metview::toUpper(sparam);

            len = 40;
            grib_get_string(h, "mars.levtype", caux, &len);
            levelType = std::string(caux);

            grib_get_long(h, "level", &ilevel);
            if (std::find(sparams_.begin(), sparams_.end(), sparam) != sparams_.end())
                if (levelType == slevel_type_)
                    if (ilevels_.empty() ||
                        (std::find(ilevels_.begin(), ilevels_.end(), ilevel) !=
                         ilevels_.end())) {
                        grib_write_message(h, outname.c_str(), "a");
                        count++;
                    }

            grib_handle_delete(h);
        }

        fclose(f);
    }

    // Consistency check
    if (count == 0) {
        std::string error = "CptecAccess-> Empty output file: no fields found";
        setError(1, error.c_str());
        return std::string();
    }

    return outname;
}

int main(int argc, char** argv)
{
    MvApplication theApp(argc, argv);
    CptecAccess data("CPTEC_ACCESS");

    theApp.run();
}
