#import "Global.h"
#import <appkit/PrintInfo.h>

#define CHUNK 127

extern void getAppDirectory (char *appDirectory)
{
    FILE *process;
    char command[256];
    char *suffix;

    strcpy (appDirectory,NXArgv[0]);
    if (appDirectory[0] == '/') { 		/* if absolute path */
        if (suffix = rindex(appDirectory,'/')) 
            *suffix  = '\0'; 			/* remove executable name */
    } else {
		sprintf(command,"which '%s'\n",NXArgv[0]);
		process=popen(command,"r");
		fscanf(process,"%s",appDirectory);
		pclose(process);
		if (suffix = rindex(appDirectory,'/')) 
			*suffix  = '\0'; 			/* remove executable name */
		chdir(appDirectory);
		getwd(appDirectory);
    }  
#ifdef DEBUG
	printf("%s\n",appDirectory);
#endif
}

char *stripnl(char *s)
{
    char *p;
    for (p=s;*p;p++) if (*p == '\n' || *p == '\r') *p = '\0';
    return s;
}

char *execstr(char *s)
/* Executes the passed string and returns a string value in that pointer */
/* Stolen from Opener 3.0 */
{
    FILE *f = popen(s,"r");
    char *p = s;
    *s = '\0';
    if (f){
        while (fgets(p,256,f))
            stripnl(p), p += strlen(p);
        pclose(f);
    }
    return s;
}

/* Functions for creating and managing a dynamically-allocated fileList */
/* - really just a list of strings.  They seem to be somewhat useful.   */

char **addFile(const char *file, char **list, int count, NXZone *zone)
/* Adds the specified filename to the list of filenames.  It allocates 
 * more memory in chunks as needed.
 */
{	
    if (!list) list = (char **)NXZoneMalloc(zone,CHUNK*sizeof(char *));
    list[count] = (char *)NXZoneMalloc(zone,(strlen(file)+1)*sizeof(char));
    strcpy(list[count], file);
    count++;
    if (!(count% CHUNK)) {
		list = (char **)NXZoneRealloc(zone,list,(((count/CHUNK)+1)*CHUNK)*sizeof(char *));
    }
    list[count] = NULL;
    return list;
}

void freeList(char **list)
/* Frees the array of filenames */
 {
    char **strings;

    if (list) {
		strings = list;
		while (*strings) NX_FREE(*strings++);
		NX_FREE(list);
    }
}


NXRect *calcFrame(id printInfo, NXRect *viewRect)
/*
 * Calculates the size of the page the user has chosen minus its margins.
 */
{
    float lm, rm, bm, tm;
    const NXRect *paperRect;

    viewRect->origin.x = viewRect->origin.y = 0.0;
    paperRect = [printInfo paperRect];
    [printInfo getMarginLeft:&lm right:&rm top:&tm bottom:&bm];
    viewRect->size = paperRect->size;
    viewRect->size.width -= lm + rm;
    viewRect->size.height -= tm + bm;

    return viewRect;
}
