/* this is the main go-between. */

/*

Copyright (C) 1995 Andrew Tefft. I liked Henry Spencer's terms so:

        Permission is granted to anyone to use this software for any
        purpose on any computer system, and to redistribute it freely,
        subject to the following restrictions:

        1. The author is not responsible for the consequences of use of
                this software, no matter how awful, even if they arise
                from defects in it.

        2. The origin of this software must not be misrepresented, either
                by explicit claim or by omission.

        3. Altered versions must be plainly marked as such, and must not
                be misrepresented as being the original software.

*/

#include <stdio.h>
#include "child.h"
#include "tkmr.h"
#include "../mr.h"
#include "../patchlevel.h"

void sendandget();
void msg();
void article();
void recv_headers();
void do_article();
void send_filenames();

  FILE *read_wish, *write_wish;
  FILE *read_mr, *write_mr;

main(argc,argv)
     int argc;
     char *argv[];
{
  int i,wishpid,mrpid;
  char result[132],*buf,numstr[32],*article,*buf1;
  int num,size;

  mrpid = start_child(MR_PATH,&read_mr, &write_mr);

  printf("mr started, pid is %d\n",mrpid);

/* wait for : and send a : to add cr after prompt string */

  while ((*result=getc(read_mr)) == 0) ;

  if (*result != ':') {
    fprintf(stderr,"Unexpected response from mr! (%d = %c)\n",*result,*result);
    exit (-1);
  }

  getc(read_mr);
  buf=(char *)malloc(1024);
  sendandget(":\n",buf);

/* now we can start up the wish */
  wishpid = start_child(WISH_PATH,&read_wish,&write_wish);
  printf("wish started, pid is %d\n",wishpid);

/* tell it to fire up mr.tcl */

fprintf(write_wish,"source %s\n",MRTCL_PATH);

fprintf(write_wish,"wm title . \"tkmr %s\"\n",VERSION);

if (argc > 1) {
  msg("Loading initial files...",INFO);
  fprintf(write_wish, "set fname \"");
  for (i=1; i<argc; i++) {
    fprintf(write_wish,"%s",argv[i]);
    if (i < argc-1) fputs(" ",write_wish);
  }
  fprintf(write_wish,"\"\nloadit $fname\n");
}


  if ((buf1 = getenv("TKMR_CUSTOM")) != NULL) {
    fprintf(write_wish,"set cust_string %s\n",buf1);
    for (i=1; i < 8; i++) {
      if (i <= strlen(buf1)) 
	fprintf(write_wish,"set c%d %c\n",i+1,buf1[i]);
      else fprintf(write_wish,"set c%d x\n",i+1);   
    }
  }
    
/* look for output from wish (meaning something happened */
  
  while (1) {
    if (fgets(result,132,read_wish) <=0) exit(0);

/* in here we should see the output from wish and acct accordingly */
    
    fprintf(stderr,"Got from wish: %s\n",result);

    switch ((int)*result) {

    case 'f':
      send_filenames();
      break;
          
    case 'z':
      sendandget(result,buf);
      break;
      
    case 'P':
    case 'p':
      do_article(result);
      break;

    case 'H':
    case 'h':
      recv_headers(result);
      fputs("makeunbusy\n",write_wish);
      break;

    case 'a':
    case 'l':
      if (strlen(result)==2) {
	msg("No file specified",ERROR);
	break;
      }
      sendandget(result,buf);
      if (strlen(result) == 3) strcat(result,DEFAULTMBOX);
      if (strlen(buf)) {
/*	fputs("makeunbusy\n",write_wish); */
	msg(buf,ERROR);
      }
      else {
/*
	fprintf(write_wish,
	      ".message.label configure -foreground black -text \"Loaded file: %s\"\n",
	      result+2);
*/
	sprintf(buf,"Loaded file: %s",result+2);
	msg(buf,INFO);
      }
      break;

    case 's':
    case '/':
      fputs("makebusy \"Working...\"\n",write_wish);
      sendandget(result,buf);
      if (strlen(buf)) msg(buf,ERROR);
      fputs("makeunbusy\n",write_wish);
      break;
 
    case 'c':
    case 'C':
      sendandget(result,buf);
      break;

    default:
      fprintf(stderr,"Unexpected output from wish:\n%s\n",result);
  }
    *result = '\0';

  }

}

/* sends tcl code to pop up an article window. */
/* sorry for this big hunk of tcl here  maybe all but the insert
/* could be put into mr.tcl */

void article(buf,num) 
     char *buf;
     int num;
{
fprintf(write_wish,
"make_artwin %d\n\
.textwin.t insert 1.0 \"F",num);


ffputs(buf,write_wish);
#if 0
fprintf(write_wish,"\"\n\
	.textwin.t mark set insert 0.0\n\
	bind .textwin <Any-Enter> \"focus .textwin.t\"\n");
#endif
fprintf(write_wish,"\"\n\
	bind .textwin <Any-Enter> \"focus .textwin.t\"\n");

}

void recv_headers(result) 
char *result;
{
  char numstr[16];
  int num;
  char *hdrbuf,*p,*p1,*p2;

      sendandget("n\n",numstr);        /* should only do this */
      num=atoi(numstr);    	       /* when loading, but.. */

/* need a better limit here! */
      hdrbuf=malloc(num*200);          /* max size of a header */

      sendandget(result,hdrbuf);

/* first clear the list... */
  fprintf(write_wish,".list.hdrlist delete 0 [ .list.hdrlist size ]\n");
  fprintf(write_wish,".list.hdrlist insert 0 ");
  p=hdrbuf;
/* get one line at a time */

  while ((p1=strchr(p,'\n')) != NULL) {
    *p1 = '\0';

/* if there is a quote or [ we have to escape it */
/* later on I can find a more efficient way to escape */

    if (strchr(p,'[') || strchr(p,'\042') || strchr(p,'\\') || strchr(p,'$')) {
      putc('\042',write_wish);
#if 0
      p2 = p;
      while (*p2) {
	if (*p2 == '\042' || *p2 == '[' || *p2 == '\\' || *p2 == '$') {
	  putc('\\',write_wish);
	}
	putc(*p2++,write_wish);
      }
#endif
      ffputs(p,write_wish);
      fprintf(write_wish,"\" ");
    }
    else fprintf(write_wish,"\"%s\" " ,p);
    p=p1+1;
}
  fprintf(write_wish,"\n");
  free(hdrbuf);
    }


/* this one grabs the first line, mallocs a buffer of the size
   indicated, gets the article text, sends it on to wish. */

void do_article(cmd)
     char *cmd;
{
  int size,artnum;
  char result[133],*buf,*buf1;

  sscanf(cmd,"%c %d ",result,&artnum);

  fprintf(write_mr,"%c %d\n",*result, artnum);

    if (fgets(result,132,read_mr) <=0) exit(0);

    size=atoi(result);
   
  buf=(char *)malloc(size);
  
  buf1=buf;

  while (1) {
    if (fgets(buf1,132,read_mr) <=0) exit(0);
    if (!strncmp(EOM_STRING,buf1,strlen(EOM_STRING))) {
      *buf1 = '\0';
      break; 
    }
#if 0
    fprintf(stderr,"-> %s",buf1);
#endif
    buf1 += strlen(buf1);
  }

  fgets(buf1,132,read_mr) ;  /* get empty line before prompt*/
  fgets(buf1,132,read_mr) ;  /* suck up prompt */
  *buf1 = '\0';
  article(buf+1,artnum);
  
/*
  fprintf(stderr,"*** %s***",buf);
*/

  free (buf);
}

/* sends a command and reads to the next prompt in buffer.
   assumes mr is at a prompt -- it will block waiting for
   some output, and getting two prompts will confuse your program. 
   So this should not be used when there is a possibility of getting
   back something that looks like a prompt but is not. */

void sendandget(cmd,buffer)
     char *cmd, *buffer;
{
  char *result;

  result = buffer;

  fprintf(write_mr,"%s",cmd);

  while (1) {
    if (fgets(result,132,read_mr) <=0) exit(0);
    if (!strncmp(": \n",result,3)) {
      *result = '\0';
      break; /* got prompt */
    }
#if 0
    fprintf(stderr,"-> %s",result);
#endif
    result += strlen(result);
  }
#if 0
  fprintf(stderr,"*** %s***",buffer);
#endif
}

/* sends wish a message, of the indicated type (see tkmr.h) */

void msg(buf,type)
     char *buf;
     int type;
{
/*  fprintf(write_wish,".message.label configure -text \"%s\" -foreground %s\n",
	  buf,msg_colors[type]);
*/
  if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0';
  fprintf(write_wish,"send_message \"%s\" %s\n",buf,msg_colors[type]);
}

/* ffputs: filter fputs (yuck) escapes " [ $  */

ffputs(buf,stream)
     char *buf;
     FILE *stream;
{
  char *p2;

  p2 = buf;
      while (*p2 != NULL) {
	if (*p2 == '\042' || *p2 == '[' || *p2 == '\\' || *p2 == '$') {
	  putc('\\',stream);
	}
	putc(*p2++,stream);
      }
}

void send_filenames() 
{
  char *p;
  char buf1[1024];
    
  fprintf(write_wish,".mboxlist.l delete 0 [.list.hdrlist size]\n");
  fprintf(write_wish,".mboxlist.l insert 0 ");

  fputs("f\n",write_mr);
  fgets(buf1,1023,read_mr);  /*toss*/
  while (fgets(buf1,1023,read_mr) != NULL && (strcmp(buf1,": \n"))) {
    putc('\042',write_wish);
    buf1[strlen(buf1)-1] = '\0';
    ffputs(buf1,write_wish);
  fprintf(write_wish,"\" ");
  
  }
  fprintf(write_wish,"\n");
}
