1 /*
2 * Copyright (c) 2014-2021, The OSKAR Developers.
3 * See the LICENSE file at the top-level directory of this distribution.
4 */
5
6 #include "telescope/station/oskar_station.h"
7
8 #include "utility/oskar_getline.h"
9 #include "utility/oskar_string_to_array.h"
10
11 #include <stdio.h>
12 #include <stdlib.h>
13
14 #ifdef __cplusplus
15 extern "C" {
16 #endif
17
oskar_station_load_element_types(oskar_Station * station,const char * filename,int * status)18 void oskar_station_load_element_types(oskar_Station* station,
19 const char* filename, int* status)
20 {
21 /* Declare the line buffer and counter. */
22 char* line = 0;
23 size_t bufsize = 0;
24 int n = 0, type = 0, old_size = 0;
25 FILE* file = 0;
26 if (*status || !station) return;
27
28 /* Check type. */
29 type = oskar_station_precision(station);
30 if (type != OSKAR_SINGLE && type != OSKAR_DOUBLE)
31 {
32 *status = OSKAR_ERR_BAD_DATA_TYPE;
33 return;
34 }
35
36 /* Open the file. */
37 file = fopen(filename, "r");
38 if (!file)
39 {
40 *status = OSKAR_ERR_FILE_IO;
41 return;
42 }
43
44 /* Get the size of the station before loading the data. */
45 old_size = oskar_station_num_elements(station);
46
47 /* Loop over each line in the file. */
48 while (oskar_getline(&line, &bufsize, file) != OSKAR_ERR_EOF)
49 {
50 int par = 0;
51
52 /* Load element data. */
53 if (oskar_string_to_array_i(line, 1, &par) < 1) continue;
54
55 /* Ensure the station model is big enough. */
56 if (oskar_station_num_elements(station) <= n)
57 {
58 oskar_station_resize(station, n + 256, status);
59 if (*status) break;
60 }
61
62 /* Store the data. */
63 oskar_station_set_element_type(station, n, par, status);
64
65 /* Increment element counter. */
66 ++n;
67 }
68
69 /* Consistency check with previous station size (should be the same as
70 * the number of elements loaded). */
71 if (!*status && n != old_size)
72 {
73 *status = OSKAR_ERR_DIMENSION_MISMATCH;
74 }
75
76 /* Free the line buffer and close the file. */
77 if (line) free(line);
78 fclose(file);
79 }
80
81 #ifdef __cplusplus
82 }
83 #endif
84