/*  Amiga-ForEach V1.4  (c)1993 Richard A Shipton         */
/*  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~         */
/*  This program is public domain.  Do what you want with */
/*  it, but just don't claim you wrote it!                */

/*  Include header files  */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.h>

/*  Prototypes  */

void main(int argc, char **argv);
void addarg(char *argument);

/*  Global variables  */

char filenames[16384],*files[2048],command[255];
char _drive[FNSIZE],_dir[FMSIZE],_node[FNSIZE],_ext[FNSIZE];
int  files_found,current_file;

void main(argc,argv)
int argc;
char **argv;
{
  int parse_arg;
  
  if(argc<3)
  {
    if((argc==2) && (!strcmp(argv[1],"?")))
    {
      printf("Amiga-ForEach V1.4  (c)1993 R.A Shipton\n");
      printf("-----------------------------------------\n\n");
      printf("Usage:  foreach <Pattern> <Command...>\n\n");
      
      printf("Filename Substitutes:\n");
      printf("  ! - Substitute Filename\n");
      printf("  @ - Substitute Filename Without Extension(s)\n");
      printf("  £ - Substitute -Just- Filename (No Path/Directory)\n");
      printf("  # - Same as \"£\", But Without Extension(s)\n\n");
      printf("Eg.  foreach #?.icon rename ! @.info\n");
    }
    else
      printf("USAGE: %s <Pattern> <Command...>\n",argv[0]);

    exit(0);
  }
  
  /*  Build and check file index  */
  
  files_found=getfnl(argv[1],filenames,sizeof(filenames),0);
  if(files_found==0)
    exit(1);
  
  if(strbpl(files,2048,filenames) != files_found)
    exit(2);
  else
    strsrt(files,files_found);

  /*  Everything's O.K - Process the file list  */
  
  for(current_file=0;current_file<files_found;current_file++)
  {
    /*  Build a command line  */
    
    strcpy(command,"");
    strsfn(files[current_file],_drive,_dir,_node,_ext);
    
    for(parse_arg=2;parse_arg<argc;parse_arg++)
    {
      addarg(argv[parse_arg]);
      strcat(command," ");
    }
  
    /*  Execute the command  */
    
    system(command);
  }

  exit(0);
}

/*  Add an argument to the command  */

void addarg(argument)
char *argument;
{
  char tmpfn[FMSIZE];
  unsigned int ch;
  
  for(ch=0;argument[ch]!='\0';ch++)
  {
    switch(argument[ch])
    {
      case '!':
        strcat(command,files[current_file]);
        break;
    
      case '@':
        strmfn(tmpfn,_drive,_dir,_node,NULL);
        strcat(command,tmpfn);
        break;

      case '£':
        strmfn(tmpfn,NULL,NULL,_node,_ext);
        strcat(command,tmpfn);
        break;
      
      case '#':
        strcat(command,_node);
        break;

      default:
        strncat(command,&argument[ch],1);
        break;
    }
  }
}
