/* regexp tester for addresses */

#include <stdio.h>
#include "regexp.h"

main() 
{
char *p,from[512],name[512],addr[512],date[512];
struct regexp *exp1,*exp2,*exp3,*exp4;
int r1,r2,r3,r4;


exp1 = regcomp("(.*) <(.*)> (.*$)"); /* name <addr> date */
exp2 = regcomp("(.*) \\((.*)\\) (.*$)");    /* addr (name) date */
exp3 = regcomp("(.*) <(.*)>"); /* name <addr> */
exp4 = regcomp("(.*) \\((.*)\\)$"); /* addr (name) nodate */

while (  gets(from) != NULL) {

  printf("%s\n",from);
/*
  printf("\texp1 %d\t",r1=regexec(exp1,from));
  printf("exp2 %d\t",r2=regexec(exp2,from));
  printf("exp3 %d\t",r3=regexec(exp3,from));
  printf("exp4 %d\n",r4=regexec(exp4,from));
*/
  
  r1=regexec(exp1,from);
  r2=regexec(exp2,from);
  r3=regexec(exp3,from);
  r4=regexec(exp4,from);
  
  if (r3) {   /* name <addr> */
    getit(name,exp3,1);
    getit(addr,exp3,2);
    if (r1) getit(date,exp1,3);
    else date[0]='\0';
  }
  
  else if (r2) { /* addr (name) date */
    getit(name,exp2,2);
    getit(addr,exp2,1);
    getit(date,exp2,3);
    if (date[0]=='(') date[0]='\0';
  }
  else if (r4) { /* addr (name) nodate */
    getit(name,exp4,2); 
    getit(addr,exp4,1);
    date[0]='\0';
  }
  else { /* first word is addr, rest is date */
    name[0]='\0';
    p = strchr(from,' ');
    if (p == NULL) date[0]='\0';
    else {
      strcpy(date,p);
      *p = '\0';
    }
    strcpy(addr,from);
  }
    printf("addr %s, name %s, date %s\n\n",addr,name,date); 
}
}

getit(buf,exp,which)
     char *buf;
     struct regexp *exp;
     int which;
{
  strncpy(buf, exp->startp[which], exp->endp[which]-exp->startp[which]);
  buf[exp->endp[which]-exp->startp[which]] = '\0';
}


