-
Notifications
You must be signed in to change notification settings - Fork 37
/
rftles.c
129 lines (96 loc) · 2.93 KB
/
rftles.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "rftles.h"
#include "satutl.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
tle_array_t *load_tles(char *tlefile) {
tle_array_t *tle_array;
tle_array = (tle_array_t *)malloc(sizeof(tle_array_t));
if (tle_array == NULL) {
return NULL;
}
tle_array->tles = NULL;
tle_array->number_of_elements = 0;
char filename[1024];
if (tlefile) {
strncpy(filename, tlefile, sizeof(filename));
} else {
char * env = getenv("ST_TLEDIR");
if (env == NULL || strlen(env) == 0) {
env=".";
}
sprintf(filename, "%s/bulk.tle", env);
}
FILE * file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "TLE file %s not found\n", filename);
return tle_array;
}
size_t linesize = 256;
char * line = malloc(linesize);
ssize_t read;
// Count number of entries
long num_elements = 0;
while ((read = getline(&line, &linesize, file)) != -1) {
if (read > 0 && strncmp(line, "1 ", 2) == 0) {
num_elements++;
}
}
// Don't allocate anything if no entry found in file
if (num_elements == 0) {
fclose(file);
free(line);
return tle_array;
}
tle_array->tles = (tle_t *)calloc(num_elements, sizeof(tle_t));
if (tle_array->tles == NULL) {
fclose(file);
free(line);
free(tle_array);
return NULL;
}
// Rewind and parse file
rewind(file);
char satname[linesize];
while (read_twoline(file, 0, &(tle_array->tles[tle_array->number_of_elements].orbit), satname) == 0) {
if (satname[0] != '\0') {
int satname_len = strlen(satname) + 1;
tle_array->tles[tle_array->number_of_elements].name = malloc(satname_len);
strncpy(tle_array->tles[tle_array->number_of_elements].name, satname, satname_len);
} else {
tle_array->tles[tle_array->number_of_elements].name = NULL;
}
tle_array->number_of_elements++;
}
free(line);
fclose(file);
printf("Loaded %ld orbits\n", tle_array->number_of_elements);
return tle_array;
}
void free_tles(tle_array_t *tle_array) {
if (tle_array) {
for (long i = 0; i < tle_array->number_of_elements; i++) {
if (tle_array->tles[i].name != NULL) {
free(tle_array->tles[i].name);
}
}
free(tle_array->tles);
free(tle_array);
}
}
tle_t *get_tle_by_index(tle_array_t *tle_array, long index) {
if (tle_array && (index < tle_array->number_of_elements)) {
return &(tle_array->tles[index]);
}
return NULL;
}
tle_t *get_tle_by_catalog_id(tle_array_t *tle_array, long satno) {
if (tle_array) {
for (long i = 0; i < tle_array->number_of_elements; i++) {
if (tle_array->tles[i].orbit.satno == satno) {
return &(tle_array->tles[i]);
}
}
}
return NULL;
}