#include "defines.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __BORLANDC__
#include <io.h>

#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
#ifdef _Windows
#define _WIN32
#endif
#ifdef __WIN32__
#define _WIN32
#endif
#ifdef _WIN32
#include <windows.h>
char windowsdirbuf[MAX_PATH];
char *windowsdir=(GetWindowsDirectory(windowsdirbuf,MAX_PATH)?windowsdirbuf:NULL);

#endif
#include "system.h"
int writable(char *name) {
char ch='x';
int handle=creat(name,0644);
if(handle<0)
	return 0;
if(write(handle,&ch,1)!=1)
	return 0;
close(handle);
unlink(name);
return 1;
}
extern const char *tmpdirs[];
extern const int tmpdirnr;
extern int tmpdirlens[];
#ifdef _WIN32
 const char *tmpdirs[]={getenv("TMP"),getenv("TEMP"),P_tmpdir,getenv("HOMEPATH"),windowsdir,"c:/",};
 const int tmpdirnr=(sizeof(tmpdirs)/sizeof(char*));
 int tmpdirlens[tmpdirnr]={0,0,0,0,0};
#else
 const char *tmpdirs[]={getenv("TMPDIR"),"~/tmp",P_tmpdir,"/tmp","/var/tmp","/usr/local/tmp"};
 const int tmpdirnr=(sizeof(tmpdirs)/sizeof(char*));
 int tmpdirlens[tmpdirnr]={0,0};
#endif
int namedir(char *buf,int i,const char *name) {
			const char *tmp=tmpdirs[i];
			if(tmp) {
				int len;
//#ifndef __CYGWIN__
#if 1
				expandfilename(buf,tmp);
				if(!tmpdirlens[i]) {
					tmpdirlens[i]=strlen(buf);
					}
#else
				if(!tmpdirlens[i]) {
					tmpdirlens[i]=strlen(tmp);
					}
				memmove(buf,tmp,tmpdirlens[i]);
#endif
				len=tmpdirlens[i];
				 buf[len++]=FILENAMESEP;
				strcpy(buf+len,name);
				return len;
			}
		else 
			return 0;
		}
int mytmpname(char *buf,int len,const char *name) {
	for(int i=0;i<tmpdirnr;i++) {
			if(namedir(buf, i,name) ) {
				if(mktemp(buf)&&writable(buf))
					return len;
				}
			}
	strcpy(buf,name);
	if(mktemp(buf)&&writable(buf))
		return 0;
	if(tmpnam(buf) &&writable(buf))
		return strlen(buf);
	 return -1;
	}
#ifdef TEST
void main(void) {
char buf[256];
mytmpname(buf,256,"bed-XXXXXX");
puts(buf);
}
#endif
