+static char* getTempDir()
+{
+#ifdef WIN32
+ char*dir = getenv("TMP");
+ if(!dir) dir = getenv("TEMP");
+ if(!dir) dir = getenv("tmp");
+ if(!dir) dir = getenv("temp");
+ if(!dir) dir = "C:\\";
+#else
+ char* dir = "/tmp/";
+#endif
+ return dir;
+}
+
+char* mktempname(char*ptr) {
+ static char tmpbuf[128];
+ char*dir = getTempDir();
+ int l = strlen(dir);
+ char*sep = "";
+ if(!ptr)
+ ptr = tmpbuf;
+ if(l && dir[l-1]!='/' && dir[l-1]!='\\') {
+#ifdef WIN32
+ sep = "\\";
+#else
+ sep = "/";
+#endif
+ }
+
+ // used to be mktemp. This does remove the warnings, but
+ // It's not exactly an improvement.
+#ifdef HAVE_LRAND48
+ sprintf(ptr, "%s%s%08x%08x",dir,sep,lrand48(),lrand48());
+#else
+# ifdef HAVE_RAND
+ sprintf(ptr, "%s%s%08x%08x",dir,sep,rand(),rand());
+# else
+ static int count = 1;
+ sprintf(ptr, "%s%s%08x%04x%04x",dir,sep,time(0),(unsigned int)tmpbuf^((unsigned int)tmpbuf)>>16,count);
+ count ++;
+# endif
+#endif
+ return ptr;
+}
+
+memfile_t* memfile_open(const char*path)
+{
+ memfile_t*file = malloc(sizeof(memfile_t));
+#if defined(HAVE_MMAP) && defined(HAVE_STAT)
+ int fi = open(path, O_RDONLY);
+ if(fi<0) {
+ perror(path);
+ free(file);
+ return 0;
+ }
+ struct stat sb;
+ if(fstat(fi, &sb)<0) {
+ perror(path);
+ return 0;
+ }
+ file->len = sb.st_size;
+ file->data = mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, fi, 0);
+#else
+ FILE*fi = fopen(path, "rb");
+ if(!fi) {
+ perror(path);
+ free(file);
+ return 0;
+ }
+ fseek(fi, 0, SEEK_END);
+ file->len = ftell(fi);
+ fseek(fi, 0, SEEK_SET);
+ file->data = malloc(file->len);
+ if(!file->data) {
+ fprintf(stderr, "Out of memory while allocating memory for file %s\n", path);
+ free(file);
+ return 0;
+ }
+ fread(file->data, file->len, 1, fi);
+ fclose(fi);
+#endif
+ return file;
+}
+
+void memfile_close(memfile_t*file)
+{
+#if defined(HAVE_MMAP) && defined(HAVE_STAT)
+ munmap(file->data, file->len);
+#else
+ free(file->data);
+#endif
+ file->data = file->len = 0;
+ free(file);
+}
+