#include <stdio.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <errno.h>
#include <io.h>

/*
 * rm.c - unix remove utility - expands wildcards during deletes, and
 * allows multiple datasets on the command line
 */

static	char *Program [] ={ "rm - remove files v1.r1.s0 - va/psj@" };
static	char *Usage = "usage: rm [-cfnt?] file [file...]\n";

#define FALSE	0
#define TRUE	1

int chmod(char *, int);
int unlink(const char *);

int errno;

int main(int argc, char * argv[])
{
    short unsigned int siOption;
    unsigned register int riFiles = 0;
    unsigned register int riTries = 0;

    short int	siType	= FALSE;    /* type names */
    short int	siCount = FALSE;    /* count files */
    short int	siForce = FALSE;    /* force indicator */
    short int	siNACK	= FALSE;    /* no action flag */

    if (argc < 2)
	_exit(fprintf(stderr, "%s", Usage) + 0x10);

    while(--argc > 0) {
	++argv;     /* find first argument */
	if((siOption = **argv) == '-' || siOption == '/')
	    while(siOption = *(++(*argv))) {	/* process flag */
		switch(toupper(siOption)) {
		    case 'C':
			siCount = TRUE;
			break;
		    case 'F':
			siForce = TRUE;
			break;
		    case 'T':
			siType = TRUE;
			break;
		    case 'N':
			siNACK = siType = TRUE;
			break;
		    case '?':
			printf("rm: options summary\n\n\t"
			    "-c count files and show total when done\n\t"
			    "-f force R/O files to R/W before delete\n\t"
			    "-n show files - deletion not performed\n\t"
			    "-t type file names after deletion\n\n");
			_exit(0x00);

		    default:
			fprintf(stderr, "rm: illegal option %c\n", siOption);
		}   /* switch closed */
	    }	/* while closed */
	else {	/* now past flags - process file */
	    if(siForce && chmod(*argv, S_IREAD|S_IWRITE)) {
		fprintf(stderr, "rm: can't force %s - not removed\n", *argv);
		continue;
	    }
	    ++riTries;
	    siForce = FALSE;
	    if(!siNACK && unlink(*argv))
		switch(errno) {
		    case EACCES:
			fprintf(stderr, "rm: %s  directory or read-only\n",
				    *argv);
			break;
		    case ENOENT:
			fprintf(stderr, "rm: %s  no such file\n", *argv);
			break;
		    default:
			fprintf(stderr, "rm: %s  unknown failure\n", *argv);
		}
	    else {
		++riFiles;
		if(siType)
		    printf("%s ", *argv);
		if(!siNACK)
		    printf("removed");
		putchar('\n');
	    }	/* file deleted without a problem */
	}   /* else past flags */
    }	/* while not more flags ... */

    if (siCount)
	if(riTries)
	    if(riFiles)
		printf("\n\t%u file(s) removed\n", riFiles);
	    else
		printf("\n\tremoved none of %u file(s)\n", riTries);
	else
	    printf("rm: none matched\n");
}
