/***************************** 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 <cstdarg>
#include <cmath>
#include "Metview.h"
#include "MvRelhum.h"
#include "MvException.h"


inline double min(double a, double b)
{
    return a < b ? a : b;
}
inline double max(double a, double b)
{
    return a > b ? a : b;
}


MvRelhum::MvRelhum()
{
    init();
}

void MvRelhum::init()
{
    refDataRepres = -1;
    refDataLength = -1;
}

MvRelhum::~MvRelhum() = default;


MvRequest MvRelhum::compute(int n, MvField& f_LNSP,
                            MvFieldSetIterator& iter_t, MvFieldSetIterator& iter_q, int lmodlv)
{
    if (lmodlv)  //-- check lnsp field format consistency with other fields
    {
        if (f_LNSP.dataRepres() != refDataRepres)
            throw MvException("LNSP: different data representation!");

        if (f_LNSP.countValues() != refDataLength)
            throw MvException("LNSP: different number of grid points!");
    }

    MvFieldSet out_q;

    for (int j = 0; j < n; j++) {
        MvField f_t = iter_t();
        MvFieldExpandThenFree x_t(f_t);

        if (f_t.dataRepres() != refDataRepres)
            throw MvException("T: different data representation!");
        if (f_t.countValues() != refDataLength)
            throw MvException("T: different number of grid points!");


        MvField f_q = iter_q();
        MvFieldExpandThenFree x_q(f_q);

        if (f_q.dataRepres() != refDataRepres)
            throw MvException("Q: different data representation!");
        if (f_q.countValues() != refDataLength)
            throw MvException("Q: different number of grid points!");

        MvRequest r = f_q.getRequest();
        int level = r("LEVELIST");

        for (int jl = 0; jl < f_t.countValues(); jl++) {
            double EPS = RV / RD;
            double C2ES = C1ES * RD / RV;
            double esice = 0.0, eswat = 0.0, mixphase = 0., es = 0., pres = 0.;

            if (f_t[jl] < TMELT) {
                esice = C2ES * exp(C3IES * (f_t[jl] - TMELT) / (f_t[jl] - C4IES));
            }

            if (f_t[jl] > TICE) {
                eswat = C2ES * exp(C3LES * (f_t[jl] - TMELT) / (f_t[jl] - C4LES));
            }


            // mixphase: 0->1,   0 = ice, 1 = water

            mixphase = min(1., pow(((max(TICE, min(TMELT, f_t[jl])) - TICE) / (TMELT - TICE)), 2.));

            es = mixphase * eswat + (1. - mixphase) * esice;

            // pres = ((lmodlv) ? f_q.modelLevelToPressure (f_LNSP[jl], level) : level * 100.);
            pres = ((lmodlv) ? f_q.meanML_to_Pressure_byLNSP(f_LNSP[jl], level) : level * 100.);

#define RELHUM_TESTPRINT 0

#if RELHUM_TESTPRINT
            double q_before = f_q[jl];
#endif

            f_q[jl] = (f_q[jl] * pres * 100.) / ((1. + (EPS - 1.) * f_q[jl]) * es);

#if RELHUM_TESTPRINT
            //-- in 1.5/1.5 grid, gridpoint 9821 is: (30N,30W)
            if (jl == 9821)
                std::cout << "  " << level
                          << "\t" << pres
                          << "\t  " << f_t[jl]
                          << "\t  " << q_before
                          << "\t  " << f_q[jl]
                          << std::endl;
#endif
        }
        f_q.setGribKeyValueLong("paramId", 157);  //-- Relative humidity

        out_q += f_q;

        //      int prevAcc = mars.accuracy;  // set mars.accuracy to -1 so that libMars
        //      mars.accuracy = -1;           // does not force ecCodes to re-allocate
        out_q[out_q.countFields() - 1].setShape(packed_mem);  // memory for this
                                                              //      mars.accuracy = prevAcc;
    }

    return out_q.getRequest();
}
