/* * cache.c * * Save the reflection datablock to save having to recalculate it * * (c) 2007 Gordon Ball * Thomas White * * dtr - Diffraction Tomography Reconstruction * */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include "reflections.h" #include "cache.h" typedef struct struct_cacheheader { char top[16]; int count; double scale; } CacheHeader; ReflectionContext *cache_load(const char *filename) { FILE *f; CacheHeader ch; ReflectionContext *rctx; size_t cachedreflection_size; int i; cachedreflection_size = sizeof(Reflection) - sizeof(Reflection *); rctx = reflection_init(); f = fopen(filename, "rb"); if ( !f ) { fprintf(stderr, "Couldn't read reflections from cache\n"); } if ( fread(&ch, sizeof(CacheHeader), 1, f) == 0 ) { fprintf(stderr, "Couldn't read reflections from cache\n"); fclose(f); return NULL; } for ( i=0; inext = 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 *input_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; char *cache_filename; cache_filename = malloc(strlen(input_filename)+7); strcpy(cache_filename, input_filename); strcat(cache_filename, ".cache"); printf("Caching reflections to %s\n", cache_filename); cachedreflection_size = sizeof(Reflection) - sizeof(Reflection *); count = 0; r = rctx->reflections; while ( r != NULL ) { count++; r = r->next; }; f = fopen(cache_filename, "wb"); free(cache_filename); if ( f == NULL ) { printf("Couldn't save reflection cache\n"); return -1; } 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; }