/* Copyright (C) 1992, 1993 Aladdin Enterprises.  All rights reserved.

This file is part of Ghostscript.

Ghostscript is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility
to anyone for the consequences of using it or for whether it serves any
particular purpose or works at all, unless he says so in writing.  Refer
to the Ghostscript General Public License for full details.

Everyone is granted permission to copy, modify and redistribute
Ghostscript, but only under the conditions described in the Ghostscript
General Public License.  A copy of this license is supposed to have been
given to you along with Ghostscript so you can know your rights and
responsibilities.  It should be in a file named COPYING.  Among other
things, the copyright notice and this notice must be preserved on all
copies.  */

/* gp_os2.c */
/* Common platform-specific routines for OS/2 and MS-DOS */
/* compiled with GCC/EMX */

#define INCL_DOS
#include <os2.h>

#include "stdio_.h"
#include <fcntl.h>

#include <dos.h>
/* Define the regs union tag for short registers. */
#  define rshort x
#define TRUE 1
#define FALSE 0
#define intdos(a,b) _int86(0x21, a, b)

#include "memory_.h"
#include "string_.h"
/* #include "gstypes.h"	/* is this needed */
#include "gx.h"
#include "gp.h"
#include "gsutil.h"
#include "stdlib.h"	/* need _osmode */
#include "time_.h"
#include "gdevpm.h"
#include <sys/emxload.h>

/* use Unix version for date and time */
/* ------ Date and time ------ */

/* Read the current date (in days since Jan. 1, 1980) */
/* and time (in milliseconds since midnight). */
void
gp_get_clock(long *pdt)
{	long secs_since_1980;
	struct timeval tp;
	struct timezone tzp;
	time_t tsec;
	struct tm *tm, *localtime();

	if ( gettimeofday(&tp, &tzp) == -1 )
	   {	lprintf("Ghostscript: gettimeofday failed!\n");
		gs_exit(1);
	   }

	/* tp.tv_sec is #secs since Jan 1, 1970 */

	/* subtract off number of seconds in 10 years */
	/* leap seconds are not accounted for */
	secs_since_1980 = tp.tv_sec - (long)(60 * 60 * 24 * 365.25 * 10);
 
	/* adjust for timezone */
	secs_since_1980 -= (tzp.tz_minuteswest * 60);

	/* adjust for daylight savings time - assume dst offset is 1 hour */
	tsec = tp.tv_sec;
	tm = localtime(&tsec);
	if ( tm->tm_isdst )
		secs_since_1980 += (60 * 60);

	/* divide secs by #secs/day to get #days (integer division truncates) */
	pdt[0] = secs_since_1980 / (60 * 60 * 24);
	/* modulo + microsecs/1000 gives number of millisecs since midnight */
	pdt[1] = (secs_since_1980 % (60 * 60 * 24)) * 1000 + tp.tv_usec / 1000;
#ifdef DEBUG_CLOCK
	printf("tp.tv_sec = %d  tp.tv_usec = %d  pdt[0] = %ld  pdt[1] = %ld\n",
		tp.tv_sec, tp.tv_usec, pdt[0], pdt[1]);
#endif
}


/* ------ Console management ------ */

/* Answer whether a given file is the console (input or output). */
/* This is not a standard gp procedure, */
/* but the MS Windows configuration needs it, */
/* and other MS-DOS configurations might need it someday. */
/* Don't know if it is neede for OS/2 */
int
gp_file_is_console(FILE *f)
{
    if (_osmode == DOS_MODE) {
	union REGS regs;
	if ( f == NULL )
		return 0;
	regs.h.ah = 0x44;	/* ioctl */
	regs.h.al = 0;		/* get device info */
	regs.rshort.bx = fileno(f);
	intdos(&regs, &regs);
	return ((regs.h.dl & 0x80) != 0 && (regs.h.dl & 3) != 0);
    }
    if ( (f==stdin) || (f==stdout) || (f==stderr) )
	return TRUE;
    return FALSE;
}

/* ------ File names ------ */

/* Define the character used for separating file names in a list. */
const char gp_file_name_list_separator = ';';

/* Define the default scratch file name prefix. */
const char gp_scratch_file_name_prefix[] = "gs";

/* Define the string to be concatenated with the file mode */
/* for opening files without end-of-line conversion. */
const char gp_fmode_binary_suffix[] = "b";
/* Define the file modes for binary reading or writing. */
const char gp_fmode_rb[] = "rb";
const char gp_fmode_wb[] = "wb";

/* Answer whether a file name contains a directory/device specification, */
/* i.e. is absolute (not directory- or device-relative). */
int
gp_file_name_is_absolute(const char *fname, uint len)
{	/* A file name is absolute if it contains a drive specification */
	/* (second character is a :) or if it start with / or \. */
	return ( len >= 1 && (*fname == '/' || *fname == '\\' ||
		(len >= 2 && fname[1] == ':')) );
}

/* Answer the string to be used for combining a directory/device prefix */
/* with a base file name.  The file name is known to not be absolute. */
const char *
gp_file_name_concat_string(const char *prefix, uint plen,
  const char *fname, uint len)
{	if ( plen > 0 )
	  switch ( prefix[plen - 1] )
	   {	case ':': case '/': case '\\': return "";
	   };
	return "\\";
}


/* ------ File enumeration ------ */


struct file_enum_s {
	FILEFINDBUF3 findbuf;
	HDIR hdir;
	char *pattern;
	int first_time;
	const gs_memory_procs *mprocs;
};

/* Initialize an enumeration.  may NEED WORK ON HANDLING * ? \. */
file_enum *
gp_enumerate_files_init(const char *pat, uint patlen,
  const gs_memory_procs *mprocs)
{	file_enum *pfen = (file_enum *)(*mprocs->alloc)(1, sizeof(file_enum), "gp_enumerate_files");
	char *pattern;
	if ( pfen == 0 ) return 0;
	pattern = (*mprocs->alloc)(patlen + 1, 1,
			    "gp_enumerate_files(pattern)");
	if ( pattern == 0 ) return 0;
	memcpy(pattern, pat, patlen);
	pattern[patlen] = 0;
	pfen->pattern = pattern;
	pfen->mprocs = mprocs;
	pfen->first_time = 1;
	pfen->hdir = HDIR_CREATE;
	return pfen;
}

/* Enumerate the next file. */
uint
gp_enumerate_files_next(file_enum *pfen, char *ptr, uint maxlen)
{
    APIRET rc;
    ULONG cFilenames = 1;
    if (_osmode == DOS_MODE) {
	/* CAN'T DO IT SO JUST RETURN THE PATTERN. */
	if ( pfen->first_time )
	{	char *pattern = pfen->pattern;
		uint len = strlen(pattern);
		pfen->first_time = 0;
		if ( len > maxlen )
			return maxlen + 1;
		strcpy(ptr, pattern);
		return len;
	}
	return -1;
    }

    /* else OS/2 */
    if ( pfen->first_time ) {
	rc = DosFindFirst(pfen->pattern, &pfen->hdir, FILE_NORMAL,
		&pfen->findbuf, sizeof(pfen->findbuf), 
		&cFilenames, FIL_STANDARD);
	pfen->first_time = 0;
    }
    else {
	rc = DosFindNext(pfen->hdir, &pfen->findbuf, sizeof(pfen->findbuf),
		&cFilenames);
    }
    if (rc)
	return -1;
    
    if (pfen->findbuf.cchName < maxlen) {
	strcpy(ptr, pfen->findbuf.achName);
	return pfen->findbuf.cchName;
    }

    strncpy(ptr, pfen->findbuf.achName, maxlen);
    return maxlen+1;

}

/* Clean up the file enumeration. */
void
gp_enumerate_files_close(file_enum *pfen)
{	const gs_memory_procs *mprocs = pfen->mprocs;
	if (_osmode == OS2_MODE)
		DosFindClose(pfen->hdir);
	(*mprocs->free)(pfen->pattern, strlen(pfen->pattern) + 1, 1,
			"gp_enumerate_files_close(pattern)");
	(*mprocs->free)((char *)pfen, 1, sizeof(file_enum),
			"gp_enumerate_files_close");
}

/*************************************************************/
/* from gp_iwatc.c and gp_itbc.c */

/* Intel processor, EMX/GCC specific routines for Ghostscript */
#include <signal.h>
#include "stat_.h"
#include "string_.h"

/* Library routines not declared in a standard header */
extern char *getenv(P1(const char *));

/* Forward declarations */
private void handle_FPE(P1(int));

/* Do platform-dependent initialization. */
void
gp_init(void)
{
	/* keep gsos2.exe in memory for number of minutes specified in */
	/* environment variable GS_LOAD */
	_emxload_env("GS_LOAD");
	/* Set up the handler for numeric exceptions. */
	signal(SIGFPE, handle_FPE);
	gp_init_console();
	fprintf(stderr,"See README.OS2 for details about this version of Ghostscript\n");
}


/* Trap numeric exceptions.  Someday we will do something */
/* more appropriate with these. */
private void
handle_FPE(int sig)
{	eprintf("Numeric exception:\n");
	exit(1);
}

extern int gs_exit_status;
/* Do platform-dependent cleanup. */
void
gp_exit(int exit_status, int code)
{
}

/* ------ Printer accessing ------ */

/* Open a connection to a printer.  A null file name means use the */
/* standard printer connected to the machine, if any. */
/* "|command" opens an output pipe. */
/* Return NULL if the connection could not be opened. */
FILE *
gp_open_printer(char *fname, int binary_mode)
{	if ( strlen(fname) == 0 ) 
		return fopen("PRN", (binary_mode ? "wb" : "w"));
	else if (fname[0] == '|')
		return popen(fname+1, (binary_mode ? "wb" : "w"));
	else
		return fopen(fname, (binary_mode ? "wb" : "w"));
}

/* Close the connection to the printer. */
void
gp_close_printer(FILE *pfile, const char *fname)
{	if ( fname[0] == '|' )
		pclose(pfile);
	else
		fclose(pfile);
}


/* ------ File names ------ */

/* Create and open a scratch file with a given name prefix. */
/* Write the actual file name at fname. */
FILE *
gp_open_scratch_file(const char *prefix, char *fname, const char *mode)
{	char *temp;
	if ( (temp = getenv("TEMP")) == NULL )
		*fname = 0;
	else
	{	char last = '\\';
		strcpy(fname, temp);
		/* Prevent X's in path from being converted by mktemp. */
		for ( temp = fname; *temp; temp++ )
			*temp = last = tolower(*temp);
		switch ( last )
		{
		default:
			strcat(fname, "\\");
		case ':': case '\\':
			;
		}
	}
	strcat(fname, prefix);
	strcat(fname, "XXXXXX");
	mktemp(fname);
	return fopen(fname, mode);
}

/* ------ File operations ------ */

/* If the file given by fname exists, fill in its status and return 1; */
/* otherwise return 0. */
int
gp_file_status(const char *fname, file_status *pstatus)
{	struct stat fst;
	if ( stat(fname, &fst) < 0 ) return 0;
	pstatus->size_pages = (fst.st_size + 1023) >> 10;
	pstatus->size_bytes = fst.st_size;
	/****** CONVERSION PROBABLY REQUIRED HERE ******/
	pstatus->time_referenced = fst.st_atime;
	pstatus->time_created = fst.st_mtime;
	return 1;
}



