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

 Copyright 2013 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 <iostream>
#include <string>

#include <cstdio>

#include "grib_api.h"

static int toVapor(const std::string& fgrib, const std::string& fvapor);

int main(int argc, char** argv)
{
    if (argc != 3) {
        exit(1);
    }


    std::string fgrib(argv[1]);
    std::string fvapor(argv[2]);

    return toVapor(fgrib, fvapor);
}


int toVapor(const std::string& fgrib, const std::string& fvapor)
{
    FILE* fp = nullptr;
    FILE* fpOut = nullptr;
    grib_handle* gh = nullptr;
    int err = 0;

    double* value = nullptr;
    float* valueOut = nullptr;
    size_t valNum = 0;

    const int MAX_VAL_LEN = 64;
    size_t vlen = 0;
    char cval[MAX_VAL_LEN];

    // Open grib file for reading
    fp = fopen(fgrib.c_str(), "r");
    if (!fp) {
        std::cout << "Cannot open grib file: " << fgrib << std::endl;
        return 1;
    }

    // Open output file
    fpOut = fopen(fvapor.c_str(), "w+");
    if (!fpOut) {
        std::cout << "Cannot open output file: " << fvapor << std::endl;
        fclose(fp);
        return 1;
    }

    // Get messages form the file
    int cnt = 0;
    while ((gh = grib_handle_new_from_file(nullptr, fp, &err)) != nullptr) {
        if (!gh) {
            std::cout << "Unable to create grib handle fro message " << cnt << std::endl;
            return 1;
        }

        // Grid type
        std::string gridType;
        vlen = MAX_VAL_LEN;
        if (grib_get_string(gh, "gridType", cval, &vlen) == GRIB_SUCCESS) {
            gridType = std::string(cval);
        }
        else {
            std::cout << "No gridType found" << std::endl;
            return 1;
        }

        vlen = MAX_VAL_LEN;
        GRIB_CHECK(grib_get_string(gh, "shortName", cval, &vlen), nullptr);
        std::string shortName(cval);

        // Get grid dimensions
        long nx = 0, ny = 0;
        std::cout << "message: " << cnt << std::endl;

        GRIB_CHECK(grib_get_long(gh, "Ni", &nx), nullptr);
        GRIB_CHECK(grib_get_long(gh, "Nj", &ny), nullptr);

        std::cout << nx << " " << ny << std::endl;

        // Allocate array for values
        size_t num = 0;
        grib_get_size(gh, "values", &num);
        if (num != static_cast<size_t>(nx * ny)) {
            std::cout << "No values found" << std::endl;
            return 1;
        }
        else if (valNum == 0) {
            valNum = num;
            value = new double[num];
            valueOut = new float[num];
        }
        else if (num != valNum) {
            std::cout << "Different field sizes!" << std::endl;
            return 1;
        }

        // Read values
        if (grib_get_double_array(gh, "values", value, &valNum) != 0) {
            delete[] value;
            delete[] valueOut;
            std::cout << "Failed to read values" << std::endl;
            return 1;
        }

        // Check if data should be rearranged
        long iScan = 0, jScan = 0;
        long jOrder = 0;

        // GRIB_CHECK(grib_get_double(gh,"latitudeOfFirstGridPointInDegrees",&lat1),0);
        // GRIB_CHECK(grib_get_double(gh,"longitudeOfFirstGridPointInDegrees",&lon1),0);
        // GRIB_CHECK(grib_get_double(gh,"latitudeOfLastGridPointInDegrees",&lat2),0);
        // GRIB_CHECK(grib_get_double(gh,"longitudeOfLastGridPointInDegrees",&lon2),0);

        GRIB_CHECK(grib_get_long(gh, "iScansPositively", &iScan), nullptr);
        GRIB_CHECK(grib_get_long(gh, "jScansPositively", &jScan), nullptr);
        GRIB_CHECK(grib_get_long(gh, "jPointsAreConsecutive", &jOrder), nullptr);

        std::cout << "nx=" << nx << " ny=" << ny << " iScan=" << iScan << " jScan=" << jScan << " jOrder=" << jOrder << std::endl;

        // i-direction scan
        if (jOrder == 0) {
            if (iScan == 1 && jScan == 0) {
                for (unsigned int j = 0; j < ny; j++)
                    for (unsigned int i = 0; i < nx; i++)
                        valueOut[j * nx + i] = value[(ny - j - 1) * nx + i];
            }
            else if (iScan == 0 && jScan == 0) {
                for (unsigned int j = 0; j < ny; j++)
                    for (unsigned int i = 0; i < nx; i++)
                        valueOut[j * nx + i] = value[nx * ny - (ny - j - 1) * nx + i];
            }
            else if (iScan == 0 && jScan == 1) {
                for (unsigned int j = 0; j < ny; j++)
                    for (unsigned int i = 0; i < nx; i++)
                        valueOut[j * nx + i] = value[(ny - j - 1) * nx + i];
            }
            else {
                for (unsigned int i = 0; i < valNum; i++)
                    valueOut[i] = value[i];
            }
        }
        else {
            for (unsigned int i = 0; i < valNum; i++)
                valueOut[i] = value[i];
        }

        if (shortName == "z")
            for (unsigned int i = 0; i < valNum; i++)
                valueOut[i] /= 9.81;


        // Write out fields
        fwrite(valueOut, 4, valNum, fpOut);

        grib_handle_delete(gh);

        cnt++;
    }


    fclose(fp);
    fclose(fpOut);

    if (value)
        delete[] value;
    if (valueOut)
        delete[] valueOut;

    return 0;
}
