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

 Copyright 2020- 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 "mars.h"

#include "VectorUtils.h"

/* read_vector_from_request
     Reads the given request and reads in the associated vector file.
     Memory is allocated here for the vector, so it is then the responsibility
     of the called to handle it.
     Returns 0 if ok, 1 on error.
*/
int read_vector_from_request(request* r, double** vec, int* length)
{
    int size = 0;
    const char* path = NULL;
    double* v = NULL;
    FILE* f = NULL;
    char buf[20] = "";
    int readSize = 0;

    path = get_value(r, "PATH", 0); /* get the path to the storage file */

    f = fopen(path, "r");

    if (f == NULL) {
        marslog(LOG_EXIT, "read_vector_from_request: unable to load file %s", path);
        return MV_VECTOR_READ_ERROR;
    }
    else {
        fread(buf, sizeof(char), 14, f);
        buf[14] = '\0';

        if (strcmp(buf, "METVIEW_VECTOR") != 0) {
            fclose(f);
            marslog(LOG_EXIT, "read_vector_from_request: start of vector file should be METVIEW_VECTOR. Is: %s", buf);
            return MV_VECTOR_READ_ERROR;
        }

        fread(buf, sizeof(char), 10, f); /* read the data type */
        buf[10] = '\0';
        if (strncmp(buf, "float64", 7) != 0) /* we only allow this for now */
        {
            fclose(f);
            marslog(LOG_EXIT, "read_vector_from_request: only allow float64 values just now. Is: '%s'", buf);
            return MV_VECTOR_READ_ERROR;
        }

        fread(&size, sizeof(int), 1, f); /* read the number of values */

        /*-- vector to be returned, must be free'd by the calling pgm --*/
        v = malloc(size * sizeof(double));
        if (!v) {
            fclose(f);
            marslog(LOG_EXIT, "read_vector_from_request: unable to get memory for %d elements", size);
            return MV_VECTOR_READ_ERROR;
        }

        readSize = fread(v, sizeof(double), size, f); /* read the values */

        fclose(f);

        if (readSize != size) {
            free(v);
            marslog(LOG_EXIT, "read_vector_from_request: tried to write %d elements - managed %d.", size, readSize);
            return MV_VECTOR_READ_ERROR;
        }

        *vec = v;
        *length = size;
    }
    return MV_VECTOR_READ_OK;
}
