#import <appkit/appkit.h>
#import "STDefines.h"

BOOL truthValue(const char *str)
{	if (!str) return NO;
	switch (str[0]|32) {
	case '1': case 'a': case 't': case 'y': return YES;
	default: return NO;
	}
}

const char *getDefaultWithErrorCheck(const char *defname)
{
register const char *a=[NXApp appName];
const char *p;
	p=(char *)NXGetDefaultValue(a,defname);
	if(!p)
		{ NXRunAlertPanel("Internal Error",
		   "%s default undefined",
		    NULL,NULL,NULL,defname);
		}
	return p;
}

BOOL BoolValueForDefault(const char *defname)
{
const char *p=getDefaultWithErrorCheck(defname);
	return truthValue(p);
}

int IntValueForDefault(const char *defname)
{
const char *p=getDefaultWithErrorCheck(defname);
	return atoi(p);
}

BOOL makepath(char *parent,char *child, BOOL cleanFlag)
{
char *p1, buf[BUFSIZE];
	if(!child) return NO;
	if(parent) 
	  { if(mkdir(parent,0700)<0 && errno!=EEXIST) goto FAILED;
	    sprintf(buf,"%s/%s",parent,child);
	  }
	else strcpy(buf, child);
	p1=strstr(buf,child);
	for(;;)
	 { p1=strchr(p1,'/');
	   if(p1) p1[0]='\0';
	   if(mkdir(buf,0700)<0 && errno!=EEXIST) goto FAILED;
	   if(!p1) goto CLEAR_LABEL;
	   p1[0]='/';
	   p1++;
	 }
FAILED:
    return NO;

CLEAR_LABEL:
	if(cleanFlag)
	 { sprintf(buf,
	      "exec /bin/rm -rf %s/%s/*",parent,child);
	   if (chdir(NXHomeDirectory())>=0)
	          system(buf);
	 }   
	return YES;
}

NXScreen *getScreenOfNumber(int screenNum)
{
int i,count;
NXScreen *list;
	[NXApp getScreens:&list count:&count];
	
	for(i=0;i<count;i++)
	 { if(list[i].screenNumber==screenNum) 
	       return &list[i];
	 }
	return NULL;
}


void internalError(const char *message)
{	NXRunAlertPanel("Internal Error","%s",NULL,NULL,NULL,message);
}

BOOL extCheck(const char *path, const char *extension)
{	
int len, pathLen;
	if(!path || !extension) return NO;
	len=strlen(extension);
	pathLen=strlen(path);
	return ((path[pathLen-len-1]=='.') &&
	        (strcmp((char *)(path+(pathLen-len)),extension)==0));
}

NSString *insertExt(NSString *path, const char *extension)
{	
char name[1024]="";
const char *p=[path cString];
NSString *newStr;

	if(!p)
	 {	fprintf(stderr,"bad path in insertExt\n");
	    return nil;
	 }
	strcpy(name,p);
	if(!extCheck(name,extension))
     { int len=strlen(name);
	   if(name[len-1]!='.') strcat((char *)name,".");
	   strcat((char *)name,extension);
	 }
	//[path release];
	newStr=[NSString stringWithCString:name];
	return newStr;
}

void NXGets(NXStream *st, char *buf, int maxSize)
{
register int i;
	for(i=0;i<maxSize;i++)
	 {	buf[i]=NXGetc(st);
	    if(buf[i]=='\n')
		 {	if(buf[i-1]=='"') buf[i-1]='\0';
		    buf[i]='\0';
		    break;
		 }
	 }
}

