#include "getline.h"
#include "stralloc.h"
#include "substdio.h"
#include "subfd.h"
#include "error.h"
#include "alloc.h"
#include "token.h"

int callback(taaddr)
token_alloc *taaddr;
{
 int i;
 if (!token_readyplus(taaddr,2))
   return -1;
 i = taaddr->len;
 taaddr->len = i + 2;
 taaddr->t[i + 1].type = TOKEN_ATOM;
 taaddr->t[i + 1].s = "{";
 taaddr->t[i + 1].slen = 1;
 while (i > 0)
  {
   taaddr->t[i] = taaddr->t[i - 1];
   --i;
  }
 taaddr->t[0].type = TOKEN_ATOM;
 taaddr->t[0].s = "}";
 taaddr->t[0].slen = 1;
 return 1;
}

stralloc sa = {0};
stralloc buf = {0};
token_alloc taout = {0};
token_alloc taaddr = {0};
token_alloc ta = {0};

void main()
{
 int match;

 while ((getline2(subfdin,&sa,&match,'\n') != -1) && match)
  {
   substdio_puts(subfdout,"original: ");
   substdio_putflush(subfdout,sa.s,sa.len);
   switch (token_parse(&ta,&sa,&buf))
    {
     case -1:
       substdio_putsflush(subfdout,"out of memory\n");
       break;
     case 0:
       substdio_putsflush(subfdout,"illegal\n");
       break;
     default:
       if (token_unparse(&sa,&ta) == -1)
         substdio_putsflush(subfdout,"out of memory\n");
       else
	{
         substdio_puts(subfdout,"respaced: ");
	 substdio_putflush(subfdout,sa.s,sa.len);
	 switch(token_addrlist(&taout,&taaddr,&ta,callback))
	  {
	   case -1:
	     substdio_putsflush(subfdout,"out of memory\n");
	     break;
	   case 0:
	     substdio_putsflush(subfdout,"illegal address\n");
	     break;
	   default:
             if (token_unparse(&sa,&taout) == -1)
	       substdio_putsflush(subfdout,"out of memory\n");
	     else
	      {
               substdio_puts(subfdout,"addrlist: ");
	       substdio_putflush(subfdout,sa.s,sa.len);
	      }
	  }
	}
    }
  }
}
