/*
	PAKSE.C		ARCE -> PKUNPAK converter, with sort.

	Copyright 1988, Michael J. Housky
	Released to the Public Domain ... *no* rights reserved.
*/

/*
    Update log:

	Version 1.2, 10 September 1988: Released to public domain.
	Version 1.0, 27 August 1988: First version.
*/

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <errno.h>


/*
	spawn_err:	Decode/print spawn/exec error message.
			Return ERRORLEVEL exit code.
*/

int spawn_err( char*, int );
int spawn_err( pname, err )
    char	*pname;		/* program name */
    int		err;		/* copy of errno */
{
    register int rc;

    switch ( err )
    {
	case ENOENT:
	    printf("Can't find %s in DOS PATH\n",pname);
	    rc = 254;
	    break;
	case ENOMEM:
	    printf("Insufficient memory to load %s\n",pname);
	    rc = 253;
	    break;
	default:
	    printf("Error %d loading %s\n",errno,pname);
	    rc = 252;
	    break;
    }
    return rc;

} /* spawn_err */


/*
	PAKSE.C main program
*/

int main(int,char **);
int main( argc, argv )
    int		argc;
    char	**argv;
{
    register int
		i,j;
    char	*pname;
    char	*order;
    char	pakfile[88];

/* First, identify self and examine paramter: */

    printf("\nPAKSE: ARCE-to-PAKSORT/PKUNPAK v1.2\n");
    
    if ( argc < 2 )
    {
	printf("Usage: PAKSE archive\n");
	return 255;
    }

/* Next, copy archive name and append default filetype, if necessary */

    strncpy(pakfile, argv[1], sizeof(pakfile)-5);
    pakfile[sizeof(pakfile)-5] = '\0';
    i = strlen(pakfile);
    do
    {
	j = pakfile[--i];
	if ( j=='\\' || j==':' || i==0 )
	{
	    strcat(pakfile,".ARC");
	    break;
	}
    } while ( j!='.' && i>0 );

/* First, attempt to sort the archive by date/time/name.ext: */

    pname = "PAKSORT";			/* run PAKSORT first */
    order = "D+T+F+";			/* order by date/time/name.ext */
    printf(">PAKSORT %s %s\n",pakfile,order);
    j = spawnlp( P_WAIT, pname, pname, pakfile, order, NULL );
    if ( j==-1 )			/* if spawn error on PAKSORT */
    {
	spawn_err(pname,errno);
    }
    if ( j )
	printf("Sort failed, rc=%d, attempting extract anyway:\n",j);

/* Now run PKUNPAK to extract files from archive: */

    pname = "PKUNPAK";			/* run PKUNPAK next */
    printf(">PKUNPAK -r %s\n",pakfile);
    j = execlp( pname, pname, "-r", pakfile, NULL );

/* Arrive here on exec trouble: global errno has reason */

    return spawn_err( pname, errno );

} /* main */
