#include <stdio.h>

#define TRUE (1)
#define FALSE (0)

struct gstr *mesglist;

struct gstr
{
  char *group, *last;
  int unread;
  struct gstr *next;
};

struct twoway
{
  FILE *sock_rd, *sock_wt;
};

/* CheckGroup takes a group and finds the first available unread
 * article in it, and stores this number in the last field of the
 * group's structure.
 */

void CheckGroup(sock_rw)
     struct twoway *sock_rw;
{
  struct gstr *tptr, *otptr;
  FILE *sock_rd, *sock_wt;
  char *dump, first[16], last[16];
  static char *out = NULL;
  int status, fill, tlast;
  void PutLine(), CheckError();
  char *GetLine();

  sock_rd = sock_rw->sock_rd;
  sock_wt = sock_rw->sock_wt;

  tptr = mesglist;
  otptr = NULL;
  while (tptr != NULL)
    {
      if (!tptr->unread)
	{
	  tptr = tptr->next;
	  continue;
	}
      if (out == NULL)
	{
	  out = (char *)malloc(sizeof(char) * (strlen("group ")
					       + strlen(tptr->group)
					       + 3));
	  if (out == NULL)
	    CheckError("Nmsgs: CheckGroup: malloc");
	}
      else
	{
	  fill = strlen("group ") + strlen(tptr->group) + 3;
	  if (fill > strlen(out))
	    {
	      out = (char *)realloc((char *)out, fill);
	      if (out == NULL)
		CheckError("Nmsgs: CheckGroup: malloc");
	    }
	}
      sprintf(out, "group %s\r\n", tptr->group);
      PutLine(out, sock_wt);
      dump = GetLine(sock_rd);
      sscanf(dump, "%d", &status);
      if (status >= 400)
	{
	  printf("%s does not exist.\n", tptr->group);
	  free(tptr->group);
	  free(tptr->last);
	  if (otptr != NULL)
	    {
	      otptr->next = tptr->next;
	      tptr = otptr->next;
	    }
	  else
	    tptr = mesglist = mesglist->next;
	  free(tptr);
	  continue;
	}
      sscanf(dump, "%d %d %s %s", &fill, &fill, first, last);
      tlast = atoi(tptr->last);
      if (atoi(first) > 0)
	{
	  if (atoi(last) < tlast)
	    tptr->unread = FALSE;
	  if (atoi(first) > tlast)
	    strcpy(tptr->last, first);
	}
      otptr = tptr;
      tptr = tptr->next;
    }
}
