rebound-bind 5.0.0

Low-level Rust FFI bindings for the REBOUND N-body simulation C library.
Documentation
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/**
 * @file 	simulationarchive.c
 * @brief 	Tools for creating and reading Simulationarchive binary files.
 * @author 	Hanno Rein <hanno@hanno-rein.de>
 * 
 * @section 	LICENSE
 * Copyright (c) 2016 Hanno Rein
 *
 * This file is part of rebound.
 *
 * rebound is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * rebound is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with rebound.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <inttypes.h>
#include <stdint.h>
#include "rebound.h"
#include "rebound_internal.h"
#include "particle.h"
#include "fmemopen.h"
#include "binarydata.h"
#include "output.h"
#include "tools.h"
#include "output.h"
#include "simulationarchive.h"
#include "simulation.h"
#ifdef MPI
#include "communication_mpi.h"
#endif


void reb_simulation_init_from_simulationarchive_with_messages(struct reb_simulation* r, struct reb_simulationarchive* sa, int64_t snapshot, enum REB_BINARYDATA_ERROR_CODE* warnings){
    FILE* inf = sa->inf;
    if (inf == NULL){
        *warnings |= REB_BINARYDATA_ERROR_FILENOTOPEN;
        return;
    }
    if (snapshot<0) snapshot += sa->nblobs;
    if (snapshot>=sa->nblobs || snapshot<0){
        *warnings |= REB_BINARYDATA_ERROR_OUTOFRANGE;
        return;
    }

    // load original binary file
#ifdef MPI
    reb_communication_mpi_init(r, 0, NULL);
#endif //MPI
    r->simulationarchive_filename = NULL;

    fseek(inf, 0, SEEK_SET);
    reb_binarydata_input_fields(r, inf, warnings);

    // Done?
    if (snapshot==0) return;

    // Read SA snapshot
    if(fseek(inf, sa->offset[snapshot], SEEK_SET)){
        *warnings |= REB_BINARYDATA_ERROR_SEEK;
        //reb_simulation_free(r);
        return;
    }
    if (r->simulationarchive_version<5){ 
        *warnings |= REB_BINARYDATA_ERROR_OLD;
        //reb_simulation_free(r);
        return;
    }else{
        // Version 2 or higher
        reb_binarydata_input_fields(r, inf, warnings);
    }
    return;
}

struct reb_simulation* reb_simulation_create_from_simulationarchive(struct reb_simulationarchive* sa, int64_t snapshot){
    if (sa==NULL) return NULL;
    enum REB_BINARYDATA_ERROR_CODE warnings = REB_BINARYDATA_WARNING_NONE;
    struct reb_simulation* r = reb_simulation_create();
    reb_simulation_init_from_simulationarchive_with_messages(r, sa, snapshot, &warnings);
    r = reb_binarydata_process_warnings(r, warnings);
    return r; // might be null if error occurred
}

struct reb_simulation* reb_simulation_create_from_file(char* filename, int64_t snapshot){
    enum REB_BINARYDATA_ERROR_CODE warnings = REB_BINARYDATA_WARNING_NONE;
    struct reb_simulation* r = reb_simulation_create();

    struct reb_simulationarchive* sa = reb_simulationarchive_create_from_file_with_messages(filename, &warnings);
    if (warnings & REB_BINARYDATA_ERROR_NOFILE){
        // Don't output an error if file does not exist, just return NULL.
        free(sa);
        return NULL;
    }else{
        reb_binarydata_process_warnings(NULL, warnings);
    }
    reb_simulation_init_from_simulationarchive_with_messages(r, sa, snapshot, &warnings);
    if (sa){
        reb_simulationarchive_free(sa);
    }
    r = reb_binarydata_process_warnings(r, warnings);
    return r;
}

void reb_simulationarchive_read_from_stream_with_messages(struct reb_simulationarchive* sa, enum REB_BINARYDATA_ERROR_CODE* warnings){
    // Assumes sa->inf is set to an open stream
    if (sa->inf==NULL){
        *warnings |= REB_BINARYDATA_ERROR_NOFILE;
        return;
    }

    // Get version
    fseek(sa->inf, 0, SEEK_SET);  
    struct reb_binarydata_field field = {0};
    sa->version = 0;
    double t0 = 0;
    sa->reb_version_major = 0;
    sa->reb_version_minor = 0;
    sa->reb_version_patch = 0;

    char name[REB_STRING_SIZE_MAX] = "";
    do{
        int didReadField = (int)fread(&field,sizeof(struct reb_binarydata_field),1,sa->inf);
        if (!didReadField){
            *warnings |= REB_BINARYDATA_WARNING_CORRUPTFILE;
            break;
        }

        if (field.size_name == reb_binarydata_header){
            int64_t objects = 0;
            // Input header.
            const int64_t bufsize = 64 - sizeof(struct reb_binarydata_field);
            char readbuf[64], curvbuf[64];
            const char* header = "REBOUND Binary File. Version: ";
            sprintf(curvbuf,"%s%s",header+sizeof(struct reb_binarydata_field), reb_version_str);

            objects += fread(readbuf,sizeof(char),bufsize,sa->inf);
            // Finding version_major/version_minor version
            int c1=0, c2=0, c3=0; 
            for (int c=0; c<bufsize; c++){
                if (c2 != 0 && c3 == 0 && readbuf[c] == '.'){
                    c3 = c;
                }
                if (c1 != 0 && c2 == 0 && readbuf[c] == '.'){
                    c2 = c;
                }
                if (c1 == 0 && readbuf[c] == ':'){
                    c1 = c;
                }
            }
            if (c1==0 || c2==0 || c3==0){
                *warnings |= REB_BINARYDATA_WARNING_CORRUPTFILE;
            }else{
                char cpatch[64];
                char cminor[64];
                char cmajor[64];
                strncpy(cpatch, readbuf+c3+1, 3);
                cminor[4] = '\0';
                strncpy(cminor, readbuf+c2+1, c3-c2-1);
                cminor[c3-c2-1] = '\0';
                strncpy(cmajor, readbuf+c1+1, c2-c1-1);
                cmajor[c2-c1-1] = '\0';
                sa->reb_version_patch = atoi(cpatch);
                sa->reb_version_minor = atoi(cminor);
                sa->reb_version_major = atoi(cmajor);
            }
            if (objects < 1){
                *warnings |= REB_BINARYDATA_WARNING_CORRUPTFILE;
            }else{
                // Note: following compares version, but ignores githash.
                if(strncmp(readbuf,curvbuf,bufsize)!=0){
                    *warnings |= REB_BINARYDATA_WARNING_VERSION;
                }
            }
            continue;
        }

        if (field.size_name==0 || field.size_name>REB_STRING_SIZE_MAX){
            *warnings |= REB_BINARYDATA_WARNING_CORRUPTFILE;
            break;
        }

        didReadField = (int)fread(name,field.size_name,1,sa->inf);
        if (!didReadField){
            *warnings |= REB_BINARYDATA_WARNING_CORRUPTFILE;
            break;
        }

        if (strcmp(name, "t")==0){
            fread(&t0, field.size_data, 1, sa->inf);
        }else if (strcmp(name, "simulationarchive_version")==0){
            fread(&(sa->version), field.size_data, 1, sa->inf);
        }else if (strcmp(name, "simulationarchive_auto_walltime")==0){
            fread(&(sa->auto_walltime), field.size_data, 1, sa->inf);
        }else if (strcmp(name, "simulationarchive_auto_interval")==0){
            fread(&(sa->auto_interval), field.size_data, 1, sa->inf);
        }else if (strcmp(name, "simulationarchive_auto_step")==0){
            fread(&(sa->auto_step), field.size_data, 1, sa->inf);
        }else{
            fseek(sa->inf,field.size_data,SEEK_CUR);
        }
    }while(strcmp(name, "end"));

    // Make index
    if (sa->version<5){
        // No longer supported
        free(sa->filename);
        sa->filename = NULL;
        fclose(sa->inf);
        sa->inf = NULL;
        *warnings |= REB_BINARYDATA_ERROR_OLD;
        return;
    }else{
        // New version
        int64_t nblobsmax = 1024;
        sa->t = calloc(nblobsmax,sizeof(double));
        sa->offset = calloc(nblobsmax,sizeof(uint64_t));
        fseek(sa->inf, 0, SEEK_SET);  
        sa->nblobs = 0;
        int read_error = 0;
        for(int64_t i=0;i<nblobsmax;i++){
            struct reb_binarydata_field field = {0};
            sa->offset[i] = ftell(sa->inf);
            int blob_finished = 0;
            do{
                size_t r1 = fread(&field,sizeof(struct reb_binarydata_field),1,sa->inf);
                if (field.size_name == reb_binarydata_header){
                    int s1 = fseek(sa->inf,64 - sizeof(struct reb_binarydata_field),SEEK_CUR);
                    if (s1){
                        read_error = 1;
                    }
                    continue;
                }
                r1 &= (int)fread(name,field.size_name,1,sa->inf);
                if (r1==1){
                    if (strcmp(name, "t")==0){
                        size_t r2 = fread(&(sa->t[i]), field.size_data,1,sa->inf);
                        if (r2!=1){
                            read_error = 1;
                        }
                    }else if (strcmp(name, "end")==0){
                        blob_finished = 1;
                    }else{
                        int s2 = fseek(sa->inf,field.size_data,SEEK_CUR);
                        if (s2){
                            read_error = 1;
                        }
                    }
                }else{
                    read_error = 1;
                }
            }while(blob_finished==0 && read_error==0);
            if (read_error){
                // Error during reading. Current snapshot is corrupt.
                break;
            }
            // Everything looks normal so far. Attempt to read next blob
            struct reb_simulationarchive_blob blob = {0};
            size_t r3;
            r3 = fread(&blob, sizeof(struct reb_simulationarchive_blob), 1, sa->inf);
            int next_blob_is_corrupted = 0;
            if (r3!=1){ // Next snapshot is definitely corrupted.
                        // Assume we have reached the end of the file.
                        // Won't be able to do checksum.
                next_blob_is_corrupted = 1;
                *warnings |= REB_BINARYDATA_WARNING_CORRUPTFILE;
            }
            if (i>0){
                size_t blobsize;
                blobsize = sizeof(struct reb_simulationarchive_blob);
                // Checking the offsets. Acts like a checksum.
                if (((int64_t)blob.offset_prev )+ ((int64_t)blobsize) != ftell(sa->inf) - ((int64_t)sa->offset[i]) ){
                    // Offsets don't work. Next snapshot is definitely corrupted. Assume current one as well.
                    read_error = 1;
                    break;
                }
            }
            // All tests passed. Accept current snapshot. Increase blob count.
            sa->nblobs = i+1;
            if (blob.offset_next==0 || next_blob_is_corrupted){
                // Last blob. 
                break;
            }
            if (i==nblobsmax-1){ // Increase 
                nblobsmax += 1024;
                sa->t = realloc(sa->t,sizeof(double)*nblobsmax);
                sa->offset = realloc(sa->offset,sizeof(uint64_t)*nblobsmax);
            }
        }
        if (read_error){
            if (sa->nblobs>0){
                *warnings |= REB_BINARYDATA_WARNING_CORRUPTFILE;
            }else{
                fclose(sa->inf);
                sa->inf = NULL;
                free(sa->filename);
                sa->filename = NULL;
                free(sa->t);
                sa->t = NULL;
                free(sa->offset);
                sa->offset = NULL;
                free(sa);
                *warnings |= REB_BINARYDATA_ERROR_SEEK;
                return;
            }
        }
    }
}

struct reb_simulationarchive* reb_simulationarchive_create_from_file_with_messages(const char* filename,  enum REB_BINARYDATA_ERROR_CODE* warnings){
    struct reb_simulationarchive* sa = malloc(sizeof(struct reb_simulationarchive));
    // Somewhat complicated calls for backwards compatibility.
#ifdef MPI
    int initialized;
    MPI_Initialized(&initialized);
    if (!initialized){
        int argc = 0;
        char** argv = NULL;
        MPI_Init(&argc, &argv);
    }
    int mpi_id=0;
    MPI_Comm_rank(MPI_COMM_WORLD,&mpi_id);
    char filename_mpi[REB_STRING_SIZE_MAX];
    sprintf(filename_mpi,"%s_%d",filename,mpi_id);
    sa->inf = fopen(filename_mpi,"rb");
#else // MPI
    sa->inf = fopen(filename,"rb");
#endif // MPI
    sa->filename = malloc(strlen(filename)+1);
    strcpy(sa->filename,filename);
    reb_simulationarchive_read_from_stream_with_messages(sa, warnings);
    return sa;
}

struct reb_simulationarchive* reb_simulationarchive_create_from_file(const char* filename){
    enum REB_BINARYDATA_ERROR_CODE warnings = REB_BINARYDATA_WARNING_NONE;
    struct reb_simulationarchive* sa = reb_simulationarchive_create_from_file_with_messages(filename, &warnings);
    if (warnings & REB_BINARYDATA_ERROR_NOFILE){
        // Don't output an error if file does not exist, just return NULL.
        free(sa);
        sa = NULL;
    }else{
        reb_binarydata_process_warnings(NULL, warnings);
    }
    return sa;
}

struct reb_simulationarchive* reb_simulationarchive_create_from_buffer_with_messages(char* buffer, size_t size,  enum REB_BINARYDATA_ERROR_CODE* warnings){
    struct reb_simulationarchive* sa = malloc(sizeof(struct reb_simulationarchive));
    sa->inf = reb_fmemopen(buffer, size, "rb");
    sa->filename = NULL;
    reb_simulationarchive_read_from_stream_with_messages(sa, warnings);
    return sa;
}

void reb_simulationarchive_free(struct reb_simulationarchive* sa){
    if (sa==NULL) return;
    if (sa->inf){
        fclose(sa->inf);
    }
    free(sa->filename);
    free(sa->t);
    free(sa->offset);
    free(sa);
}

void reb_simulationarchive_heartbeat(struct reb_simulation* const r){
    if (r->simulationarchive_filename!=NULL){
        int modes = 0;
        if (r->simulationarchive_auto_interval!=0) modes++;
        if (r->simulationarchive_auto_walltime!=0.) modes++;
        if (r->simulationarchive_auto_step!=0) modes++;
        if (modes>1){
            reb_simulation_error(r,"Only use one of simulationarchive_auto_interval, simulationarchive_auto_walltime, or simulationarchive_auto_step");
        }
        if (r->simulationarchive_auto_interval!=0.){
            const double sign = r->dt>0.?1.:-1;
            if (sign*r->simulationarchive_next <= sign*r->t){
                r->simulationarchive_next += sign*r->simulationarchive_auto_interval;
                //Snap
                reb_simulation_save_to_file(r, NULL);
            }
        }
        if (r->simulationarchive_auto_step!=0.){
            if (r->simulationarchive_next_step <= r->steps_done){
                r->simulationarchive_next_step += r->simulationarchive_auto_step;
                //Snap
                reb_simulation_save_to_file(r, NULL);
            }
        }
        if (r->simulationarchive_auto_walltime!=0.){
            if (r->simulationarchive_next <= r->walltime){
                r->simulationarchive_next += r->simulationarchive_auto_walltime;
                //Snap
                reb_simulation_save_to_file(r, NULL);
            }
        } 
    }
}

void reb_simulation_save_to_file(struct reb_simulation* const r, const char* filename){
    if (r->simulationarchive_version<5){
        reb_simulation_error(r, "Writing Simulationarchives with a version < 5 is no longer supported.\n");
        return;
    }
    if (filename==NULL) filename = r->simulationarchive_filename;
    struct stat buffer;
#ifdef MPI
#define filename_combined filename_mpi
    char filename_mpi[REB_STRING_SIZE_MAX];
    sprintf(filename_mpi,"%s_%d",filename,r->mpi_id);
#else // MPI
#define filename_combined filename
#endif // MPI
    if (stat(filename_combined, &buffer) < 0){
        // File does not exist. Output binary.
        FILE* of = fopen(filename_combined,"wb"); 
        if (of==NULL){
            reb_simulation_error(r, "Can not open file.");
            return;
        }
        char* bufp;
        size_t sizep;
        reb_binarydata_simulation_to_stream(r, &bufp,&sizep);
        fwrite(bufp,sizep,1,of);
        free(bufp);
        fclose(of);
    }else{
        // File exists, append snapshot.
        // Create buffer containing original binary file
        FILE* of = fopen(filename_combined,"r+b");
        fseek(of, 64, SEEK_SET); // Header
        struct reb_binarydata_field field = {0};
        char name[REB_STRING_SIZE_MAX];
        struct reb_simulationarchive_blob blob = {0};
        int bytesread;
        do{
            bytesread = (int)fread(&field,sizeof(struct reb_binarydata_field),1,of);
            if (!bytesread){
                reb_simulation_warning(r, "Simulationarchive appears to be corrupted. A recovery attempt has failed. No snapshot has been saved.\n");
                return;
            }
            if (field.size_name != reb_binarydata_header && (field.size_name==0 || field.size_name>REB_STRING_SIZE_MAX)){
                reb_simulation_warning(r, "Simulationarchive appears to be corrupted. A recovery attempt has failed. No snapshot has been saved.\n");
                return;
            }
            bytesread = (int)fread(name,field.size_name,1,of);
            if (!bytesread){
                reb_simulation_warning(r, "Simulationarchive appears to be corrupted. A recovery attempt has failed. No snapshot has been saved.\n");
                return;
            }
            int seekfailed = fseek(of, field.size_data, SEEK_CUR);
            if (seekfailed){
                reb_simulation_warning(r, "Simulationarchive appears to be corrupted. A recovery attempt has failed. No snapshot has been saved.\n");
                return;
            }
        }while(strcmp(name, "end"));
        int64_t size_old = ftell(of);

        bytesread = (int)fread(&blob,sizeof(struct reb_simulationarchive_blob),1,of);
        if (bytesread!=1){
            reb_simulation_warning(r, "Simulationarchive appears to be corrupted. A recovery attempt has failed. No snapshot has been saved.\n");
            return;
        }
        int archive_contains_more_than_one_blob = 0;
        if (blob.offset_next>0){
            archive_contains_more_than_one_blob = 1;
        }


        char* buf_old = malloc(size_old);
        fseek(of, 0, SEEK_SET);  
        fread(buf_old, size_old,1,of);

        // Create buffer containing current binary file
        char* buf_new;
        size_t size_new;
        reb_binarydata_simulation_to_stream(r, &buf_new, &size_new);

        // Create buffer containing diff
        char* buf_diff;
        size_t size_diff;
        reb_binarydata_diff(buf_old, size_old, buf_new, size_new, &buf_diff, &size_diff, REB_BINARYDATA_OUTPUT_STREAM);

        // Check if file is valid.
        int file_corrupt = 0;
        int seekfailed = fseek(of, -sizeof(struct reb_simulationarchive_blob), SEEK_END);
        if (seekfailed){
            file_corrupt = 1;
            goto recovery_attempt;
        }
        bytesread = (int)fread(&blob, sizeof(struct reb_simulationarchive_blob), 1, of);
        if (!bytesread){
            file_corrupt = 1;
            goto recovery_attempt;
        }
        if ( (archive_contains_more_than_one_blob && blob.offset_prev <=0) || blob.offset_next != 0){ // blob contains unexpected data. Note: First blob is all zeros.
            file_corrupt = 1;
            goto recovery_attempt;
        }
        if (file_corrupt==0 && archive_contains_more_than_one_blob ){
            // Check if last two blobs are consistent.
            size_t end_len = strlen("end")+1;
            int seekfailed = fseek(of, - sizeof(struct reb_simulationarchive_blob) - sizeof(struct reb_binarydata_field) - end_len, SEEK_CUR);  
            if (seekfailed){
                file_corrupt = 1;
                goto recovery_attempt;
            }
            bytesread = (int)fread(&field, sizeof(struct reb_binarydata_field), 1, of);
            if (!bytesread || field.size_name == 0 || field.size_name > REB_STRING_SIZE_MAX){
                file_corrupt = 1;
                goto recovery_attempt;
            }
            bytesread = (int)fread(name, field.size_name, 1, of);
            if (!bytesread){
                file_corrupt = 1;
                goto recovery_attempt;
            }
            if (strcmp(name, "end") || field.size_data !=0){
                // expected an END field
                file_corrupt = 1;
                goto recovery_attempt;
            }
            seekfailed = fseek(of, -blob.offset_prev - sizeof(struct reb_simulationarchive_blob), SEEK_CUR);  
            if (seekfailed){
                file_corrupt = 1;
                goto recovery_attempt;
            }
            struct reb_simulationarchive_blob blob2 = {0};
            bytesread = (int)fread(&blob2, sizeof(struct reb_simulationarchive_blob), 1, of);
            if (!bytesread){
                file_corrupt = 1;
            }
        }

recovery_attempt:
        if (file_corrupt){
            // Find last valid snapshot to allow for restarting and appending to archives where last snapshot was cut off
            reb_simulation_warning(r, "Simulationarchive appears to be corrupted. REBOUND will attempt to fix it before appending more snapshots.\n");
            seekfailed = fseek(of, size_old, SEEK_SET);
            int64_t last_blob = size_old + sizeof(struct reb_simulationarchive_blob);
            do
            {
                seekfailed = fseek(of, -sizeof(struct reb_binarydata_field), SEEK_CUR);
                if (seekfailed){
                    break;
                }
                seekfailed = fseek(of, -sizeof(char)*4, SEEK_CUR); // strlen("end")
                if (seekfailed){
                    break;
                }
                bytesread = (int)fread(&field, sizeof(struct reb_binarydata_field), 1, of);
                if (field.size_name != 4){ // string can't be "end"
                    break;
                }
                if (!bytesread || field.size_name == 0 || (field.size_name > REB_STRING_SIZE_MAX && field.size_name != reb_binarydata_header)){
                    break;
                }
                bytesread = (int)fread(name, field.size_name, 1, of);
                if (!bytesread || strncmp(name, "end", 4)){ // EOF or corrupt snapshot
                    break;
                }
                bytesread = (int)fread(&blob, sizeof(struct reb_simulationarchive_blob), 1, of);
                if (!bytesread){
                    break;
                }
                last_blob = ftell(of);
                if (blob.offset_next==0){
                    break;
                }
                seekfailed = fseek(of, blob.offset_next, SEEK_CUR);
                if (seekfailed){
                    break;
                }
            } while(1);

            // To append diff, seek to last valid location (=EOF if all snapshots valid)
            fseek(of, last_blob, SEEK_SET);
        }else{
            // File is not corrupt. Start at end to save time.
            fseek(of, 0, SEEK_END);  
        }

        // Update blob info and Write diff to binary file
        fseek(of, -sizeof(struct reb_simulationarchive_blob), SEEK_CUR);  
        fread(&blob, sizeof(struct reb_simulationarchive_blob), 1, of);
        blob.offset_next = (uint64_t)(size_diff+sizeof(struct reb_binarydata_field)+strlen("end")+1);
        fseek(of, -sizeof(struct reb_simulationarchive_blob), SEEK_CUR);  
        fwrite(&blob, sizeof(struct reb_simulationarchive_blob), 1, of);
        fwrite(buf_diff, size_diff, 1, of); 
        field.size_name = strlen("end")+1;
        field.size_data = 0;
        fwrite(&field,sizeof(struct reb_binarydata_field), 1, of);
        fwrite("end",field.size_name, 1, of);
        blob.index++;
        blob.offset_prev = blob.offset_next;
        blob.offset_next = 0;
        fwrite(&blob, sizeof(struct reb_simulationarchive_blob), 1, of);

        fclose(of);
        free(buf_new);
        free(buf_old);
        free(buf_diff);
    }
}

static int check_and_set_simulationarchive_filename(struct reb_simulation* const r, const char* filename){
    if (r==NULL) return -1;
    if (filename==NULL){
        reb_simulation_error(r, "Filename missing.");
        return -1;
    }
    struct stat buffer;
#ifdef MPI
#define filename_combined filename_mpi
    char filename_mpi[REB_STRING_SIZE_MAX];
    sprintf(filename_mpi,"%s_%d",filename,r->mpi_id);
#else // MPI
#define filename_combined filename
#endif // MPI
    if (stat(filename_combined, &buffer) == 0){
        reb_simulation_warning(r, "File in use for Simulationarchive already exists. Snapshots will be appended.");
    }
    free(r->simulationarchive_filename);
    r->simulationarchive_filename = strdup(filename);
    return 0;
}

void reb_simulation_save_to_file_interval(struct reb_simulation* const r, const char* filename, double interval){
    if(check_and_set_simulationarchive_filename(r,filename)<0) return;
    if(r->simulationarchive_auto_interval != interval){
        // Only update simulationarchive_next if interval changed. 
        // This ensures that interrupted simulations will continue
        // after being restarted from a simulationarchive
        r->simulationarchive_auto_interval = interval;
        r->simulationarchive_next = r->t;
    }
}

void reb_simulation_save_to_file_walltime(struct reb_simulation* const r, const char* filename, double walltime){
    if(check_and_set_simulationarchive_filename(r,filename)<0) return;
    // Note that this will create two snapshots if restarted.
    r->simulationarchive_auto_walltime = walltime;
    r->simulationarchive_next = r->walltime;
}

void reb_simulation_save_to_file_step(struct reb_simulation* const r, const char* filename, uint64_t step){
    if(check_and_set_simulationarchive_filename(r,filename)<0) return;
    if(r->simulationarchive_auto_step != step){
        // Only update simulationarchive_next if interval changed. 
        // This ensures that interrupted simulations will continue
        // after being restarted from a simulationarchive
        r->simulationarchive_auto_step = step;
        r->simulationarchive_next_step = r->steps_done;
    }
}