#include "ckcsym.h"
char *ckzv = "Stratus VOS File support, 6.1.005, 15 January 1998";

/* C K L F I O  --  Kermit file system support for Stratus VOS */

/*
  Author: Frank da Cruz <fdc@columbia.edu>,
  The Kermit Project, Columbia University
  First released January 1985.
  Adapted to Stratus VOS by David R. Lane, SoftCom System, Inc., Nov 1993

  Copyright (C) 1985, 1999,
    Trustees of Columbia University in the City of New York.
    All rights reserved.  See the C-Kermit COPYING.TXT file or the 
    copyright text in the ckcmai.c module for disclaimer and permissions.
*/

/* Include Files */

#include "ckcdeb.h"
#include <signal.h>
#include <limits.h>

#define DIRSEP       '>'
#define ISDIRSEP(c)  ((c)=='>'||(c)=='<')

#include <stdlib.h>
#include <time.h>			/* Need this */
#include <system_io_constants.h>
#include <get_port_info.h>
#include <file_status_info.h>
#include <error_codes.h>

extern int binary;			/* We need to know this for open() */

/*
  Functions (n is one of the predefined file numbers from ckcker.h):

   zopeni(n,name)   -- Opens an existing file for input.
   zopeno(n,name,attr,fcb) -- Opens a new file for output.
   zclose(n)        -- Closes a file.
   zchin(n,&c)      -- Gets the next character from an input file.
   zsinl(n,&s,x)    -- Read a line from file n, max len x, into address s.
   zsout(n,s)       -- Write a null-terminated string to output file, buffered.
   zsoutl(n,s)      -- Like zsout, but appends a line terminator.
   zsoutx(n,s,x)    -- Write x characters to output file, unbuffered.
   zchout(n,c)      -- Add a character to an output file, unbuffered.
   zchki(name)      -- Check if named file exists and is readable, return size.
   zchko(name)      -- Check if named file can be created.
   zchkspa(name,n)  -- Check if n bytes available to create new file, name.
   znewn(name,s)    -- Make a new unique file name based on the given name.
   zdelet(name)     -- Delete the named file.
   zxpand(string)   -- Expands the given wildcard string into a list of files.
   znext(string)    -- Returns the next file from the list in "string".
   zxcmd(n,cmd)     -- Execute the command in a lower fork on file number n.
   zclosf()         -- Close input file associated with zxcmd()'s lower fork.
   zrtol(n1,n2)     -- Convert remote filename into local form.
   zltor(n1,n2)     -- Convert local filename into remote form.
   zchdir(dirnam)   -- Change working directory.
   zhome()          -- Return pointer to home directory name string.
   zkself()         -- Kill self, log out own job.
   zsattr(struct zattr *) -- Return attributes for file which is being sent.
   zstime(f, struct zattr *, x) - Set file creation date from attribute packet.
   zrename(old, new) -- Rename a file.
   zmkdir(path)      -- create a directory
   zrmdir(path)      -- delete a directory
   isdir(path)       -- is this path a directory?
   zfseek(offset)    -- position input file to offset (zero-based)
   zfnqfp(fname, buflen, buf) -- get fully qualified absolute path
 */

/* Kermit-specific includes */
/*
  Definitions here supersede those from system include files.
  ckcdeb.h is included above.
*/
#include "ckcker.h"			/* Kermit definitions */
#include "ckucmd.h"			/* For sys-dependent keyword tables */
#include "ckuver.h"			/* Version herald */

char *ckzsys = HERALD;

/* Definitions of some system commands */

char *DELCMD = "!delete_file ";		/* For file deletion */
char *PWDCMD = "!display_current_dir ";	/* For saying where I am */
char *TYPCMD = "!display ";		/* For typing a file */
char *DIRCMD = "!list -full -files -dirs -links ";/* For directory listing */
					/* For directory listing, no args */
char *DIRCM2 = "!list -full -files -dirs -links ";
char *WHOCMD = "!list_users -process login ";/* Who's there? */
char *SPACMD = "!display_disk_info ";	/* For space on disk */
char *SPACM2 = "!display_disk_info -long ";	/* For space on disk */

#ifdef DTILDE				/* For tilde expansion */
_PROTOTYP( char * tilde_expand, (char *) );
#endif /* DTILDE */

_PROTOTYP( vostty, (int) );

/* Prototypes for VOS s$calls */

_PROTOTYP( extern VOID s$attach_default_output, (CV(256) *path,
	short *append, short *status) );

_PROTOTYP( extern VOID s$attach_port, (CV(32) *port_name, CV(256)* path,
	short *hold, short *port_id, short *status) );

_PROTOTYP( extern VOID s$change_current_dir, (CV(256) *dir, short *status) );

_PROTOTYP( extern VOID s$clone, (short *status, CV(256) *err_msg) );

_PROTOTYP( extern VOID s$close, (short *port_id, short *status) );

_PROTOTYP( extern void s$copy_file, (CV(256) *source, CV(256) *dest,
	CV(32) *caller, short *switches, short *status) );

_PROTOTYP( extern VOID s$delete_file_on_close, (CV(256) *path,
	short *status) );

_PROTOTYP( extern VOID s$create_dir, (CV(256) *path, short *status) );

_PROTOTYP( extern VOID s$cv_to_int_date_time, (CV(32) *src_time,
	time_t *time, short *status) );

_PROTOTYP( extern VOID s$delete_dir, (CV(256) *path, CV(32) *dummy,
	short *flags, short *status) );

_PROTOTYP( extern VOID s$detach_default_output, (short *status) );

_PROTOTYP( extern VOID s$detach_port, (short *port_id, short *status) );

_PROTOTYP( extern VOID s$get_current_dir, (CV(256) *dir) );

_PROTOTYP( extern VOID s$get_disk_info, (CV(66) *disk_name, VOID *info,
	short *status) );

_PROTOTYP( extern VOID s$get_file_status, (CV(256) *path, VOID *info,
	short *status) );

_PROTOTYP( extern VOID s$get_home_dir, (CV(256) *dir) );

_PROTOTYP( extern void s$get_object_type, (CV(256) *path, short *chase,
	short *type, short *status) );

_PROTOTYP( extern VOID s$get_port_info, (short *port,
	struct get_port_info *pinfo, short *status) );

_PROTOTYP( extern VOID s$get_temp_file, (short *organization,
	short *max_rec_len, CV(256) *path, short *status) );

_PROTOTYP( extern VOID s$get_user_name, (CV(65) *name) ); 

_PROTOTYP( extern VOID s$expand_path, (CV(256) *src_path, CV(32) *suffix,
	CV(256) *dest_path, short *status) ); 

_PROTOTYP( extern VOID s$expand_star, (CV(256) *star_name, short *flags,
	short *max_count, short *count, VOID *dest, short *status) );

_PROTOTYP( extern VOID s$open, (short *port_id, short *organization,
	short *max_rec_len, short *io_type, short *locking_type,
	short *access_mode, CV(32) *index_name, short *status) );

_PROTOTYP( extern VOID s$read_raw, (short *port_id, short *buff_size,
	short *rec_len, void *buffer, short *status) );

_PROTOTYP( extern VOID s$seq_open, (CV(256) *path, short *io_type,
	short *port_id, short *status) );

_PROTOTYP( extern VOID s$seq_position,  (short *port_id, short *relation,
	long *rec_number, short *status) );

_PROTOTYP( extern VOID s$seq_read, (short *port_id, short *buff_size,
	short *rec_len, VOID *buffer, short *status) );

_PROTOTYP( extern VOID s$seq_write, (short *port_id, short *rec_length,
	VOID *buffer, short *status) );

_PROTOTYP( extern VOID s$seq_write_partial, (short *port_id,
	short *rec_length, VOID *buffer, short *status) );

_PROTOTYP( extern VOID s$set_expiration_date, (CV(256) *path_name,
	time_t *date_time, short *status) );

_PROTOTYP( extern VOID s$set_object_times, (CV(256) *path_name,
	time_t *time_array, short *status) ); /* four times in array */

_PROTOTYP( extern VOID s$stop_program, (CV(256) *command_line,
        short *status ) );

_PROTOTYP( extern VOID s$write_raw, (short *port_id, short *length,
	void *buffer, short *status) );

/* Define maximum length for a file name if not already defined */

#ifndef MAXNAMLEN
#define MAXNAMLEN 32
#endif /* MAXNAMLEN */

/* Longest pathname */

#ifdef MAXPATHLEN
#ifdef MAXPATH
#undef MAXPATH
#endif /* MAXPATH */
#define MAXPATH MAXPATHLEN
#else
#ifdef PATH_MAX
#define MAXPATH PATH_MAX
#else
#define MAXPATH 256
#endif /* PATH_MAX */
#endif /* MAXPATHLEN */

/* Maximum number of filenames for wildcard expansion */

/* VOS directories can be up to 256 data blocks.  This is about 5000 entries */
/* but it can vary a lot, depending on a number of factors, such as the      */
/* lengths of the names, whether or not Access Control Lists are present,    */
/* and so on.  This is about the most you get, in practice, though.          */

#define MAXWLD 5000

struct path {
    char npart[MAXNAMLEN+4];		/* name part of path segment */
    struct path *fwd;			/* forward ptr */
};

_PROTOTYP( int shxpand, (char *, char *[], int ) );


/* Declarations */

int maxnam = MAXNAMLEN;			/* Available to the outside */
int maxpath = MAXPATH;

typedef struct {
    short port;
    short io_type;
    short binary;
    short organization;
    short max_record_len;
    short record_len;
    short buffer_size;
    short buffer_pointer;
    short count;
    short count_invalid;
    char  *buffer;
} VFILE;

VFILE *fp[ZNFILS] = { 			/* File pointers */
    NULL, NULL, NULL, NULL, NULL, NULL, NULL };

/* There is not a Stratus-provided include for this.  I typed it in from
 * the VOS C subroutines manual, R068, under s$get_disk_info.
 */

struct disk_info {
    short 	version;
    CV(32) 	module_name;
    long	file_partition_size;
    long	file_partition_used;
    long	page_partition_size;
    long	page_partition_used;
    CV(32)	disk_type;
    long	disk_size;
    short	reserved1[19];
    long	disk_reads;
    long	disk_writes;
    short	reserved2;
    short	recovery_switches;
    long	reserved3;
    short	number_of_members;
    long	fatal_errors;
    long	reserved4;
};

/* Buffers and pointers used in buffered file input and output. */
#ifdef DYNAMIC
extern char *zinbuffer, *zoutbuffer;
#else
extern char zinbuffer[], zoutbuffer[];
#endif /* DYNAMIC */
extern char *zinptr, *zoutptr;
extern int zincnt, zoutcnt;
extern int wildxpand;

extern UID_T real_uid();

static long iflen = -1L;		/* Input file length */

static PID_T pid = 0;			/* pid of child fork */
static int fcount;			/* Number of files in wild group */
static char nambuf[MAXPATH+4]; 		/* Buffer for a filename */
#ifndef NOFRILLS
static char zmbuf[200];			/* For mail, remote print strings */
#endif /* NOFRILLS */

/* static */				/* Not static, must be global now. */
int  oldmtchs;				/* number of matches in last expand */
char *mtchs[MAXWLD],			/* Matches found for filename */
     **mtchptr;				/* Pointer to current match */

/*  Z K S E L F  --  Kill Self: log out own job, if possible.  */

int
zkself() {				/* For "bye", but no guarantee! */
    /* as of 6.1.alpha.11, this really does what it's supposed to do... */
    CV(256) command_line;
    short status;

    debug(F100,"zkself","",0);

    strcpy(&command_line,"logout");
    status = 0;
    s$stop_program(&command_line,&status);

    debug(F101,"zkself did not...","",status);
    exit(0);
    /*NOTREACHED*/
}

/*  Z O P E N I  --  Open an existing file for input. */

int
zopeni(n,name) int n; char *name; {
    CV(256) path;
    CV(256) src_path;
    CV(32) suffix;
    FILE_STATUS_STRUCT finfo;
    short status;

    debug(F111," zopeni",name,n);
    debug(F101,"  fp","", fp[n]);
    if (chkfn(n) != 0) return(0);
    zincnt = 0;				/* Reset input buffer */

    if (fp[n])				/* make sure it's closed */
	zclose(n);

 if (n == ZSYSFN) {			/* Input from a system function? */
/*** Note, this function should not be called with ZSYSFN ***/
/*** Always call zxcmd() directly, and give it the real file number ***/
/*** you want to use.  ***/
        debug(F110,"zopeni called with ZSYSFN, failing!",name,0);
	*nambuf = '\0';			/* No filename. */
	return(0);			/* fail. */
    }
    if (n == ZSTDIO) {			/* Standard input? */
	if (vostty(DEFAULT_INPUT_PORT_ID)) {
	    fprintf(stderr,"Terminal input not allowed");
	    debug(F100,"zopeni: attempts input from unredirected stdin","",0);
	    *nambuf = '\0';		/* No filename. */
	    return(0);
	}

	return(1);
    }

#ifdef COMMENT
    *nambuf = '\0';			/* Forget filename */
#endif /* COMMENT */

    strcpy (&src_path, name);
    strcpy (&suffix, "");
    s$expand_path (&src_path, &suffix, &path, &status);
    if (status) {
	debug(F101,"  zopeni s$expand_path status","",status);
	return 0;
    }

    finfo.version = FILE_STAT_VERSION_5;
    s$get_file_status (&path, &finfo, &status);
    if (status) {
	debug(F101,"zopeni s$get_file_status status","",status);
	return 0;
    }

    switch (finfo.file_organization) {
	case SEQUENTIAL_FILE:
	case STREAM_FILE:
	    iflen = finfo.last_record_number;
	    break;

	case FIXED_FILE:
	    iflen = finfo.last_record_number * 
		finfo.flags_struct.flags_bits_overlay.max_record_size;
	    break;

	case RELATIVE_FILE:
	    iflen = finfo.last_record_number * 
		(finfo.flags_struct.flags_bits_overlay.max_record_size + 2);
	    break;

	default:	/* uhhhh.... */
	    iflen = -1L;
	    break;
    }

    fp[n] = calloc (1, sizeof (**fp));
    debug(F111," zopeni allocated", name, fp[n]);
    if (fp[n] == NULL) {
	debug(F101,"  zopeni could not allocate fp","",sizeof **fp);
	perror("zopeni");
	return 0;
    }

    /* CANNOT RETURN AFTER HERE WITHOUT FREEING MEMORY */

    fp[n]->organization = finfo.file_organization;
    fp[n]->max_record_len
	= finfo.flags_struct.flags_bits_overlay.max_record_size;

    fp[n]->buffer_size = fp[n]->max_record_len ? fp[n]->max_record_len : 4096;
    fp[n]->buffer = calloc (1, fp[n]->buffer_size);

    if (NULL == fp[n]->buffer) {
	debug(F101,"zopeni cannot allocate buffer","",fp[n]->buffer_size);
	free (fp[n]);
	fp[n] = NULL;
	return 0;
    }

    fp[n]->io_type = INPUT_TYPE;
    s$seq_open (&path, &fp[n]->io_type, &fp[n]->port, &status);
    if (status) {
	debug(F101,"zopeni s$seq_open status","",status);
	free (fp[n]);
	fp[n] = NULL;
	free (fp[n]->buffer);
	return 0;
    }

#ifdef COMMENT
    strcpy (nambuf, name);		/* save filename */
#endif /* COMMENT */
    fp[n]->binary = binary; 		/* remember this */
    fp[n]->count_invalid = 1;		/* have no buffered data yet */
    return(1);
}

/*  Z O P E N O  --  Open a new file for output.  */

int
zopeno(n,name,zz,fcb)
/* zopeno */  int n; char *name; struct zattr *zz; struct filinfo *fcb; {
    short io_type;
    short org;
    short record_len;
    short port = 0;
    CV(256) path;
    CV(256) src_path;
    CV(32) suffix;
    CV(32) index;
    CV(32) portnam;
    short lockmod;
    short access;
    short hold;
    FILE_STATUS_STRUCT finfo;
    short status;
    int  is_binary = 0;

/* As of Version 5A, the attribute structure and the file information */
/* structure are included in the arglist. */

    if (n != ZDFILE) {
	debug(F111," zopeno",name,n);
	if (fcb) {
	    debug(F101,"zopeno fcb disp","",fcb->dsp);
	    debug(F101,"zopeno fcb type","",fcb->typ);
	    debug(F101,"zopeno fcb char","",fcb->cs);
	} else {
	    debug(F100,"zopeno fcb is NULL","",0);
	}
    }

    if (chkfn(n) != 0)
	return(0);

    io_type = OUTPUT_TYPE;

    if (fcb) {				/* If called with an FCB... */
	if (fcb->typ == XYFT_T)		/* Does it say Text? */
	    is_binary = 0;		/* Yes, not binary. */
	else
	    is_binary = 1;		/* No, it is binary. */
    }
    else {
	switch (n) {
	    case ZOFILE:
	    case ZWFILE:
	    case ZMFILE:
		is_binary = binary;	/* Use current file mode */
		break;

	    case ZDFILE:
	    case ZTFILE:
	    case ZSYSFN:
	    case ZCTERM:
	    case ZSTDIO:
		is_binary = 0;		/* Always text */
		break;

	    case ZSFILE:
		is_binary = 1;		/* Always binary */
		break;

	}
    }

    if ((n != ZCTERM) && (n != ZSTDIO)) {  /* Terminal or standard output */

	/* A real file.  Open it in desired mode (create or append). */

	if (fcb) {				/* If called with an FCB... */
	    if (fcb->dsp == XYFZ_A)		/* Does it say Append? */
	      io_type = APPEND_TYPE;	/* Yes. */
	}

	strcpy (&src_path, name);
	strcpy (&suffix, "");
	s$expand_path (&src_path, &suffix, &path, &status);
	if (status) {
	    if (n != ZDFILE)
		debug(F101,"  zopeno s$expand_path status","",status);
	    return 0;
	}

	finfo.version = FILE_STAT_VERSION_5;
	s$get_file_status (&path, &finfo, &status);
	if (status) {
	    if (status != e$object_not_found) {
		if (n != ZDFILE)
		    debug(F101,"zopeno s$get_file_status status","",status);
		return 0;
	    }

	    /* the session log is a stream file, because that reflects */
	    /* the "log of data sent back and forth" better            */

	    org = (is_binary) ? STREAM_FILE : SEQUENTIAL_FILE;
	    record_len = 4096;
	}
	else {
	    org = finfo.file_organization;
	    record_len = finfo.flags_struct.flags_bits_overlay.max_record_size;
	}
    }
    else {	/* it is a "terminal" */
	n = ZOFILE;		/* change to output file */
	org = TERMINAL_TYPE;
	record_len = 4096;
	port = DEFAULT_OUTPUT_PORT_ID;
        debug(F101," zopen terminal, ZOFILE", "", n);
    }

    fp[n] = calloc (1, sizeof (**fp));
    if (n != ZDFILE)
	debug(F111," zopeno allocated", name, fp[n]);
    if (fp[n] == NULL) {
	if (n != ZDFILE)
	    debug(F101,"  zopeno could not allocate fp","",sizeof **fp);
	perror("zopeno");
	return 0;
    }

    /* CANNOT RETURN AFTER HERE WITHOUT FREEING MEMORY */

    fp[n]->max_record_len = record_len;
    fp[n]->buffer_size = fp[n]->max_record_len ? fp[n]->max_record_len : 4096;
    fp[n]->buffer = calloc (1, fp[n]->buffer_size);

    if (NULL == fp[n]->buffer) {
	if (n != ZDFILE)
	    debug(F101,"zopeno cannot allocate buffer","",fp[n]->buffer_size);
	free (fp[n]);
	fp[n] = NULL;
	return 0;
    }

    /* save pre-calculated information */

    fp[n]->io_type = io_type;
    fp[n]->organization = org;
    fp[n]->port = port;
    fp[n]->binary = is_binary;		/* save this! */

    if (0 == fp[n]->port) {  /* not set yet */
	strcpy (&portnam, "");
	hold = DONT_HOLD;
	s$attach_port (&portnam, &path, &hold, &fp[n]->port, &status);
	if (status) {
	    if (n != ZDFILE)
		debug(F101,"zopeno s$attach_port status","",status);
	    free (fp[n]->buffer);
	    free (fp[n]);
	    fp[n] = NULL;
	    return 0;
	}

	lockmod = IMPLICIT_LOCKING;
	access = SEQUENTIAL_MODE;
	strcpy (&index, "");
	s$open (&fp[n]->port, &fp[n]->organization, &fp[n]->max_record_len,
	    &fp[n]->io_type, &lockmod, &access, &index, &status);
	if (status) {
	    if (n != ZDFILE)
		debug(F101,"zopeno s$open status","",status);
	    free (fp[n]->buffer);
	    free (fp[n]);
	    fp[n] = NULL;
	    return 0;
	}
    }

    zoutcnt = 0;			/* (PWP) reset output buffer */
    zoutptr = zoutbuffer;
    return((fp[n] != NULL) ? 1 : 0);
}

/*  Z C L O S E  --  Close the given file.  */

/*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */

int
zclose(n) int n; {
    int x, x2;
    short status;

    if (chkfn(n) < 1) return(0);	/* Check range of n */

    debug(F101,"zclose file","",n);

    if ((n == ZOFILE) && (zoutcnt > 0))	/* (PWP) output leftovers */
      x2 = zoutdump();
    else
      x2 = 0;

    x = 0;				/* Initialize return code */
    if (fp[ZSYSFN]) {			/* If file is really pipe */
    	x = zclosf(n);			/* do it specially */
    } else {
	if (fp[n]->port > MAX_RESERVED_PORT_ID) { /* only close user ports */
	    s$close (&fp[n]->port, &status);
	    x = status ? EOF : 0;
	    s$detach_port (&fp[n]->port, &status);
	    x = (status || x) ? EOF : 0;
	}
	else
	    x = 0;
	free (fp[n]->buffer);
	free (fp[n]);
	fp[n] = NULL;
    }

    iflen = -1L;			/* Invalidate file length */

    if (x == EOF)			/* if we got a close error */
      return(-1);
    else if (x2 < 0)		/* or an error flushing the last buffer */
      return(-1);		/* then return an error */
    else
      return(1);
}

/*  Z C H I N  --  Get a character from the input file.  */

/*  Returns -1 if EOF, 0 otherwise with character returned in argument  */

int
zchin(n,c) int n; int *c; {
    int a, x;
    register VFILE *vp;
    short status;
    short rbuffsize;

    /* (PWP) Just in case this gets called when it shouldn't. */
    if (n == ZIFILE) {
	x = zminchar();
	*c = x;
	return((x < 0) ? -1 : 0);
    }

    if (chkfn(n) < 1) return(-1);
    vp = fp[n];

    if (vp->count_invalid) {	/* need to read more data */

	debug(F101,"zchin reading file","",n);

	if (!vp->binary) { /* text mode, add appropriate line separators */

	    rbuffsize = vp->buffer_size - 1;
	    /* leave room for line terminator character(s) */

#ifndef NLCHAR
	    rbuffsize--;
#endif /* NLCHAR */

	    s$seq_read (&vp->port, &rbuffsize, &vp->record_len,
		vp->buffer, &status);

	    if (0 != status) {
		debug(F101,"zchin text s$seq_read status","",status);
		return (-1); /* hope it's end of file... */
	    }
#ifdef NLCHAR
	    vp->buffer[vp->record_len++] = NLCHAR;
#else
	    vp->buffer[vp->record_len++] = '\r';
	    vp->buffer[vp->record_len++] = '\n';
#endif /* NLCHAR */
	}
	else {		/* binary */
	    if (vp->organization == STREAM_FILE) {
		s$read_raw (&vp->port, &vp->buffer_size, &vp->record_len,
		    vp->buffer, &status);
		if (status == e$short_record) /* not buffer_size bytes left */
		    status = 0;
	    }
	    else
		s$seq_read (&vp->port, &vp->buffer_size, &vp->record_len,
		    vp->buffer, &status);

	    if (0 != status) {
		debug(F101,"zchin binary s$...read... status","",status);
		return (-1); /* hope it's end of file... */
	    }
    	}
	/* set up for character stuff... */
	vp->count = vp->record_len;
	vp->buffer_pointer = 0;
	vp->count_invalid = 0;
    }
    /* count is valid */

    x = vp->buffer[vp->buffer_pointer++];
    if (0 >= --(vp->count))
	vp->count_invalid = 1;

    *c = x;
    return((x < 0) ? -1 : 0);
}

/*  Z S I N L  --  Read a line from a file  */

/*
  Writes the line into the address provided by the caller.
  n is the Kermit "channel number".
  Writing terminates when newline is encountered, newline is not copied.
  Writing also terminates upon EOF or if length x is exhausted.
  Returns 0 on success, -1 on EOF or error.
*/
int
zsinl(n,s,x) int n, x; char *s; {
    int a, z = 0;			/* z is return code. */

    if (chkfn(n) < 1) {			/* Make sure file is open */
	return(-1);
    }
    a = -1;				/* Current character, none yet. */
    while (x--) {			/* Up to given length */
#ifndef NLCHAR
	int old;
	old = a;			/* Previous character */
#endif
	if (zchin(n,&a) < 0) {		/* Read a character from the file */
	    debug(F101,"zsinl","",a);
	    z = -1;			/* EOF or other error */
	    break;
	}
#ifdef NLCHAR
	if (a == (char) NLCHAR) break;	/* Single-character line terminator */
#else
	if (a == '\015') continue;	/* CR, get next character */
	if (old == '\015') {		/* Previous character was CR */
	    if (a == '\012') break;	/* This one is LF, so we have a line */
	    else *s++ = '\015';		/* Not LF, deposit CR */
	}
#endif /* NLCHAR */
	*s = a;				/* Deposit character */
	s++;
    }
    *s = '\0';				/* Terminate the string */
    return(z);
}

/*
 * (PWP) (re)fill the buffered input buffer with data.  All file input
 * should go through this routine, usually by calling the zminchar()
 * macro (in ckcker.h).
 */

/*
 * Suggestion: if fread() returns 0, call ferror to find out what the
 * problem was.  If it was not EOF, then return -2 instead of -1.
 * Upper layers (getpkt function in ckcfns.c) should set cxseen flag
 * if it gets -2 return from zminchar macro.
 *
 * This always uses zin* buffering for io, not fp->buffer.
 */
int
zinfill() {
    int x;
    short status;
    short buff_len;
    VFILE *vp = fp[ZIFILE];

    errno = 0;
    buff_len = INBUFSIZE;
    
    /* leave room for line terminators in text mode */
    if (0 == vp->binary)
#ifdef NLCHAR
	buff_len -= 1;
#else
	buff_len -= 2;
#endif /* NLCHAR */

    if (vp->binary && vp->organization == STREAM_FILE)
	s$read_raw (&vp->port, &buff_len, &vp->record_len, zinbuffer, &status);
    else
	s$seq_read (&vp->port, &buff_len, &vp->record_len, zinbuffer, &status);

    zincnt = vp->record_len;

    debug(F101,"zinfill zincnt","",zincnt);
    if (status) {
	debug(F101,"zinfill s$...read... status","",status);
	return (status == e$end_of_file) ? (-1) : (-2);
    }

    if (0 == vp->binary) { /* text mode, add a NLCHAR to it */
#ifdef NLCHAR
	zinbuffer[zincnt++] = NLCHAR;
#else
	zinbuffer[zincnt++] = '\r';
	zinbuffer[zincnt++] = '\n';
#endif
    }

    zinptr = zinbuffer;	/* set pointer to beginning, (== &zinbuffer[0]) */
    zincnt--;		/* one less char in buffer */
    return((int)(*zinptr++) & 0377); /* because we return the first */
}

/*  Z S O U T  --  Write a string out to the given file, buffered.  */

int
zsout(n,s) int n; char *s; {
    short status;
    int len;

    if (chkfn(n) < 1) return(-1); /* Keep this here, prevents memory faults */
    if (n != ZDFILE)
	debug(F111,"zsout writing to file",s,n);

    len = strlen (s);
    if ('\n' == s[len-1]) {
	s[--len] = '\0';
	return (zsoutl (n,s));
    }

    fp[n]->record_len = (short) strlen(s);
    /* since this never writes an end-of-line, always write partial */
    if (fp[n]->organization == STREAM_FILE && fp[n]->binary)
	s$write_raw (&fp[n]->port, &fp[n]->record_len, s, &status);
    else
	s$seq_write_partial (&fp[n]->port, &fp[n]->record_len, s, &status);

    return status ? (-1) : 0;
}

/*  Z S O U T L  --  Write string to file, with line terminator, buffered  */

int
zsoutl(n,s) int n; char *s; {
    short status;
    int len;

    if (chkfn(n) < 1) return(-1);
    if (n != ZDFILE)
	debug(F111,"zsoutl writing to file",s,n);

    len = strlen (s);
    if ('\n' == s[len-1])
	len--;

    fp[n]->record_len = len;
    /* adding a record terminator, means always use seq_write... */

    s$seq_write (&fp[n]->port, &fp[n]->record_len, s, &status);
    return status ? (-1) : 0;
}

/*  Z S O U T X  --  Write x characters to file, unbuffered.  
 *  returns -1 on error, or the number of characters written.
 */

int
zsoutx(n,s,x) int n, x; char *s; {
    short status;

    if (chkfn(n) < 1) return(-1);
    if (n != ZDFILE)
	debug(F101,"zsoutx writing to file","",n);
    fp[n]->record_len = x;

    if (fp[n]->binary) {
	if (fp[n]->organization == STREAM_FILE)
	    s$write_raw (&fp[n]->port, &fp[n]->record_len, s, &status);
	else
	    s$seq_write_partial (&fp[n]->port, &fp[n]->record_len, s, &status);
    }
    else
	s$seq_write (&fp[n]->port, &fp[n]->record_len, s, &status);

    return((status == 0) ? x : -1);
}


/*  Z C H O U T  --  Add a character to the given file.  */

/*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */

int
#ifdef CK_ANSIC
zchout(register int n, char c)
#else
zchout(n,c) register int n; char c;
#endif /* CK_ANSIC */
/* zchout() */ {
    short status;
    char  buff[2];

    if (chkfn(n) < 1) return(-1);

    buff[0] = c;
    buff[1] = '\0';
    if (n != ZDFILE)
	debug(F111,"zchout writing to file",buff,n);

    fp[n]->record_len = 1;

    if (fp[n]->binary) {
	if (fp[n]->organization == STREAM_FILE)
	    s$write_raw (&fp[n]->port, &fp[n]->record_len, &c, &status);
	else
	    s$seq_write_partial (&fp[n]->port, &fp[n]->record_len,
		&c, &status);
    }
    else
	s$seq_write (&fp[n]->port, &fp[n]->record_len, &c, &status);

    return((status == 0) ? 1 : -1);
}

/* (PWP) buffered character output routine to speed up file IO */

int
zoutdump() {
    int x;
    VFILE *vp;
    short status = 0;
    int   len;
    register char  *ep;
#ifdef NLCHAR
    char  *cp;
#else
    register int   i;
    static   char  last;
#endif /* NLCHAR */

    zoutptr = zoutbuffer;		/* Reset buffer pointer in all cases */
    debug(F101,"zoutdump chars","",zoutcnt);
    if (zoutcnt == 0) {			/* Nothing to output */
	return(0);
    } else if (zoutcnt < 0) {		/* Unexpected negative argument */
	zoutcnt = 0;			/* Reset output buffer count */
	return(-1);			/* and fail. */
    }

    vp = fp[ZOFILE];

    if (vp->binary) {
	vp->record_len = zoutcnt;
	debug(F101,"zoutdump binary, port","",vp->port);
	if (vp->port == DEFAULT_OUTPUT_PORT_ID) { /* terminal */
	    conxo (vp->record_len, zoutbuffer);
	}
	else {
	    if (vp->organization == STREAM_FILE)
		s$write_raw (&vp->port, &vp->record_len,
		    zoutbuffer, &status);
	    else
		s$seq_write_partial (&vp->port, &vp->record_len,
		    zoutbuffer, &status);
	}
    }
    else {
	/* need to deblock the data in the output buffer */

	debug(F101,"zoutdump text, port","",vp->port);
#ifdef NLCHAR
	cp = zoutbuffer;

	do {
	    for (ep = cp; *ep != NLCHAR; ep++)
		if (ep > &zoutbuffer[zoutcnt-1]) {
		    ep = NULL;
		    break;
		}
	    if (NULL != ep) {
		len = (int) (ep - cp); /* NOT +1 */
		vp->record_len = len;
		if (vp->port == DEFAULT_OUTPUT_PORT_ID) { /* terminal */
		    *ep = '\0'; /* conoll wants ASCIIZ string */
		    conoll (cp);
		}
		else
		    s$seq_write (&vp->port, &vp->record_len, cp, &status);
		ep++;	/* move past the NLCHAR or NULL */
	    }
	    else if (cp < &zoutbuffer[zoutcnt-1]) {	/* not done it all */
		/* it's flushing in the middle of a record */
		len = zoutcnt - (int) (cp - (&zoutbuffer[0]));
		vp->record_len = len;
		if (vp->port == DEFAULT_OUTPUT_PORT_ID) { /* terminal */
		    *(cp+len) = '\0'; /* conol wants ASCIIZ string */
		    conol (cp);
		}
		else {
		    if (vp->organization == STREAM_FILE)
			s$write_raw (&vp->port, &vp->record_len,
			    cp, &status);
		    else
			s$seq_write_partial (&vp->port, &vp->record_len,
			    cp, &status);
		}
	    }
	    cp = ep;
	} while ((status == 0) && (NULL != cp) &&
		 ((cp < &zoutbuffer[zoutcnt-1])));
#else
	/* this is not tested, but it is identical to log code in dpt.pm */
	ep = zoutbuffer;
	for (i = 0; i < zoutcnt; i++)
	{
	    if ((zoutbuffer[i] == '\r') || (zoutbuffer[i] == '\n'))
	    {
		len = (zoutbuffer + i) - ep;
		if ((last != '\r') || (buff[i] != '\n')) {
		    if (vp->port == DEFAULT_OUTPUT_PORT_ID) { /* terminal */
			*(ep + len) = '\0'; /* conoll wants ASCIIZ string */
			conoll (ep);
		    }
		    else
			s$seq_write (&vp->port, &len, ep, &status);
		}
		ep = &zoutbuffer[i+1];
	    }
	    last = zoutbuffer[i];
	}

	if (ep < (zoutbuffer + len)) /* write out the last bit */
	{
	    len = (zoutbuff + len) - ep;
	    if (vp->port == DEFAULT_OUTPUT_PORT_ID) { /* terminal */
		*(ep + len) = '\0'; /* conol wants ASCIIZ string */
		conol (ep);
	    }
	    else {
		if (vp->organization == STREAM_FILE)
		    s$write_raw (&vp->port, &len, ep, &status);
		else
		    s$seq_write_partial (&vp->port, &len, ep, &status);
	    }
	}

#endif /* NLCHAR */

    }
    if (0 == status) {
	debug(F101,"zoutdump s$...write... ok","",zoutcnt);
	zoutcnt = 0;			/* Reset output buffer count */
	return(0);			/* write() worked OK */
    } else {
	debug(F101,"zoutdump s$...write... status","",status);
	zoutcnt = 0;			/* Reset output buffer count */
	return(-1);			/* s$write_* failed */
    }
}

/*  C H K F N  --  Internal function to verify file number is ok  */

/*
 Returns:
  -1: File number n is out of range
   0: n is in range, but file is not open
   1: n in range and file is open
*/
int
chkfn(n) int n; {
    if (n < 0 || n >= ZNFILS) {
	debug(F101,"chkfn: file number out of range","",n);
	return(-1);
    }
    else return( (fp[n] == NULL) ? 0 : 1 );
}

/*  Z C H K I  --  Check if input file exists and is readable  */

/*
  Returns:
   >= 0 if the file can be read (returns the size).
     -1 if file doesn't exist or can't be accessed,
     -2 if file exists but is not readable (e.g. a directory file).
     -3 if file exists but protected against read access.

 Directory files, special files, and symbolic links are not readable.
*/
long
zchki(name) char *name; {
    CV(256) path;
    CV(256) src_path;
    CV(32) suffix;
    FILE_STATUS_STRUCT finfo;
    short status;
    int x;
    long size;

    debug(F110,"zchki checking",name,0);

    if (!name) return (-1);

    strcpy (&src_path, name);
    strcpy (&suffix, "");
    s$expand_path (&src_path, &suffix, &path, &status);
    if (status) {
	debug(F101,"zchki s$expand_path status","",status);
	return -1; /* doesn't exist or cannot be accessed */
    }

    finfo.version = FILE_STAT_VERSION_5;
    s$get_file_status (&path, &finfo, &status);
    if (status) {
	debug(F101,"zchki s$get_file_status status","",status);
	return -1;
    }

    switch ((int) finfo.callers_mode) {
	case 'r':
	case 'w':
	    break;		/* exists, and we can read it */

	case 'e':
	case 'n':
	case 'u':
	    return (-3);	/* exists, but protected from reading */

	default:
	    return (-2);	/* not a file */
    }

    switch (finfo.file_organization) {
	case SEQUENTIAL_FILE:
	case STREAM_FILE:
	    size = finfo.last_record_number;
	    break;

	case FIXED_FILE:
	    size = finfo.last_record_number * 
		finfo.flags_struct.flags_bits_overlay.max_record_size;
	    break;

	case RELATIVE_FILE:
	    size = finfo.last_record_number * 
		(finfo.flags_struct.flags_bits_overlay.max_record_size + 2);
	    break;

	default:	/* uhhhh.... */
	    size = 0;
	    break;
    }

    strcpy (nambuf,name);		/* remember the name of the file */

    if (size > (finfo.blocks_used * 4096))
	size = (finfo.blocks_used * 4096);

    if (size < 0)
	size = 0;

    return (size);
}

/*  Z C H K O  --  Check if output file can be created  */

/*
 Returns -1 if write permission for the file would be denied, 0 otherwise.
*/
int
zchko(name) char *name; {
    int i, x;
    char *s;

    if (!name) return(-1);		/* Watch out for null pointer. */
    x = (int)strlen(name);		/* Get length of filename */
    debug(F111,"zchko length",name,x);

    return (0);
}

/*  Z D E L E T  --  Delete the named file.  */

int
zdelet(name) char *name; {
    debug(F110,"zdelet",name,0);
    return(remove(name));
}

/*  Z R T O L  --  Convert remote filename into local form  */

/*  For VOS as in UNIX, this means changing uppercase letters to lowercase. */

VOID
zrtol(name,name2) char *name, *name2; {
    char *p; int flag = 0;
    debug(F101,"zrtol name","",name);
    debug(F101,"zrtol name2","",name2);
    if (!name || !name2) return;
    debug(F101,"zrtol input","",name);
    p = name2;
    for ( ; *name != '\0'; name++) {
	if (*name > ' ') flag = 1;	/* Strip leading blanks and controls */
	if (flag == 0 && *name < '!') continue;
    	*p++ = isupper(*name) ? tolower(*name) : *name;
    }
    *p-- = '\0';			/* Terminate */
    while (*p < '!' && p > name2)	/* Strip trailing blanks & contronls */
      *p-- = '\0';

    debug(F110,"zrtol result",name2,0);
}

VOID
nzrtol(name,name2,fncnv,fnrpath,max)
    char *name, *name2; int fncnv, fnrpath, max;
{ /* nzrtol */
    char *p; int flag = 0, n = 0;
    char tmpbuf[CKMAXPATH+1], *tmp;
    int devnull = 0;
    int acase = 0;
    if (!name2) return;
    if (!name) name = "";
    debug(F110,"zrtol original name",name,0);

    tmpbuf[0] = '\0';
    tmp = tmpbuf;
    devnull = !strcmp(name,"/dev/null");

    if (!devnull && fnrpath == PATH_OFF) { /* RECEIVE PATHNAMES OFF */
	zstrip(name,&p);
	strncpy(tmpbuf,p,CKMAXPATH);
    } else if (!devnull && fnrpath == PATH_ABS) { /* REC PATHNAMES ABSOLUTE */
	strncpy(tmpbuf,name,CKMAXPATH); 
    } else if (!devnull && isabsolute(name)) { /* RECEIVE PATHNAMES RELATIVE */
	sprintf(tmpbuf,".%s",name);
    } else {				/* Ditto */
	strncpy(tmpbuf,name,CKMAXPATH); 
    }
    tmpbuf[CKMAXPATH] = 0;
    debug(F110,"zrtol tmpbuf",tmpbuf,0);

    if (!fncnv || devnull) {		/* Not converting */
	strncpy(name2,tmpbuf,max);	/* We're done. */
	return;
    }
    name = tmpbuf;			/* Converting */

    p = name2;
    for (; *name != '\0' && n < maxnam; name++) {
	if (*name > ' ') flag = 1;	/* Strip leading blanks and controls */
	if (flag == 0 && *name < '!')
	  continue;
	if (isupper(*name))		/* Check for mixed case */
	  acase |= 1;
	else if (islower(*name))
	  acase |= 2;
	*p++ = *name;
	n++;
    }
    *p-- = '\0';			/* Terminate */
    while (*p < '!' && p > name2)	/* Strip trailing blanks & controls */
      *p-- = '\0';

    if (*name2 == '\0') {		/* Nothing left? */
	strcpy(name2,"NONAME");		/* do this... */
    } else if (acase == 1) {		/* All uppercase? */
	p = name2;			/* So convert all letters to lower */
	while (*p) {
	    if (isupper(*p))
	      *p = tolower(*p);
	    p++;
	}
    }      
    debug(F110,"zrtol new name",name2,0);
}

/*  Z S T R I P  --  Strip device & directory name from file specification */

/*  Strip pathname from filename "name", return pointer to result in name2 */

static char work[257];

VOID
zstrip(name,name2) char *name, **name2; {
    char *cp, *pp;
    debug(F110,"zstrip before",name,0);
    pp = work;
#ifdef DTILDE
    if (*name == '~') name++;
#endif /* DTILDE */
    for (cp = name; *cp != '\0'; cp++) {
    	if (ISDIRSEP(*cp))
	  pp = work;
	else
	  *pp++ = *cp;
    }
    *pp = '\0';				/* Terminate the string */
    *name2 = work;
    debug(F110,"zstrip after",*name2,0);
}

/*  Z L T O R  --  Local TO Remote */

VOID
zltor(name,name2) char *name, *name2; {
    nzltor(name,name2,1,0,CKMAXPATH);
}

/*  N Z L T O R  --  New Local TO Remote */

VOID
nzltor(name,name2,fncnv,fnspath,max)
    char *name, *name2; int fncnv, fnspath, max;
{ /* nzltor */
    char *cp, *pp;
#ifdef COMMENT
    int dc = 0;
#endif /* COMMENT */
    int n = 0;
    char *dotp = NULL;
    char tmpbuf[CKMAXPATH+1];
    char *p;

    debug(F110,"nzltor name",name,0);

    /* Handle pathname */
    
    tmpbuf[0] = 0;
    if (fnspath == PATH_OFF) {		/* PATHNAMES OFF */
	zstrip(name,&p);
	strncpy(tmpbuf,p,CKMAXPATH);
	tmpbuf[CKMAXPATH] = 0;
    } else {
	int ndx;

	if (fnspath == PATH_ABS) {	/* ABSOLUTE */
	    zfnqfp(name,CKMAXPATH,tmpbuf);
	} else {			/* RELATIVE */
	    strncpy(tmpbuf,name,CKMAXPATH); 
	}

	for (p = tmpbuf; !ISDIRSEP(*p); p++)
	    ; 				/* Look for first '>' */
	ndx = 0;   			/* strip off %system#module */
	while (*p) {
	    tmpbuf[ndx++] = *p++;
	}

    }
    debug(F110,"zltor tmpbuf",tmpbuf,0);

    if (!fncnv) {			/* Not converting */
	strncpy(name2,tmpbuf,max);	/* We're done. */
	return;
    }
    name = tmpbuf;			/* Converting */

    pp = work;				/* Output buffer */

    for (cp = name, n = 0; *cp && n < max; cp++,n++) { /* Strip path name */

	if (islower(*cp))		/* Uppercase letters */
	  *pp++ = toupper(*cp);		/* Change tilde to 'X' */
	else if (*cp == '~')
	  *pp++ = 'X';
	else if (*cp == '#')		/* Change number sign to 'X' */
	  *pp++ = 'X';
	else if (*cp == '*' || *cp == '?')
	  *pp++ = 'X';
	else if (*cp <= ' ')		/* Change space and controls to 'X' */
	  *pp++ = 'X';
	else if (*cp == '>' || *cp == '<')	/* Change any dirseps to '/' */
	  *pp++ = '/';                  /* <'s should really be parsed out */
	else if (*cp == '.') {		/* Change dot to underscore */
	    dotp = pp;			/* Remember where we last did this */
	    *pp++ = '_';
	} else
	  *pp++ = *cp;
    }
    *pp = 0;				/* Tie it off. */
    if (dotp) *dotp = '.';		/* Restore last dot (if any) */
    cp = name2;				/* If nothing before dot, */
    if (*work == '.') *cp++ = 'X';	/* insert 'X' */
    strncpy(cp,work,max);
    debug(F110,"zltor name2",name2,0);
}



/*  Z C H D I R  --  Change directory  */
/*
  Call with:
    dirnam = pointer to name of directory to change to,
      which may be "" or NULL to indicate user's home directory.
  Returns:
    0 on failure
    1 on success
*/
int
zchdir(dirnam) char *dirnam; {
    char *hd, *sp, *p;
    CV(256) rel;
    CV(256) abs;
    CV(32) suffix;
    short status;

    debug(F110,"zchdir",dirnam,0);
    if (dirnam == NULL || dirnam == "" || *dirnam == '\0') /* If arg is null */
      dirnam = zhome();			/* use user's home directory. */
    sp = dirnam;
    debug(F110,"zchdir 2",dirnam,0);

#ifdef DTILDE
    hd = tilde_expand(dirnam);		/* Attempt to expand tilde */
    if (*hd == '\0') hd = dirnam;	/* in directory name. */
#else
    hd = dirnam;
#endif /* DTILDE */
    debug(F110,"zchdir 3",hd,0);


    strcpy(&rel, hd);
    strcpy(&abs, "");
    strcpy(&suffix, "");
    status = 0;

    s$expand_path(&rel, &suffix, &abs, &status);
    debug(F111,"zchdir4",hd,status);
    if(status)
	return(0);

    s$change_current_dir(&abs, &status);
    debug(F111,"zchdir5",hd,status);
    if(status)
 	return(0);
    else
	return(1);
}

/*  Z H O M E  --  Return pointer to user's home directory  */

/* This is a royal pain under some operating systems, involving reading	*/
/* the password file, etc.  Under VOS we just ask, since the user is    */
/* allowed to specify a different home dir at login time, they make it  */
/* easy to get the answer.						*/

char *
zhome() {
    CV(256) cv_home;
    static char homebuf[257];
    char *home;

    s$get_home_dir (&cv_home);
    strcpy (homebuf, &cv_home);
    home = homebuf;

    return(home ? home : ".");
}

/*  Z G T D I R  --  Return pointer to user's current directory  */

char *
zgtdir() {
    char *buf;
    static char currbuf[257];
    CV(256) cv_curr;

    s$get_current_dir (&cv_curr);
    strcpy (currbuf, &cv_curr);
    buf = currbuf;

    return buf;
}

/*  Z X C M D -- Run a system command so its output can be read like a file */

/* return 0 on error, 1 on success, -1 if file number is bad. */

int
zxcmd(filnum,comand) int filnum; char *comand; {
    int out;
    short organization = SEQUENTIAL_FILE;
    short max_record_len = 4096;
    short status;
    short append_switch = 0;
    CV(256) temp_path;
    char c_temp_path[257];
    int save_binary;

    debug(F111,"zxcmd called",comand,filnum);
    if (chkfn(filnum) < 0) return(-1);	/* Need a valid Kermit file number. */

    if (filnum == ZSTDIO || filnum == ZCTERM) /* But not one of these. */
      return(0);

    out = (filnum == ZIFILE || filnum == ZRFILE) ? 0 : 1 ;
    if (out) {
      debug(F101,"zxcmd cannot open for output","",filnum);
      return (0); /* we can't write to the file */
    }

    s$get_temp_file (&organization, &max_record_len, &temp_path, &status);
    if (status) {
	debug(F101,"zxcmd s$get_temp_file, status","",status);
	return (0); /* error */
    }
    strcpy (c_temp_path, &temp_path);
    s$attach_default_output (&temp_path, &append_switch, &status);
    if (status) {
	debug(F111,"zxcmd s$attach_default_output, status",c_temp_path,status);
	return (0); /* error */
    }
    *nambuf = '\0';		/* forget old name */
    status = zsyscmd(comand); /* Hope this works. get VOS status back. */ 
    debug(F111,"zxcmd zsyscmd status",c_temp_path,status);
    if (status) { /* error */
	s$detach_default_output (&status); /* ignore this status */
	s$delete_file_on_close (&temp_path, &status); /* ignore this status */
	return (0); /* error */
    }
    s$detach_default_output (&status);
    if (status) {
	debug(F111,"zxcmd s$detach_default_output, status",c_temp_path,status);
	s$delete_file_on_close (&temp_path, &status); /* ignore this status */
	return (0); /* error */
    }
    save_binary = binary;
    binary = 0; /* it's a text file */
    if (0 == zopeni (filnum, c_temp_path)) { /* error? */
	binary = save_binary;
	debug(F100,"zxcmd zopeni failed","",0);
	s$delete_file_on_close (&temp_path, &status); /* ignore this status */
	return (0); /* error */
    }
    binary = save_binary;
    s$delete_file_on_close (&temp_path, &status); /* will poof at zclosf */
    if (status) {
	debug(F111,"zxcmd s$delete_file_on_close, status",c_temp_path,status);
	/* continue, it will still read, just leaving a loose file around */
    }

    return(1); /* Success! */
}

/*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */

int
zclosf(filnum) int filnum; {
    debug(F101,"zclosf called","",filnum);
    return(1);
}

/*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
/*
  Returns the number of files that match fn1, with data structures set up
  so  that first file (if any) will be returned by the next znext() call.
  Depends on external variable wildxpand:  0 means  we  expand  wildcards
  internally, nonzero means we call the shell to do it. In VOS, we always
  do it.
*/

int
zxpand(fn) char *fn; {
    char *p;

#ifdef DTILDE				/* Built with tilde-expansion? */
    char *tnam;
#endif /* DTILDE */
    debug(F111,"zxpand entry",fn,wildxpand);
#ifdef DTILDE				/* Built with tilde-expansion? */
    if (*fn == '~') {			/* Starts with tilde? */
	tnam = tilde_expand(fn);	/* Try to expand it. */
	if (tnam) fn = tnam;
    }
    debug(F110,"zxpand after tilde_x",fn,0);
#endif /* DTILDE */

    fcount = shxpand(fn,mtchs,MAXWLD); /* Shell [JUST KIDDING!] */

    if (fcount > 0) {
	mtchptr = mtchs;		/* Save pointer for next. */
    }
    if (fcount > 0) {
	debug(F111,"zxpand ok",mtchs[0],fcount);
	return(fcount);
    }
    debug(F111,"zxpand fgen1",fn,fcount); /* Didn't get one, or got too many */
    p = malloc((int)strlen(fn) + 10);	/* Make space */
    if (!p) return(0);
    zrtol(fn,p);			/* Try again, maybe lowercase */

    fcount = shxpand(p,mtchs,MAXWLD); /* Shell */

    if (fcount > 0) {			/* Got one? */
	mtchptr = mtchs;		/* Save pointer for next. */
	debug(F111,"zxpand fgen2 ok",mtchs[0],fcount);
    } else debug(F111,"zxpand 2 not ok",p,fcount);
    free(p);
    return(fcount);
}


/*  Z N E X T  --  Get name of next file from list created by zxpand(). */
/*
 Returns >0 if there's another file, with its name copied into the arg string,
 or 0 if no more files in list.
*/
int
znext(fn) char *fn; {
    if (fcount-- > 0) strcpy(fn,*mtchptr++);
    else *fn = '\0';
    debug(F111,"znext",fn,fcount+1);
    return(fcount+1);
}


/*  Z C H K S P A  --  Check if there is enough space to store the file  */

/*
 Call with file specification f, size n in bytes.
 Returns -1 on error, 0 if not enough space, 1 if enough space.

 On  VOS, we pick up the volume name from first part of the path name, then
 check to make sure it's valid, then check the amount of space available on
 that volume.  Also, VOS won't let you use the last 200 blocks of the  file
 partition  on  the  volume, so we count off for that.  Also, the number of
 indirect blocks is only  partially  accounted  for.  This  isn't  perfect,
 because  some  of  the different file organizations can cause the reported
 size of the file not to match the actual size of the  file,  but  this  is
 only  a problem with files with a large number of records and certain file
 orgs.  We don't try to figure this out, instead we let the  transfer  fail
 when  the  disk gets full, which is what a number of implementations do in
 all cases.

*/
int
#ifdef CK_ANSIC
zchkspa(char *f, long n)
#else
zchkspa(f,n) char *f; long n;
#endif /* CK_ANSIC */
/* zchkspa() */ {
    CV(256) path;
    CV(256) src_path;
    char    cpath[257];
    CV(32) suffix;
    CV(66) disk_name;
    short status;
    int x;
    struct disk_info dinfo;
    char *cp;
    long blocks_left;

    debug(F111,"zchkspa checking",f,n);

    if (!f) return (-1);

    strcpy (&src_path, f);
    strcpy (&suffix, "");
    s$expand_path (&src_path, &suffix, &path, &status);
    if (status) {
	debug(F101,"zchkspa s$expand_path status","",status);
	return -1; /* an error occurred */
    }

    strcpy (cpath, &path);
    cp = strchr (cpath, DIRSEP);
    if (cp)
	*cp = '\0'; /* cut off the directory name from the disk name */

    strcpy (&disk_name, cpath);
    dinfo.version = 1;
    s$get_disk_info (&disk_name, &dinfo, &status);
    if (status) {
	debug(F111,"zchkspa s$get_disk_info status",cpath,status);
	return -1; /* an error occurred */
    }

    blocks_left = dinfo.file_partition_size - dinfo.file_partition_used;
    blocks_left -= 200; /* can't use last 200 blocks */

    n /= 4096;
    n++;

    /* count some of the indirect blocks */
    /* I used to know how to count these really... */

    if (n > 16)
	n++;

    if (n > 256)
	n++;

    if (n >= blocks_left)
	return(0);				/* not enough space */
    else
	return(1);				/* Okay! */
}


/*  Z N E W N  --  Make a new name for the given file  */

/*
  Given  the  name,  fn, of a file that already exists, this function builds a
  new name of the form "<oldname>.~<n>~", where  <oldname>  is  argument  name
  (fn),  and  <n>  is  a  version number, one higher than any existing version
  number for that file, up to 9999.  This format is consistent with that  used
  by GNU EMACS.  If the constructed name is too long for the system's maximum,
  enough  characters  are  truncated from the end of <fn> to allow the version
  number to fit.  If no free version numbers  exist  between  1  and  9999,  a
  version  number  of  "xxxx"  is  used.  Returns a pointer to the new name in
  argument s.
*/

VOID
znewn(fn,s) char *fn, **s; {
#define ZNEWNBL 255
#define ZNEWNMD 4

    static char buf[ZNEWNBL+1];
    char *bp, *xp, *yp;
#ifdef OS2
    char *zp, ch, temp[14];
#endif /* OS2 */
    int len = 0, d = 0, n, t, i, j, k, power = 1;

    int max = MAXNAMLEN;		/* Maximum name length */

    if (max < 14) max = 14;		/* Make it reasonable */
    if (max > ZNEWNBL) max = ZNEWNBL;
    bp = buf;				/* Buffer for building new name */
    yp = fn;
    while (*yp) {			/* Copy old name into buffer */
	*bp++ = *yp++;
	if (len++ > ZNEWNBL) break;	/* ...up to buffer length */
    }
    *s = NULL;
    for (i = 1; i < ZNEWNMD + 1; i++) {	/* Version numbers up to 10**i - 1 */
	power *= 10;			/* Next power of 10 */
	j = max - len;			/* Space left for version number */
	k = 3 + i;			/* Space needed for it */
	if (j < k) {			/* Make room if necessary */
	    len -= (k - j);		/* Adjust length of filename */
	    bp = buf + len;		/* Point to new end */
	}
	*bp++ = '*';			/* Put a star on the end (UNIX) */
	*bp-- = '\0';			/* Terminate with null */

	n = zxpand(buf);		/* Expand the resulting wild name */
					/* n is the number of matches */
	while (n-- > 0) {		/* Find any existing name.~n~ files */
	    xp = *mtchptr++;		/* Point at matching name */
	    xp += len;			/* Look for .~<n>~ at the end of it */
	    if (*xp == '.' && *(xp+1) == '~') {	/* Has a version number */
		t = atoi(xp+2);		        /* Get it */
		if (t > d) d = t;	/* Save d = highest version number */
	    }
	}
	if (d < power-1) {		/* Less than maximum possible? */
	    sprintf(bp,".~%d~",d+1);	/* Yes, make "name.~<d+1>~" */
	    *s = buf;			/* Point to new name */
	    break;			/* Done, return it */
	}
    }
    if (*s == NULL) {
	sprintf(bp,".~xxxx~");		/* Too many, use xxxx. */
	*s = buf;
    }

    return;
}


/*  Z R E N A M E  --  Rename a file  */

/*  Call with old and new names */
/*  Returns 0 on success, -1 on failure. */

int
zrename(old,new) char *old, *new; {
   debug(F110,"zrename old",old,0);
   debug(F110,"        new",new,0);
   return rename(old, new);
}


/*  Z C O P Y  --  Copy a file  */
/*
   Call with source and destination names.
   If destination name is the name of a directory, the source file is
   copied to that directory with the original name.
   Returns 0 on success, -1 on failure.
*/
int
zcopy(source,destination) char *source, *destination; {
    CV(256) cvsrc;
    CV(256) cvdest;
    CV(32)  suffix;
    CV(256) cvpath;
    CV(32)  caller;
    short   switches;
    short   status;
    char p[257], *s = destination;
    int x;
    
    debug(F110,"zcopy source",source,0);
    debug(F110,"zcopy destination",s,0);
    /* it's easier to code this way, not faster... */
    if (isdir(destination)) {
	char *q = NULL;
	x = strlen(destination);

	strcpy(p,destination);		/* Directory part */
	if (!ISDIRSEP(*(destination+x-1))) /* Separator, if needed */
	  strcat(p,">");
	zstrip(source,&q);		/* Strip path part from old name */
	strcat(p,q);			/* Concatenate to new directory */
	s = p;
	debug(F110,"zcopy dir",s,0);
    } else
        debug(F110,"zcopy no dir",s,0);

    strcpy(&cvpath,source);
    strcpy(&suffix,"");
    status = 0;
    s$expand_path(&cvpath,&suffix,&cvsrc,&status);
    if (status != 0) {
        debug(F101,"zcopy failed expand src","",status);
	return(-1);
    }

    strcpy(&cvpath,s);
    s$expand_path(&cvpath,&suffix,&cvdest,&status);
    if (status != 0) {
        debug(F101,"zcopy failed expand dest","",status);
	return(-1);
    }

    switches = 2; /* OVERWRITE */
    strcpy(&caller,"kermit");
    s$copy_file(&cvsrc,&cvdest,&caller,&switches,&status);
    if (status != 0) {
        debug(F101,"zcopy failed s$copy_file","",status);
	return(-1);
    }

    return(0);
}


/*  Z S A T T R */
/*
 Fills in a Kermit file attribute structure for the file which is to be sent.
 Returns 0 on success with the structure filled in, or -1 on failure.
 If any string member is null, then it should be ignored.
 If any numeric member is -1, then it should be ignored.
*/
int
zsattr(xx) struct zattr *xx; {
    long k;
    CV(256) path;
    CV(256) src_path;
    CV(32) suffix;
    FILE_STATUS_STRUCT finfo;
    short status;
    int x;
    char *cp;
    static char  creator[67];
    static char  cdate[20];
    struct tm *tp;

    k = iflen % 1024L;			/* File length in K */
    if (k != 0L) k = 1L;
    xx->lengthk = (iflen / 1024L) + k;
    xx->type.len = 0;			/* File type can't be filled in here */
    xx->type.val = "";

    if (*nambuf) {
        debug(F110,"zsattr checking",nambuf,0);

	strcpy (&src_path, nambuf);
	strcpy (&suffix, "");
	s$expand_path (&src_path, &suffix, &path, &status);
	if (status) {
	    debug(F101,"zsattr s$expand_path status","",status);
	    return -1; /* doesn't exist or cannot be accessed */
	}

	finfo.version = FILE_STAT_VERSION_5;
	s$get_file_status (&path, &finfo, &status);
	if (status) {
	    debug(F101,"zsattr s$get_file_status status","",status);
	    return -1;
	}

	tp = localtime ((const time_t *) &finfo.date_time_modified);
	if (NULL != tp) {
	    sprintf(cdate, "%04d%02d%02d %02d:%02d:%02d", tp->tm_year + 1900,
		tp->tm_mon + 1, tp->tm_mday, tp->tm_hour, tp->tm_min,
		tp->tm_sec);
	    xx->date.val = cdate;	/* File creation date */
	    xx->date.len = (int)strlen(xx->date.val);
	}
	else {
	    xx->date.val = "";	/* File creation date */
	    xx->date.len = 0;
	}

	strcpy (creator, &finfo.author);
	cp = strchr (creator, '.');
	*cp++ = '\0';

	/* (person_name (file_info author)) */
	xx->creator.val = creator;		/* File creator */
	xx->creator.len = strlen (creator);

	/* (group_name (file_info author)) */
	xx->account.len = strlen (cp);		/* File account */
	xx->account.val = cp;

	xx->recfm.len = 0;			/* Record format */
	xx->recfm.val = "";

    } else {
	xx->date.len = 0;
	xx->date.val = "";

	xx->creator.len = 0;		/* File creator */
	xx->creator.val = "";

	xx->recfm.len = 0;			/* Record format */
	xx->recfm.val = "";

	xx->account.len = 0;		/* File account */
	xx->account.val = "";
    }
    xx->area.len = 0;			/* File area */
    xx->area.val = "";
    xx->password.len = 0;		/* Area password */
    xx->password.val = "";
    xx->blksize = -1L;			/* File blocksize */
    xx->xaccess.len = 0;		/* File access */
    xx->xaccess.val = "";
    xx->encoding.len = 0;		/* Transfer syntax */
    xx->encoding.val = 0;
    xx->disp.len = 0;			/* Disposition upon arrival */
    xx->disp.val = "";
    xx->lprotect.len = 0;		/* Local protection */
    xx->lprotect.val = "";
    xx->gprotect.len = 0;		/* Generic protection */
    xx->gprotect.val = "";
    xx->systemid.len = 2;		/* System ID */
    xx->systemid.val = "MV";		/* MISC, VOS */
    xx->sysparam.len = 0;		/* System-dependent parameters */
    xx->sysparam.val = "";
    xx->length = iflen;			/* Length */
    return(0);
}

/* Z F C D A T  --  Get file creation date */
/*
  Call with pointer to filename.
  On success, returns pointer to creation date in yyyymmdd hh:mm:ss format.
  On failure, returns pointer to null string.
*/
char *
zfcdat(name) char *name; {
    static char  cdate[20];
    CV(256) path;
    CV(256) src_path;
    CV(32) suffix;
    FILE_STATUS_STRUCT finfo;
    short status;
    struct tm  *tp;

    debug(F110,"zfcdate called",name,0);
    strcpy (&src_path, name);
    strcpy (&suffix, "");
    s$expand_path (&src_path, &suffix, &path, &status);
    if (status) {
	debug(F101,"zfcdate s$expand_path status","",status);
	return ""; /* error */
    }

    finfo.version = FILE_STAT_VERSION_5;
    s$get_file_status (&path, &finfo, &status);
    if (status) {
	debug(F101,"zfcdate s$get_file_status status","",status);
	return "";
    }

    tp = localtime ((const time_t *) &finfo.date_time_modified);
    if (NULL == tp)
	return("");

    sprintf(cdate, "%04d%02d%02d %02d:%02d:%02d", tp->tm_year + 1900,
	tp->tm_mon + 1, tp->tm_mday, tp->tm_hour, tp->tm_min,
	tp->tm_sec);

    return cdate;
}

/* Z S T I M E  --  Set creation date for incoming file */
/*
 Call with:
 f  = pointer to name of existing file.
 yy = pointer to a Kermit file attribute structure in which yy->date.val
      is a date of the form yyyymmdd hh:mm:ss, e.g. 19900208 13:00:00.
 x  = is a function code: 0 means to set the file's creation date as given.
      1 means compare the given date with the file creation date.
 Returns:
 -1 on any kind of error.
  0 if x is 0 and the file date was set successfully.
  0 if x is 1 and date from attribute structure <= file creation date.
  1 if x is 1 and date from attribute structure > file creation date.
*/

int
zstime(f,yy,x) char *f; struct zattr *yy; int x; {
    int r = -1;				/* return code */
    CV(256) path;
    CV(256) src_path;
    CV(32) suffix;
    FILE_STATUS_STRUCT finfo;
    short status;
    struct tm  *tp;
    struct tm  mytm;
    char fdate[20];
    char adate[32];
    CV(32) cvtime;
    int dlen; /* length of date part */
    time_t file_times[4]; /* created, used, modified, saved */
    time_t idate;
    char *cp;
    int scanval;
    time_t now;

    now = time(NULL);
    debug(F111,"zstime called, x",f,x);
    if (NULL == yy) {
	debug(F100,"zstime called with NULL attr struct","",0);
	return r;
    }
    if (yy->date.len > 17) { /* too long */
	debug(F111,"zstime bad date",yy->date.val,yy->date.len);
	return r;
    }
    strncpy (adate, yy->date.val, yy->date.len);
    adate[yy->date.len] = '\0';
    debug(F111,"zstime attr date",adate,yy->date.len);

    memset (&mytm, 0, sizeof mytm); /* clear it out initially */
    
    /* "normalize" attribute date string */
    if (NULL != (cp = strchr (adate, ' '))) {	/* is time present? */
  	dlen = (int)(cp - adate);
	cp++; /* now get time, let sscanf deal with missing seconds */
	scanval = sscanf(cp,"%2d:%2d:%2d",
	    &mytm.tm_hour, &mytm.tm_min, &mytm.tm_sec);
        debug(F111,"   sscan time",cp,scanval);
	if (scanval != 2 && scanval != 3)
	    return (-1);		/* this is an error */
    }
    else
	dlen = strlen (adate);
 
    if (dlen == 8) { 		/* yyyymmdd */
	scanval = sscanf(adate,"%4d%2d%2d",
	    &mytm.tm_year, &mytm.tm_mon, &mytm.tm_mday);
	debug(F111,"   sscan long date",adate,scanval);
	if (scanval != 3)
	    return (-1);
	mytm.tm_year -= 1900;
    }
    else if (dlen == 6) {	/* yymmdd */
	sscanf(adate,"%2d%2d%2d",
	    &mytm.tm_year, &mytm.tm_mon, &mytm.tm_mday);
	debug(F111,"   sscan short date",adate,scanval);
	if (scanval != 3)
	    return (-1);
	if (mytm.tm_year < 80) 			/* VOS dates start at 1980 */
	    mytm.tm_year += 100;		/* UNIX could be 1975...   */
    }
    else {					/* error */
	debug(F110,"zstime bad date",adate,0);
	return (-1);
    }

    mytm.tm_mon -= 1;

    strcpy (&src_path, f);
    strcpy (&suffix, "");
    s$expand_path (&src_path, &suffix, &path, &status);
    if (status) {
	debug(F101,"zstime s$expand_path status","",status);
	return (-1); /* error */
    }

    finfo.version = FILE_STAT_VERSION_5;
    s$get_file_status (&path, &finfo, &status);
    if (status) {
	debug(F101,"zstime s$get_file_status status","",status);
	return (-1);
    }
 
    if (1 == x) { /* compare times only */
	tp = localtime ((const time_t *) &finfo.date_time_modified);
	if (NULL == tp)
	    return (-1);

	sprintf(fdate, "%04d%02d%02d %02d:%02d:%02d", tp->tm_year + 1900,
	    tp->tm_mon + 1, tp->tm_mday, tp->tm_hour, tp->tm_min,
	    tp->tm_sec);

        debug(F111,"zstime file mod date",fdate,finfo.date_time_modified);

	sprintf(adate, "%04d%02d%02d %02d:%02d:%02d", mytm.tm_year + 1900,
	    mytm.tm_mon + 1, mytm.tm_mday, mytm.tm_hour, mytm.tm_min,
	    mytm.tm_sec);

        debug(F110,"zstime adate",adate,0);

	if (strcmp (adate, fdate) > 0)
	    r = 1;
	else
	    r = 0;
 	debug(F101,"zstime compare","",r);
	return r;
    }

    /* set date on existing file */
    sprintf (adate,"%02.2ld-%02.2ld-%02.2ld %02.2ld:%02.2ld:%02.2ld",
	mytm.tm_year, mytm.tm_mon + 1, mytm.tm_mday,
	mytm.tm_hour, mytm.tm_min, mytm.tm_sec);

    strcpy (&cvtime, adate);
    s$cv_to_int_date_time (&cvtime, &idate, &status);
    if (status) {
	debug(F111,"zstime s$cv_to_int_date_time status",adate,status);
	return (-1);
    }

    file_times[0] = idate;			/* time created */
    file_times[1] = now;			/* time used */
    file_times[2] = idate;			/* time modified */
    file_times[3] = 0;				/* time saved */

    s$set_object_times (&path, &file_times[0], &status);
    if (status) {
	debug(F111,"zstime s$set_object_times status",adate,status);
	return (-1);
    }

    s$set_expiration_date (&path, &now, &status);
    if (status) {
	debug(F111,"zstime s$set_expiration_date status",adate,status);
	return (-1);
    }

    return(0);
}

/* Find initialization file. */

int
zkermini() {
/*  nothing here for VOS.  This function added for benefit of VMS Kermit.  */
/*  VOS always uses "(home_dir)>start_up.kermit" 			   */
    return(0);
}

#ifndef NOFRILLS
int
zmail(p,f) char *p; char *f; {		/* Send file f as mail to address p */
/*
  Returns 0 on success
   2 if mail delivered but temp file should not be deleted
  -2 if mail can't be delivered
*/
    char buff[300];
    int r;
    int len;

    len = sprintf (buff, 
	"!send_mail '%s' 'Kermit:%s' -priority '%s' -letter_path '%s'",
	p, f, "normal", f);
    debug(F110,"zmail",buff,len);
    r = zsyscmd (buff);
    if (r != 0) {
	debug(F101,"zmail call to zsyscmd","",r);
	return(-2);
    }

    return 0;
}
#endif /* NOFRILLS */

#ifndef NOFRILLS
int
zprint(p,f) char *p; char *f; {		/* Print file f with options p */
/*
  Returns 0 on success
   3 if file is printed but temp file can't be deleted
  -3 if file can't be printed
*/
    char buff[300];
    int r;
    int len;

    len = sprintf (buff, "!print -delete %s %s", f, p);
    debug(F110,"zprint",buff,len);
    r = zsyscmd (buff);
    if (r != 0)
	return(-3);

    /* the spooler will delete the file after it is printed */
    /**/ /* should this be 3? check caller */
    return 0;
}
#endif /* NOFRILLS */

/* S H X P A N D  -- expand star names appropriate to the user's shell.
   In VOS, use the s$expand_star command, which is the same as the command
   processor uses.  It is also much easier than doing it our self.
*/
int
shxpand(pat,namlst,len) char *pat, *namlst[]; int len; {
    char *p, *q;			/* Workers */
    int i, x, retcode; char c;		/* ... */
    CV(256) relpath;
    CV(32)  suffix;
    CV(256) fullpath;
    char dirnam[256];
    short status;
    struct {
	short version;
	struct {
	    CV(32) objnam;
	    short	     objtyp;
	} entries[1];
    } *expinfo = NULL;
    short switches;
    short maxnbr;
    short nbrmatch;
    short dummy;

    for (i = 0; i < oldmtchs; i++)	/* Free previous file list */
      free(namlst[i]);
    
    oldmtchs = 0;
    strcpy (&relpath, pat);
    strcpy (&suffix, "");		/* don't append a suffix */
    s$expand_path (&relpath, &suffix, &fullpath, &status);
    if (status) {
	debug(F111,"shxpand expand_path failed",pat,status);
	return 0;
    }

    strcpy (dirnam, &fullpath);
    *(strrchr (dirnam, DIRSEP) + 1) = '\0'; /* cut it off after last dir */

    switches = 1; /* FILES, no dirs, no links, don't sort */
    maxnbr = 0;   /* don't want names, just how many */
    dummy = 1;	  /* looks like expinfo->version, with no data part */
    s$expand_star (&fullpath, &switches, &maxnbr, &nbrmatch, &dummy, &status);
    if (status) {
	debug(F111,"shxpand starmatch 1 failed",pat,status);
	return 0;
    }

    debug(F111,"shxpand found matches",pat,nbrmatch);
    if (0 == nbrmatch) /* aren't any matches anyway */
	return 0;

    nbrmatch += 10; /* add a little bit */
    if (nbrmatch > MAXWLD)
      nbrmatch = MAXWLD;

    expinfo = malloc (sizeof (*expinfo->entries) * (nbrmatch - 1)
		      + sizeof (*expinfo));
    if (NULL == expinfo) {
	debug(F101,"shxpand expinfo malloc","",(int)expinfo);
	return 0;
    }
    switches = 9; /* FILES, no dirs, no links, SORT */
    maxnbr = nbrmatch;
    expinfo->version = 1;
    s$expand_star (&fullpath, &switches, &maxnbr, &nbrmatch, expinfo, &status);
    if (status) {
	debug(F111,"shxpand starmatch 2 failed",pat,status);
	free(expinfo);
	return 0;
    }

    strcpy (&relpath, dirnam);	/* set up relnam */
    for (i = 0; i < nbrmatch; i++) {
	/* if no dirsep chars, don't put full path in expansion */
        if ((NULL == strchr(pat,'>')) && (NULL == strchr(pat,'<')))
	    strcpy (&fullpath, &expinfo->entries[i].objnam);
	else {
	    strcpy (&fullpath, &relpath); /* faster with CV's */
	    strcat (&fullpath, &expinfo->entries[i].objnam);
	}

	x = (int)strlen(&fullpath);	/* Yes, get length of name */
	q = malloc(x+1);		/* Allocate space for it */
	if (!q) goto shxfin;		/* Fail if space can't be obtained */
	strcpy(q,&fullpath);		/* Copy name to space */

	namlst[i] = q;		/* Copy pointer to name into array */
	if (i >= len) goto shxfin;	/* Fail if too many */
    }
    retcode = i;			/* Return number of matching files */

shxfin:					/* Common exit point */

    oldmtchs = i;			/* Remember how many files */
    free(expinfo);
    return(retcode);
}

/*  W H O A M I  --  Get user's username.  */

/*
  Under UNIX, this is hard to do, and different methods are used on
  different implementations (ATT/BSD/MINIX/etc).  On VOS, it's a gimme.
*/
static char *
whoami () {
    CV(65) uname;
    char realname[66];	

    s$get_user_name (&uname);
    strcpy (realname, &uname);
    return(realname);
}

/*  T I L D E _ E X P A N D  --  expand ~user to the user's home directory. */

/*  This is not implemented correctly.  If DTILDE is defined, you will get  */
/*  compilation errors.  Tilde expansion is not a VOS concept.              */

char *
tilde_expand(dirname) char *dirname; {
#ifdef DTILDE

#define BUFLEN 257

    struct passwd *user;
    static char olddir[BUFLEN];
    static char oldrealdir[BUFLEN];
    static char temp[BUFLEN];
    int i, j;

    debug(F111,"tilde_expand",dirname,dirname[0]);

    if (dirname[0] != '~')		/* Not a tilde...return param */
      return(dirname);
    if (!strcmp(olddir,dirname)) {	/* Same as last time */
      return(oldrealdir);		/* so return old answer. */
    } else {
	j = (int)strlen(dirname);
	for (i = 0; i < j; i++)		/* find username part of string */
	  if (!ISDIRSEP(dirname[i]))
	    temp[i] = dirname[i];
	  else break;
	temp[i] = '\0';			/* tie off with a NULL */
	if (i == 1) {			/* if just a "~" */
	    user = getpwnam(whoami());	/*  get info on current user */
	} else {
	    user = getpwnam(&temp[1]);	/* otherwise on the specified user */
	}
    }
    if (user != NULL) {			/* valid user? */
	strcpy(olddir, dirname);	/* remember the directory */
	strcpy(oldrealdir,user->pw_dir); /* and their home directory */
	strcat(oldrealdir,&dirname[i]);
	return(oldrealdir);
    } else {				/* invalid? */
	strcpy(olddir, dirname);	/* remember for next time */
	strcpy(oldrealdir, dirname);
	return(oldrealdir);
    }
#else
    return(NULL);
#endif /* DTILDE */
}

/*
  Functions for executing system commands.

  zsyscmd() executes the system command in the normal, default way for
  the system.  In UNIX, it does what system() does.  Thus, its results
  are  always  predictable;  in  VOS, it uses system(), so it is NEVER
  predictable, because system() is one of the weirdest  parts  of  the
  c-runtime.

  zshcmd()  executes  the  command "using the user's preferred shell,"
  which is a meaningless concept under VOS,  so  we  use  zsyscmd  for
  consistency.
*/
int
zsyscmd(s) char *s; {
    int r;
    short status;
    CV(256) msgtext;
    char msg[257];

    debug(F110,"zsyscmd",s,0);
    if (strcmp (s, "login") && 0 != strlen (s)) {
	r = system(s);
	if (0 != r) {
	    debug(F101,"system() returned status","",r);
	}
    }
    else {
	strcpy (&msgtext, "");
	s$clone (&status, &msgtext);
	r = status;
        if (0 != r) {
	    strcpy (msg, &msgtext);
	    debug(F111,"s$clone status",msg,status);
	}
    }

#ifdef COMMENT
    /* changed in edit 002 */
    /* 0 == failure, 1 == success */
    return (0 == r);
#else
    return r;
#endif /* COMMENT */
}

int
zshcmd(s) char *s; {
    debug(F110,"zshcmd",s,0);
    return(zsyscmd(s));
}

/*  I S W I L D  --  Check if filespec is "wild"  */

/*
  Returns 0 if it is a single file, 1 if it contains wildcard characters.
  Note: must match the algorithm used by match(), hence no [a-z], etc.
*/
int
iswild(filespec) char *filespec; {
    char c; int x; char *p;
    if (wildxpand) {
	if ((x = zxpand(filespec)) > 1) return(1);
	if (x == 0) return(0);		/* File does not exist */
	p = malloc(MAXNAMLEN + 20);
	znext(p);
	x = (strcmp(filespec,p) != 0);
	free(p);
	return(x);
    } else {
	while ((c = *filespec++) != '\0')
	  if (c == '*') return(1); /* only '*' allowed in VOS star-names */
	return(0);
    }
}

/*
   Tell if string pointer s is the name of a directory.
   Returns 1 if directory, 0 if not a directory.
*/
int
isdir(s) char *s; {
    int x;
    CV(256) relpath;
    CV(32)  suffix;
    CV(256) fullpath;
    short   status;
    short   type;
    short   chase = 1;

    if (!s) return(0);
    if (!*s) return(0);

    strcpy (&relpath, s);
    strcpy (&suffix, "");		/* don't append a suffix */
    s$expand_path (&relpath, &suffix, &fullpath, &status);
    if (status) {
	debug(F111,"isdir expand_path failed",s,status);
	return 0;
    }

    s$get_object_type (&fullpath, &chase, &type, &status);
    
    debug(F111,"isdir type",s,type);
    return( (type == 2) ? 1 : 0 );  /* 1=File, 2=Dir, 3=Link */
}

#ifdef CK_MKDIR
/* Some systems don't have mkdir(), e.g. Tandy Xenix 3.2.. */

/* Z M K D I R  --  Create directory(s) if necessary */
/*
   Call with:
    A pointer to a file specification that might contain directory
    information.  The filename is expected to be included.
    If the file specification does not include any directory separators,
    then it is assumed to be a plain file.
    If one or more directories are included in the file specification,
    this routine tries to create them if they don't already exist.
   Returns:
    0 on success, i.e. the directory was created
   -1 on failure to create the directory
*/
int
zmkdir(path) char *path; {
    char *xp, *tp, c;
    int x;
    CV(256) cv_path;
    short   status;

    x = strlen(path);
    debug(F111,"zmkdir",path,x);
    if (x < 1 || x > MAXPATH)		/* Check length */
      return(-1);
    if (!(tp = malloc(x+1)))		/* Make a temporary copy */
      return(-1);
    strcpy(tp,path);

    xp = tp;
    if (ISDIRSEP(*xp))			/* Don't create root directory! */
      xp++;

    /* Go thru filespec from left to right... */

    for (; *xp; xp++) {			/* Create parts that don't exist */
	if (!ISDIRSEP(*xp))		/* Find next directory separator */
	  continue;
	c = *xp;			/* Got one. */
	*xp = '\0';			/* Make this the end of the string. */
	if (!isdir(tp)) {		/* This directory exists already? */
	    debug(F110,"zmkdir making",tp,0);
	    strcpy (&cv_path, tp);
	    s$create_dir (&cv_path, &status);
	
	    if (status != 0) {
		debug(F101,"zmkdir failed, status","",status);
		free(tp);		/* Free temporary buffer. */
		return(-1);		/* Freturn failure code. */
	    }
	}
	*xp = c;			/* Replace the separator. */
    }
    free(tp);				/* Free temporary buffer. */
    return(0);				/* Return success code. */
}
#endif /* CK_MKDIR */

int
zrmdir(path) char *path; {
    CV(256) cv_path;
    CV(32)  idunno;
    short status;
    short flags;

    flags = 0;
    status = 0;
    strcpy(&idunno, "");
    strcpy(&cv_path, path);
    s$delete_dir(&cv_path, &idunno, &flags, &status);	
    debug(F111,"zrmdir", path, status);

    return(status == 0);
}


/* Z F S E E K  --  Position input file pointer */
/*
   Call with:
    Long int, 0-based, indicating desired position.
   Returns:
    0 on success.
   -1 on failure.
*/
#ifndef NORESEND
int
#ifdef CK_ANSIC
zfseek(long pos)
#else
zfseek(pos) long pos;
#endif /* CK_ANSIC */
/* zfseek */ {
    short port;
    short position_control;
    short status;
    long  nbr_records;
    int   rv; /* return value */
    VFILE *vp = fp[ZIFILE];

    debug(F101,"zfseek","",pos);
    if (NULL != vp) {
	port = vp->port;
	position_control = POS_BEGINNING_OF_FILE;
	nbr_records = 0;
	status = 0;

	s$seq_position (&port, &position_control, &nbr_records, &status);
	if (status == 0) {
	    port = vp->port;
	    position_control = POS_NUM_BYTES_FORWARD;
	    nbr_records = pos;
	    status = 0;

	    s$seq_position (&port, &position_control, &nbr_records, &status);
	}
    } else {
        status = 1;
    }

    rv = (status == 0) ? 0 : -1;
    return(rv);
}
#endif /* NORESEND */

struct zfnfp *
zfnqfp(fname, buflen, buf)  char * fname; int buflen; char * buf; {
    int x = 0, y = 0;
    char * xp;
    static struct zfnfp fnfp;
    CV(256) rel;
    CV(256) abs;
    CV(32) suffix = "";
    short status;

    if (!fname)
      return(NULL);

    /* initialize the data structure */
    fnfp.len = buflen;
    fnfp.fpath = buf;
    fnfp.fname = NULL;

#ifdef DTILDE
        if (*fname == '~') {
	    xp = tilde_expand(fname);
	if (*xp)
	    fname = xp;
	}
#endif /* DTILDE */

    strcpy(&rel, fname);
    strcpy(&abs, "");
    strcpy(&suffix, "");
    status = 0;

    s$expand_path(&rel, &suffix, &abs, &status);
    debug(F111,"zfnqfp",fname,status);
    if(status)
	return(NULL);

    if(strlen(&abs)<buflen) {
	strncpy(buf,&abs,buflen);
	x = strlen(buf);
	while(buf[x]!='>')		/* absolute path must have one */
	    x--;
	fnfp.fname = &buf[x];
	return(&fnfp);
    }

    return(NULL);
}
