/***************************** 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, i;
    const char* c;
    const char* path;
    double* v;
    char buf[20] = "";
    FILE* f;
    int read;

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

    f = fopen(path, "r");

    if (!f) {
        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")) {
            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)) /* we only allow this for now */
        {
            marslog(LOG_EXIT, "read_vector_from_request: only allow float64 values just now. Is: '%s'", buf);
            return MV_VECTOR_READ_ERROR;
        }


        read = 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) {
            marslog(LOG_EXIT, "read_vector_from_request: unable to get memory for %d elements", size);
            return MV_VECTOR_READ_ERROR;
        }

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

        fclose(f);

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

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

