aboutsummaryrefslogtreecommitdiff
path: root/src/cache.c
blob: f1998b737009d1667caedbaee981744015b4681c (plain)
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
/*
 * cache.c
 *
 * Save the reflection datablock to save having to recalculate it
 *
 * (c) 2007 Gordon Ball <gfb21@cam.ac.uk>
 *	    Thomas White <taw27@cam.ac.uk>
 *
 *  dtr - Diffraction Tomography Reconstruction
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "reflections.h"
#include "cache.h"

ReflectionContext *cache_load(const char *filename) {

	FILE *f;
	CacheHeader ch;
	ReflectionContext *rctx;
	size_t cachedreflection_size;

	cachedreflection_size = sizeof(Reflection) - sizeof(Reflection *);

	rctx = reflection_init();
	f = fopen(filename, "rb");
	fread(&ch, sizeof(CacheHeader), 1, f);
	
	int i;
	for ( i=0; i<ch.count; i++ ) {
	
		Reflection *cr;
		
		cr = malloc(sizeof(Reflection));
		fread(cr, cachedreflection_size, 1, f);
		cr->next = NULL;	/* Guarantee swift failure in the event of a screw-up */
		//printf("reading (%f,%f,%f) i=%f (%d,%d,%d) %d\n",cr->x,cr->y,cr->z,cr->intensity,cr->h,cr->k,cr->l,cr->type);
		reflection_add_from_reflection(rctx, cr);
		
	}
	
	fclose(f);
	
	return rctx;
}

int cache_save(const char *filename, ReflectionContext *rctx) {

	FILE *f;
	CacheHeader ch;
	Reflection *r;
	int count;
	const char top[16] = "DTRCACHE\0\0\0\0\0\0\0\0";
	size_t cachedreflection_size;

	cachedreflection_size = sizeof(Reflection) - sizeof(Reflection *);
	
	count = 0;
	r = rctx->reflections;
	while ( r != NULL ) {
		count++;
		r = r->next;
	};
	
	f = fopen(filename, "wb");
	memcpy(&ch.top, &top, sizeof(top));
	ch.count = count;
	ch.scale = 0.; //temp, currently doesn't do anything
	fwrite(&ch, sizeof(CacheHeader), 1, f);
	
	r = rctx->reflections;
	while ( r != NULL ) {
		
		fwrite(r, cachedreflection_size, 1, f);	/* Write the reflection block, stopping just short of the "next" pointer */
		r = r->next;
		
	};
	
	fclose(f);
	
	return 0;
	
}

unsigned int cache_is_cachefile(const char *filename) {

	FILE *fh;
	CacheHeader ch;
	size_t nread;

	fh = fopen(filename, "rb");
	nread = fread(&ch, sizeof(CacheHeader), 1, fh);
	fclose(fh);

	if ( nread != 1 ) {
		return 0;
	}
	
	if ( strncmp(ch.top, "DTRCACHE", 8) == 0 ) {
		return 1;
	}
	
	/* Backwards compatability */
	if ( strncmp(ch.top, "DTR-CACHE", 9) == 0 ) {
		return 1;
	}
	
	return 0;

}