/***************************** 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 <stdio.h>

#include "grib_api.h"

using namespace std;

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

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


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

    return toVapor(fgrib, fvapor);
}


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

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

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

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


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


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

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

        vlen = MAX_VAL_LEN;
        GRIB_CHECK(grib_get_string(gh, "shortName", cval, &vlen), 0);
        string shortName(cval);

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

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

        cout << nx << " " << ny << endl;

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

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

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

        //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), 0);
        GRIB_CHECK(grib_get_long(gh, "jScansPositively", &jScan), 0);
        GRIB_CHECK(grib_get_long(gh, "jPointsAreConsecutive", &jOrder), 0);

        cout << "nx=" << nx << " ny=" << ny << " iScan=" << iScan << " jScan=" << jScan << " jOrder=" << jOrder << 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;
}
