#include	<stdio.h>
#include	<errno.h>

#define		R	0
#define		W	1
#define		RW	2
#define		BUFSZE	7
#define		PATHSZE 256
#define		NODESZE sizeof(struct node)
#define		NODEPTR struct node *

/* Define FutureNet types */
#define		TEOF	0
#define		TTEXT	3
/* Define FutureNet attributes */
#define		ALOC	2

struct node
{
   long index;
   NODEPTR next;
};

error(msg)
char msg[];
{
   fprintf(stderr,"Error # %d - %s\n",errno,msg);
   exit(1);
}

main(argc,argv)
int  argc;
char *argv[];
{
NODEPTR root = NULL;
NODEPTR cur  = NULL;
int  fd,
     nsymb = 0,
     nread;
long nblocks = 0;
char buf[BUFSZE],
     infile[PATHSZE],
     page = 'A';

/* Check for proper usage and print header */
   fprintf(stdout,"RENUMBER: version 1.0 (c) ATARI CORPORATION.\n\n");
   if (argc == 1)
   {
      fprintf(stderr,"Usage: renum [-p#] drawing [[-p#] drawing ...]");
      exit(1);
   }

/* Scan across command line for drawings                   */

   for (argv++ ;argc > 1; argc--, argv++)
      if ((*argv)[0] == '-')
         page = (*argv)[2];
      else
      {

/* Create filename by checking for a dot extension.  If none, add ".dwg" */
         strcpy(infile,*argv);
         if (strchr(infile,'.') == NULL)
            strcat(infile,".dwg");

         if ((fd = open(infile,R)) == -1)
            error("occurred while opening an input file.");

         fprintf(stdout,"Scanning page %c ... ",(page=toupper(page)));

         for(root = NULL, nsymb = 0, nblocks = 0;
             (nread = read(fd,buf,BUFSZE)) > 2 && buf[0] != TEOF;
             lseek(fd,(nblocks += (long)buf[1])<<4,0))
         {
            if (buf[0] == TTEXT && buf[2] == ALOC)
            {
	       if (root == NULL)
	          cur = root = (NODEPTR)malloc(NODESZE);
               else
    	       {
	          cur->next = (NODEPTR)malloc(NODESZE);
	          cur = cur->next;
               }
	       if (cur == NULL)
	          error("occured while allocating memory.");
               cur->next = NULL;
	       cur->index = nblocks + 1;
	       nsymb++;
            }
         }

         if (nread == -1)
            error("occured while reading");

         close(fd);
         if ((fd = open(infile,RW)) == -1)
            error("occured while opening a file for output.");

         fprintf(stdout,"Scan complete, %3d symbols found.\n",nsymb);
         for(cur = root; cur != NULL; root=cur,cur=cur->next,free(root))
         {
            lseek(fd,(cur->index)<<4,0);
            sprintf(buf,"P%c%03d",page,nsymb--);
            if (write(fd,buf,6) != 6)
               error("occured while writing.");
         }
         close(fd);
         page++;
      }
}
