#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <errno.h>
#include <sys/msg.h>

long que_id;
typedef struct
{
  long mtype;
  char mtext[2048];
} message;
message  msg1;
struct msqid_ds buf;
int que_size; 
int iret;


/* make queue */
int questart(msg_qu_key)
key_t *msg_qu_key;
{
  if((que_id = msgget(*msg_qu_key,0777  | IPC_CREAT | IPC_EXCL))==-1)
    {
      if(errno==EEXIST) return 1;
      perror("queuestart: Cannot create message queue\n");
      exit(1);
    };
  return 0;
}

/* connect to queue */
queconn(msg_qu_key)
key_t *msg_qu_key;
{
  if((que_id = msgget(*msg_qu_key,0666))==-1)
	  {
	    perror("queueconn: Cannot locate message queue");
	    exit(1);
	  };
  iret=msgctl(que_id,IPC_STAT,&buf);
  if(iret){
    perror("queuesize error: ");
  };
  que_size=buf.msg_qbytes;
  if(que_size>2048) que_size=2048;
#ifdef DEBUG
  printf("queue size %d\n",que_size);
#endif
}

questop()
{
  if ( msgctl(que_id,IPC_RMID,0)==-1)
    perror("cleanup routine : ");
}

int queread(s,msgtype)
char *s;
int msgtype;
{  
  if(msgrcv(que_id,&msg1,sizeof(msg1.mtext),msgtype,0) == -1) {
    perror("queueread: Not able to receive the message"); 
    return 0;
  };
  strcpy(s,msg1.mtext);
  return 1;
}


int geturl(src,targ)
char *src,*targ;
{
  key_t msgqid=3075;
  char s1[1024];

  if(strlen(src)){
    strcpy(s1,"netscape -remote 'openURL(");
    strcat(s1,src);
    strcat(s1,")'");
    if(system(s1)){
      strcpy(s1,"netscape \"");
      strcat(s1,src);
      strcat(s1,"\" &");
      system(s1);
    };
  }
  if(questart(&msgqid)){fprintf(stderr,"Queue exists already.\n");return -1;};
  queconn(&msgqid);
  fprintf(stderr,"Waiting for URL from browser...\n");
  if(!queread(targ,10)){
    fprintf(stderr,"Error in reading queue, url= %s.\n",src);return -1;
  };
  questop();
  return 0;
}

#ifdef MAINPROGRAM
main(argc,argv)
int argc;
char *argv[];
{
  char t[1024];
  printf("%d --- %s\n",geturl("",t),t);
}
#endif
