/* Copyright (C) 1989, 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.  */

#include "stdio_.h"
#include <fcntl.h>
#include "memory_.h"
#include "string_.h"
#include "stat_.h"
#include "time_.h"
#include "gstypes.h"
#include "gp.h"
#include "gsutil.h"

#include <io.h>
#include <string.h>
#include <time.h>


/* ------ Date and time ------ */
/* gettimeofday */
#ifndef HZ
#  define	HZ	CLOCKS_PER_SEC
#endif

int
gettimeofday(struct timeval *tvp, struct timezone *tzp)
{
	static long offset = 0;
	long ticks;

	if (!offset)
	{	time(&offset);
		/* call localtime to set the timezone variable */
		localtime(&offset);
		offset -= (clock() / HZ);
	}
	ticks = clock();
	tvp->tv_sec = ticks/HZ + offset;
	tvp->tv_usec = (ticks % HZ) * (1000*1000/HZ);
	tzp->tz_minuteswest = _timezone/60;
}

/* 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
}


int
gp_file_is_console(FILE *f)
{
    if (f) {
        if (_fileno(f) == _fileno(stdin) || _fileno(f) == _fileno(stdout) ||
              _fileno(f) == _fileno(stderr))
            return 1;
    }
    return 0;
}

void
gp_set_printer_binary(int prnfno, int binary)
{
}

/* Define the character used for separating file names in a list. */
const char gp_file_name_list_separator = ';';
const char gp_scratch_file_name_prefix[] = "_temp_";
const char gp_fmode_binary_suffix[] = "b";
const char gp_fmode_rb[] = "rb";
const char gp_fmode_wb[] = "wb";

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] == ':')) );
}

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 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 sbuf;
	/* The RS/6000 prototype for stat doesn't include const, */
	/* so we have to explicitly remove the const modifier. */
	if ( stat((char *)fname, &sbuf) < 0 ) return 0;
	pstatus->size_pages = stat_blocks(&sbuf);	/* st_blocks is */
					/* missing on some systems, */
					/* see stat_.h */
	pstatus->size_bytes = sbuf.st_size;
	pstatus->time_referenced = sbuf.st_mtime;
	pstatus->time_created = sbuf.st_ctime;
	return 1;
}

/* ------ File enumeration ------ */

struct file_enum_s {
        struct _finddata_t ffblk;
	char *pattern;			/* orig pattern + modified pattern */
	int patlen;			/* orig pattern length */
	int pat_size;			/* allocate space for pattern */
	int head_size;			/* pattern length through last */
					/* :, / or \ */
	int first_time;
	const gs_memory_procs *mprocs;
};

/* Initialize an enumeration.  Note that * and ? in a directory */
/* don't work, and \ is taken literally unless a second \ follows. */
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");
	int pat_size = 2 * patlen + 1;
	char *pattern;
	char *p;
	int hsize = 0;
	int i;
	if ( pfen == 0 )
		return 0;
	pattern = (*mprocs->alloc)(pat_size, 1,
				   "gp_enumerate_files(pattern)");
	if ( pattern == 0 )
		return 0;
	memcpy(pattern, pat, patlen);
	p = pattern + patlen;
	for ( i = 0; i < patlen; i++ )
	{	switch ( pat[i] )
		{
		case '*':
			/* Skip to . or end of string so DOS can do it. */
			*p++ = '*';
			while ( i < patlen && pat[i] != '.' ) i++;
			i--;
			continue;
		case '\\':
			if ( i + 1 < patlen && pat[i + 1] == '\\' )
				i++;
			/* falls through */
		case ':':
		case '/':
			hsize = p + 1 - (pattern + patlen);
		}
		*p++ = pat[i];
	}
	*p = 0;
	pfen->pattern = pattern;
	pfen->patlen = patlen;
	pfen->pat_size = pat_size;
	pfen->head_size = hsize;
	pfen->mprocs = mprocs;
	pfen->first_time = 0;
	return pfen;
}

/* Enumerate the next file. */
private const string_match_params smp_file = { '*', '?', -1, 1 };
uint
gp_enumerate_files_next(file_enum *pfen, char *ptr, uint maxlen)
{	int code;
	char *p, *q;
	uint len;
	char *fpat = pfen->pattern + pfen->patlen;
top:	if ( !pfen->first_time )
	   {	code = _findfirst(fpat, &pfen->ffblk);
                pfen->first_time = code;
	   }
	else
		code = _findnext(pfen->first_time, &pfen->ffblk);
	if ( code != 0 )
	   {	/* All done, clean up. */
		gp_enumerate_files_close(pfen);
		return ~(uint)0;
	   }
	if ( maxlen < 13 + pfen->head_size ) return maxlen + 1;	/* cop out! */
	memcpy(ptr, fpat, pfen->head_size);
	for ( p = &pfen->ffblk.name[0], q = ptr + pfen->head_size; *p; p++ )
		if ( *p != ' ' ) *q++ = *p;
	len = q - ptr;
	/* Make sure this file really matches the pattern. */
	if ( !string_match(ptr, len, pfen->pattern, pfen->patlen, &smp_file) )
		goto top;
	return len;
}

/* Clean up the file enumeration. */
void
gp_enumerate_files_close(file_enum *pfen)
{	const gs_memory_procs *mprocs = pfen->mprocs;
        if (pfen->first_time)
            _findclose(pfen->first_time);
        pfen->first_time = 0;
	(*mprocs->free)(pfen->pattern, pfen->pat_size, 1,
		 "gp_enumerate_files_close(pattern)");
	(*mprocs->free)((char *)pfen, 1, sizeof(file_enum), "gp_enumerate_files_close");
}


char *_fstrtok (char *s1, char *s2)
{
    return strtok(s1,s2);
}

int _fmemcpy (void *d, void *s, int n)
{
  return memcpy (d,s,n);
}

int _fmemset (void *d, int c, int n)
{
  return memset (d, c, n);
}

int unlink (char *fn)
{
  return _unlink (fn);
}
