/*\c
* cvt_rm.c - simple implementation of rm to delete multiple files.
* This file only deletes all files supplied by the command line; the
* return value is always 0/1 (success).
*
* If the first character of an argument is `+', this argument is
* considered to be a file containing  a list of files to delete. This
* feature is added to avoid too long command lines for M\$DOG \& Co.
*
* For VMS, files beginning with `sys$share:' are not deleted; (this
* entry is used for sys$share:vaxcrtl, and it should not be deleted!!)
*/

#include <stdio.h>
#include <stdlib.h>
#if VMS
#  include <string.h>
#  include <descrip.h>
  int delete_file(char *file,int all);
  int lib$delete_file();
#else
#  define delete_file(file,all) unlink(file)
#endif

main(int argc, char **argv)
{
  int i;
  FILE *input;
  char *buffer,*ptr,*ptr1;

  buffer=(char *)malloc(1024);
  for(i=1;i<argc;i++){
     if(*argv[i]=='+' || *argv[i]=='@'){
        strcpy(buffer,argv[i]+1);
#if VMS
        for(ptr=buffer;*ptr;ptr++)if(*ptr==';')*ptr=0;   /* no version number!! */
#endif
        if((input=fopen(buffer,"r"))!=NULL){
           while(fscanf(input,"%s",buffer)==1)delete_file(buffer,1);
           fclose(input);
           if(*argv[i]=='+'){
              strcpy(buffer,argv[i]+1);
              delete_file(buffer,1);
           }
        }
     }
     else{
#if VMS
        for(ptr=argv[i],ptr1=buffer;*ptr;ptr++){
           if(*ptr==','){
              *ptr1=0;
              delete_file(buffer,0);
              ptr1=buffer;
           }
           else
              *ptr1++= *ptr;
        }
        if(ptr1>buffer){
           *ptr1=0;
           delete_file(buffer,0);
        }
#else
        delete_file(argv[i],0);
#endif
    }
  }
#if VMS
  return 1;
#else
  return 0;
#endif
}

#if VMS
int delete_file(char *file,int all)
{
  $DESCRIPTOR(d_file,"");
  char *ptr,*ptr1,filebuffer[256];

  if(!strncmp("sys$share:",file,10))return;   /* don't remove shared libraries from opt file! */
  strcpy(filebuffer,file);
  for(ptr=filebuffer;*ptr && *ptr++!='.';);
     /* for extensions .obj/obj_x, .exe/.exe_x or .opt/.opt_x use .obj*;*,
      * .exe*;* and .opt*;* */
  if(*ptr=='o' && ((*(ptr+1)=='b' && *(ptr+2)=='j')
      || (*(ptr+1)=='p' && *(ptr+2)=='t'))
      || *ptr=='e' && *(ptr+1)=='x' && *(ptr+2)=='e'){
     *(ptr+3)='*';
     *(ptr+4)=0;
     for(ptr1=file;*ptr1 && *ptr1!=';';ptr1++);
     if(*ptr1)all=1;
  }
  if(all){
     for(ptr=filebuffer;*ptr && *ptr!=';';ptr++);
     *ptr++=';';
     *ptr++='*';
     *ptr=0;
  }
  d_file.dsc$w_length=strlen(filebuffer);
  d_file.dsc$a_pointer=filebuffer;
  return lib$delete_file(&d_file);
}
#endif