1 /*
2 * Copyright (c) 2011-2021, The OSKAR Developers.
3 * See the LICENSE file at the top-level directory of this distribution.
4 */
5
6 #include "sky/oskar_sky.h"
7 #include "utility/oskar_getline.h"
8
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 #ifdef __cplusplus
13 extern "C" {
14 #endif
15
oskar_sky_load(const char * filename,int type,int * status)16 oskar_Sky* oskar_sky_load(const char* filename, int type, int* status)
17 {
18 int n = 0;
19 FILE* file = 0;
20 char* line = 0;
21 size_t bufsize = 0;
22 oskar_Sky* sky = 0;
23 if (*status) return 0;
24
25 /* Get the data type. */
26 if (type != OSKAR_SINGLE && type != OSKAR_DOUBLE)
27 {
28 *status = OSKAR_ERR_BAD_DATA_TYPE;
29 return 0;
30 }
31
32 /* Open the file. */
33 file = fopen(filename, "r");
34 if (!file)
35 {
36 *status = OSKAR_ERR_FILE_IO;
37 return 0;
38 }
39
40 /* Initialise the sky model. */
41 sky = oskar_sky_create(type, OSKAR_CPU, 0, status);
42
43 /* Loop over lines in file. */
44 while (oskar_getline(&line, &bufsize, file) != OSKAR_ERR_EOF)
45 {
46 int str_error = 0;
47
48 /* Ensure enough space in arrays. */
49 if (oskar_sky_num_sources(sky) <= n)
50 {
51 const int new_size = ((2 * n) < 100) ? 100 : (2 * n);
52 oskar_sky_resize(sky, new_size, status);
53 if (*status) break;
54 }
55
56 /* Try to set source data from the string. */
57 oskar_sky_set_source_str(sky, n, line, &str_error);
58
59 /* Increment source count only if successful. */
60 if (!str_error) n++;
61 }
62
63 /* Set the size to be the actual number of elements loaded. */
64 oskar_sky_resize(sky, n, status);
65
66 /* Free the line buffer and close the file. */
67 free(line);
68 fclose(file);
69
70 /* Check if an error occurred. */
71 if (*status)
72 {
73 oskar_sky_free(sky, status);
74 sky = 0;
75 }
76
77 /* Return a handle to the sky model. */
78 return sky;
79 }
80
81 #ifdef __cplusplus
82 }
83 #endif
84