summaryrefslogtreecommitdiff
path: root/copt/copt.c
blob: 3a183ad5ef3d93e74c5b7bfee66408ea19284bec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
/*
 **************************************************************************
 *
 * Utility program to optimize the output of the BCC compiler
 *
 * Module:  copt.c
 * Purpose: Optimize BCC assembler output
 * Entries: main
 *
 * This program is based on an idea from Christopher W. Fraser.
 *
 **************************************************************************
 *
 * Copyright (C) 1995,1996,1997 Gero Kuhlmann <gero@gkminix.han.de>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
#include "utility.h"
#include "../../headers/general.h"
#include "../../headers/version.h"
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define KEEPCOMMENTS

#define MAXLINE		1024
#ifdef __BCC__
#define HASHSIZE	107
#else
#define HASHSIZE	1999
#endif
#define NOCHAR		'\177'
#define VARNUM		10



/* Struct containing each string of an input file */
struct line_s {
	char          *text;
	struct line_s *prev;
	struct line_s *next;
	int 	       comment_flg;
};


/* Struct containing one rule */
struct rule_s {
	struct line_s *old;
	struct line_s *new;
	struct rule_s *next;
};


/* Hash table to store strings in a space saving way */
struct hash_s {
	char          *text;
	struct hash_s *next;
};



/*
 * Global variables
 */
static struct rule_s *first = NULL;	/* first rule */
static struct rule_s *last = NULL;	/* last rule */
static struct line_s *infile = NULL;	/* list of strings in input file */
static struct hash_s *htab[HASHSIZE];	/* string hash table */
static int hash_init = 0;		/* flag if hash table initialized */
static char *vars[VARNUM];		/* variable table */
static char *progname;			/* program name */



/*
 * Allocate memory and print error if none available
 */
static void *mymalloc(int size)
{
  void *p;

  if ((p = malloc(size)) == NULL) {
	fprintf(stderr, "%s: no memory\n", progname);
	exit(1);
  }
  return(p);
}



/*
 * Insert a string into the hash table. If the string is already in there
 * just return the pointer to that string.
 */
static char *install(char *str, int slen)
{
  struct hash_s *hp;
  char *chkstr;
  char *cp;
  unsigned int hashval;

  /* Clear the hashing table if not already done */
  if (!hash_init) {
	for (hashval = 0; hashval < HASHSIZE; hashval++)
		htab[hashval] = NULL;
	hash_init++;
  }

  /* Get check string */
  if (slen < 0)
	slen = strlen(str);
  chkstr = mymalloc(slen + 1);
  strncpy(chkstr, str, slen);
  chkstr[slen] = '\0';

  /* Determine hashing value of string */
  hashval = 0;
  for (cp = chkstr; *cp; cp++)
	hashval = hashval*75 + *cp;
  hashval %= HASHSIZE;

  /* Check if the string is already in the hashing table */
  for (hp = htab[hashval]; hp != NULL; hp = hp->next)
	if (!strcmp(chkstr, hp->text)) {
		free(chkstr);
		return(hp->text);
	}

  /* String is not in hash table, so create a new entry */
  hp = (struct hash_s *)mymalloc(sizeof(struct hash_s));
  hp->text = chkstr;
  hp->next = htab[hashval];
  htab[hashval] = hp;
  return(hp->text);
}



/*
 * Read one line from input file and skip all blanks at the beginning
 */
static char *readline(FILE *fp)
{
  static char buf[MAXLINE];
  char *cp;

  /* Read line from input file */
  if (fgets(buf, MAXLINE-1, fp) == NULL)
	return(NULL);
  buf[MAXLINE-1] = '\0';

  /* Delete trailing newline */
  if ((cp = strchr(buf, '\n')) != NULL)
	*cp = '\0';

  /* Delete leading white spaces */
  for (cp = buf; *cp && isspace(*cp); cp++) ;
  if (cp != buf && *cp)
	memmove(buf, cp, strlen(cp) + 1);

  return(buf);
}



/*
 * Read a list of input lines. Terminate reading when the 'quit' character
 * has been found in the first column of the input line. All lines with the
 * 'comment' character in the first position will be skipped.
 *
 * If 'havequit' is non-null, then the boolean '*havequit' says whether we
 * saw an input line with the 'quit' character.
 */
static struct line_s *readlist(FILE *fp, int quit, int comment, int *havequit)
{
  struct line_s *lp;
  struct line_s *first_line = NULL;
  struct line_s *last_line = NULL;
  char *cp;

  while ((cp = readline(fp)) != NULL) {
	if (quit != NOCHAR && quit == *cp)
		break;
	if (comment != NOCHAR && comment == *cp)
		if (quit != NOCHAR)
			continue;
	if (*cp == '\0')
		continue;
	lp = mymalloc(sizeof(struct line_s));
	lp->text = install(cp, -1);
	lp->prev = last_line;
	lp->next = NULL;
	lp->comment_flg = (comment != NOCHAR && *cp == comment);
	if (first_line == NULL)
		first_line = lp;
	if (last_line != NULL)
		last_line->next = lp;
	last_line = lp;
  }
  if (havequit)
	*havequit = (cp != NULL);
  return(first_line);
}



/*
 * Read pattern file
 */
static void readpattern(char *rulesdir, char *filename)
{
  static char path[MAXLINE];
  int havequit;
  struct rule_s *rp;
  FILE *fp;

  /* Open pattern file */
  if (rulesdir != NULL)
	sprintf(path, "%s/%s", rulesdir, filename);
  else
	sprintf(path, "%s", filename);
  if ((fp = fopen(path, "r")) == NULL) {
	fprintf(stderr, "%s: can't open pattern file %s\n", progname, path);
	exit(1);
  }

  /* Read every line of the pattern file */
  while (!feof(fp)) {
	rp = (struct rule_s *)mymalloc(sizeof(struct rule_s));
	rp->old = readlist(fp, '=', '#', &havequit);
	rp->new = readlist(fp, '\0', '#', NULL);
	if (rp->old == NULL || !havequit) {
		free(rp);
		break;
	}

/* This put the rules into the table in reverse order; this is confusing *
	rp->next = first;
	first = rp;
	if (last == NULL)
		last = rp;
*/
	rp->next = NULL;
	if (last) {
		last->next = rp;
		last = rp;
	} else {
		first = last = rp;
	}

  }

  /* Close pattern file */
  (void)fclose(fp);
}



/*
 * Clear pattern list to allow for another run
 */
static void clearpattern(void)
{
  struct rule_s *rp1, *rp2;
  struct line_s *lp1, *lp2;

  rp1 = first;
  while (rp1 != NULL) {
	/* Clear old rule text list */
	lp1 = rp1->old;
	while (lp1 != NULL) {
		lp2 = lp1;
		lp1 = lp1->next;
		free(lp2);
	}
	/* Clear new rule text list */
	lp1 = rp1->new;
	while (lp1 != NULL) {
		lp2 = lp1;
		lp1 = lp1->next;
		free(lp2);
	}
	/* Clear rule itself */
	rp2 = rp1;
	rp1 = rp1->next;
	free(rp2);
  }

  first = NULL;
  last = NULL;
}



/*
 * Read input file
 */
static void readinfile(char *filename, int comment)
{
  FILE *fp;

  fp = stdin;
  if (filename != NULL && (fp = fopen(filename, "r")) == NULL) {
	fprintf(stderr, "%s: can't open input file %s\n", progname, filename);
	exit(1);
  }
  infile = readlist(fp, NOCHAR, comment, NULL);
  if (fp != stdin)
	  (void)fclose(fp);
}

#define NO_OP  0
#define ADD_OP 1
#define SUB_OP 2
#define MUL_OP 3
#define DIV_OP 4
#define SHL_OP 5
#define SHR_OP 6

  long retval = 0;
  long num = 0;
  int sign = 1;
  int base = 10;
  int op = NO_OP;

/* Apply operation to current numeric value */
static void doretval(void)
{
      switch (op) {
	      case NO_OP:	retval = num * sign;
			      break;
	      case ADD_OP:	retval += num * sign;
			      break;
	      case SUB_OP:	retval -= num * sign;
			      break;
	      case MUL_OP:	retval *= num * sign;
			      break;
	      case DIV_OP:	retval /= num * sign;
			      break;
	      case SHL_OP:	retval <<= num;
			      break;
	      case SHR_OP:	retval >>= num;
			      break;
      }
      op = NO_OP;
      num = 0;
      sign = 1;
      base = 10;
}


/*
 * Eval an expression into an integer number
 */
static long eval(char *str, int len)
{
  char *cp, c;
  int state = 0;
  int i, varnum;

  retval = 0;
  num = 0;
  sign = 1;
  base = 10;
  op = NO_OP;

  /* Scan through whole string and decode it */
  for (cp = str, i = 0; *cp && i < len; cp++, i++) {
	c = toupper(*cp);
	if (c == '-' && (state == 0 || state == 5)) {
		state = 1;
		sign = -1;
	} else if (c == '+' && (state == 0 || state == 5)) {
		state = 1;
		sign = 1;
	} else if (c == '%' && isdigit(*(cp + 1)) && (state < 2 || state == 5)) {
		state = 4;
		varnum = *(cp + 1) - '0';
		if (vars[varnum] == NULL || i >= len)
			return(0);
		num = eval(vars[varnum], strlen(vars[varnum]));
		doretval();
		cp++; i++;
	} else if (c == '$' && (state < 2 || state == 5)) {
		state = 2;
		base = 16;
	} else if (base == 10 && (c >= '0' && c <= '9') &&
	           (state <= 3 || state == 5)) {
		state = 3;
		num = num * 10 + (c - '0');
	} else if (base == 16 &&
	           ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) &&
	           (state <= 3 || state == 5)) {
		state = 3;
		num = num * 16 + (c >= 'A' ? c - '0' - 7 : c - '0');
	} else if (c == ' ' && (state == 3 || state == 4 || state == 5)) {
		if (state == 3) {
			doretval();
			state = 4;
		}
	} else if (strchr("+-*/<>", c) != NULL && (state == 3 || state == 4)) {
		if (state == 3)
			doretval();
		state = 5;
		switch (c) {
			case '+':	op = ADD_OP;
					break;
			case '-':	op = SUB_OP;
					break;
			case '*':	op = MUL_OP;
					break;
			case '/':	op = DIV_OP;
					break;
			case '<':	op = SHL_OP;
					break;
			case '>':	op = SHR_OP;
					break;
		}
	} else
		return(0);
  }

  /* Check if the string has been terminated correctly */
  if (state != 3 && state != 4)
	return(0);
  if (state == 3)
	doretval();
  return(retval);
}



/*
 * Compare an infile string with a pattern string. If there is any variable
 * defined, it will be inserted into the variable list from the pattern
 * string.
 */
static int match(char *ins, char *pat)
{
  char *cp, *oldpat;
  long val;
  int varnum;
  int len = 0;

  while (*ins && *pat)
  {
  	if (pat[0] != '%')
	{
		if (*pat++ != *ins++)
			return(0);
		else
			continue;
	}
	if (pat[1] == '%') {
		/* '%%' actually means '%' */
		if (*ins != '%')
			return(0);
		pat += 2;
	} else if ((pat[1] == '*' || isdigit(pat[1]))) {
		/* Copy variable text into vars array */
		pat += 2;
		for (cp = ins; *ins && !match(ins, pat); ins++) ;
		if (pat[-1] == '*')
			continue;
		len = ins - cp;
		varnum = pat[-1] - '0';
		if (vars[varnum] == NULL)
			vars[varnum] = install(cp, len);
		else if (strlen(vars[varnum]) != len ||
		           strncmp(vars[varnum], cp, len))
			return(0);
	} else if (pat[1] == '[') {
		/* Copy only specific variable text into vars array */
		if ((cp = strchr(pat + 2, ']')) == NULL ||
		    (*(cp + 1) != '*' && !isdigit(*(cp + 1)))) {
			if (*ins != '[')
				return(0);
			pat += 2;
			continue;
		}
		oldpat = pat + 1;
		pat = cp + 2;
		/* Seperate allowable patterns and compare them with ins */
		while (*oldpat && *oldpat != ']') {
			oldpat++;
			len = strcspn(oldpat, "|]");
			if (!strncmp(ins, oldpat, len))
				break;
			oldpat += len;
		}
		if (!*oldpat || *oldpat == ']')
			return(0);
		ins += len;
		if (!match(ins, pat))
			return(0);
		/* Install new string into variable table */
		if (*(cp + 1) == '*')
			continue;
		varnum = *(cp + 1) - '0';
		if (vars[varnum] == NULL)
			vars[varnum] = install(oldpat, len);
		else if (strlen(vars[varnum]) != len ||
		           strncmp(vars[varnum], oldpat, len))
			return(0);
	} else if (pat[1] == '!') {
		/* Match only if the pattern string is not found */
		if (pat[2] != '[' || (cp = strchr(pat + 3, ']')) == NULL) {
			if (*ins != '!')
				return(0);
			pat += 3;
			continue;
		}
		oldpat = pat + 2;
		pat = cp + 1;
		/* Seperate allowable patterns and compare them with ins */
		while (*oldpat && *oldpat != ']') {
			oldpat++;
			len = strcspn(oldpat, "|]");
			if (!strncmp(ins, oldpat, len))
				return(0);
			oldpat += len;
		}
	} else if (pat[1] == '(') {
		/* Match ins with expression */
		if ((cp = strchr(pat + 2, ')')) == NULL) {
			if (*ins != '(')
				return(0);
			pat += 2;
			continue;
		}
		oldpat = pat + 2;
		pat = cp + 1;
		len = cp - oldpat;
		val = eval(oldpat, len);
		for (cp = ins; *ins && !match(ins, pat); ins++) ;
		len = ins - cp;
		if (val != eval(cp, len))
			return(0);
	}
	else /* Bad % format cannot match */
		return(0);
  }

  return(*ins == *pat);
}



/*
 * Substitute variables in a string
 */
static char *subst(char *pat)
{
  char buf[MAXLINE];
  char *cp, *cp1, *cp2, *varptr;
  long num;
  int i = 0;
  int j, pos;

  while (*pat)
	if (pat[0] == '%' && isdigit(pat[1])) {
		/* Substitute with value of variable */
		cp = vars[pat[1] - '0'];
		while (cp != NULL && *cp) {
			buf[i++] = *cp++;
			if (i >= MAXLINE - 1) {
				fprintf(stderr, "%s: line too long\n", progname);
				exit(1);
			}
		}
		pat += 2;
	} else if (pat[0] == '%' && pat[1] == '(') {
		/* Substitute with expression */
		cp = pat + 2;
		if ((pat = strchr(cp, ')')) == NULL || pat - cp <= 0)
			num = 0;
		else
			num = eval(cp, pat - cp);
		if (i >= MAXLINE - 20) {
			fprintf(stderr, "%s: line too long\n", progname);
			exit(1);
		}
		i += sprintf(&buf[i], "%s$%lx", num < 0 ? "-" : "", labs(num));
		pat++;
	} else if (pat[0] == '%' && pat[1] == '=') {
		/* Substitute with converted variable */
		/* First seperate all parts of the pattern string */
		cp = pat + 2;
		cp1 = cp2 = varptr = NULL;
		if (*cp == '[') {
			cp1 = ++cp;
			while (*cp && *cp != ']')
				cp++;
			if (cp[0] == ']' && cp[1] == '[') {
				cp += 2;
				cp2 = cp;
				while (*cp && *cp != ']')
					cp++;
				if (cp[0] == ']' && isdigit(cp[1]))
					 varptr = vars[cp[1] - '0'];
			}
		}
		if (cp1 == NULL || cp2 == NULL || varptr == NULL) {
			buf[i++] = *pat++;
			if (i >= MAXLINE - 1) {
				fprintf(stderr, "%s: line too long\n", progname);
				exit(1);
			}
			continue;
		}
		pat = cp + 2;
		/* Now scan through the first string to find variable value */
		cp1--;
		pos = 0;
		while (*cp1 != ']') {
			cp1++;
			j = strcspn(cp1, "|]");
			if (strlen(varptr) == j && !strncmp(cp1, varptr, j))
				break;
			pos++;
			cp1 += j;
		}
		if (*cp1 == ']')
			continue;
		/* Scan through the second string to find the conversion */
		cp2--;
		while (*cp2 != ']' && pos > 0) {
			cp2++;
			j = strcspn(cp2, "|]");
			pos--;
			cp2 += j;
		}
		if (*cp2 == ']' || pos != 0)
			continue;
		/* Insert conversion string into destination */
		cp2++;
		while (*cp2 != '|' && *cp2 != ']') {
			buf[i++] = *cp2++;
			if (i >= MAXLINE - 1) {
				fprintf(stderr, "%s: line too long\n", progname);
				exit(1);
			}
		}
	} else {
		buf[i++] = *pat++;
		if (i >= MAXLINE - 1) {
			fprintf(stderr, "%s: line too long\n", progname);
			exit(1);
		}
	}

  buf[i] = '\0';
  return(install(buf, i));
}



/*
 * Optimize one line of the input file
 */
static struct line_s *optline(struct line_s *cur)
{
  struct rule_s *rp;
  struct line_s *ins, *pat;
  struct line_s *lp1, *lp2;
  int i;

  for (rp = first; rp != NULL; rp = rp->next) {
	/* Clear variable array */
	for (i = 0; i < VARNUM; i++)
		vars[i] = NULL;

	/* Scan through pattern texts and match them against the input file */
	ins = cur;
	pat = rp->old;
	while (ins != NULL
	    && pat != NULL
	    && ( ins->comment_flg ||
	         ( /* (pat->text[0]=='%' || ins->text[0]==pat->text[0]) && */
		  match(ins->text, pat->text)))) {

		if (!ins->comment_flg)
			pat = pat->next;
		else if (ins->text[0]==pat->text[0]) /* Matching a comment! */
		{
		   if (match(ins->text, pat->text))
		      pat = pat->next;
		}
		ins = ins->next;
	}

	/* Current pattern matched input line, so replace input with new */
	if (pat == NULL) {
		/* Clear all lines in the source file for this pattern */
		lp1 = cur;
		cur = cur->prev;
		while (lp1 != ins) {
#if 0
			if( lp1->comment_flg )
			{
				lp2 = lp1;
				lp1 = lp1->next;
				lp2->next = cur->next;
				cur->next = lp2;
				lp2->prev = cur;
				cur=cur->next;
			}
			else
#endif
			{
				lp2 = lp1;
				lp1 = lp1->next;
				free(lp2);
			}
		}
		/* Insert new lines into list */
		pat = rp->new;
		lp1 = cur;
		lp2 = NULL;
		while (pat != NULL) {
			lp2 = mymalloc(sizeof(struct line_s));
			lp2->text = subst(pat->text);
			lp2->next = NULL;
			lp2->prev = lp1;
			lp2->comment_flg = 0;
			if (lp1 != NULL)
				lp1->next = lp2;
			else
				infile = lp2;
			lp1 = lp2;
			pat = pat->next;
		}
		if (ins != NULL)
			ins->prev = lp2;
		if (lp2 != NULL)
			lp2->next = ins;
		else if (lp1 != NULL)
			lp1->next = NULL;
		else
			infile = NULL;
		return(cur);
	}
  }
  return(cur->next);
}



/*
 * Actually optimize all strings in the input file
 */
static void optimize(int backup)
{
  struct line_s *cur, *lp;
  int i;
  int in_asm = 0;

  /* Scan through all lines in the input file */
  cur = infile;
  while (cur != NULL) {
	if (cur->comment_flg || in_asm)
	{
		lp=cur->next;
		if (memcmp(cur->text, "!BCC_", 5) == 0)
			in_asm = (memcmp(cur->text+5, "ASM", 3) == 0);
	}
	else
	        if ((lp = optline(cur)) != NULL && lp != cur->next) {
			for (i = 0; i < backup && lp != NULL; i++)
				lp = lp->prev;
			if (lp == NULL)
				lp = infile;
		}
	cur = lp;
  }
}



/*
 * Write out into destination file
 */
static void writeoutf(char *filename, char *headstr)
{
  FILE *fp;
  struct line_s *lp;

  fp = stdout;
  if (filename != NULL && (fp = fopen(filename, "w")) == NULL) {
	fprintf(stderr, "%s: can't open output file %s\n", progname, filename);
	exit(1);
  }
  if (headstr != NULL) {
	fprintf(fp, "%s", headstr);
	fprintf(fp, "\n");
  }
  for (lp = infile; lp != NULL; lp = lp->next)
	fprintf(fp, "%s\n", lp->text);
  if (fp != stdout)
	  (void)fclose(fp);
}



/*
 * Print usage
 */
static void usage(void)
{
  fprintf(stderr, "usage: %s [-c<comment-char>] [-f<src-file>] [-o<out-file>]\n"
		"\t\t[-b<backup-num>] [-h<head-str>] [-d<ruls-dir>] "
		"<rules-file> ...\n", progname);
  exit(1);
}



/*
 * Main program
 */
int
main(int argc, char **argv)
{
  char comment = NOCHAR;
  char *srcfile = NULL;
  char *outfile = NULL;
  char *headstr = NULL;
  char *rulesdir = NULL;
  int backup = 0;
  int i;

  /* Get program name */
  if ((progname = strrchr(argv[0], '/')) == NULL)
	progname = argv[0];
  else
	progname++;

  /* Make life easy for bcc */
  if ( argc > 4 && strcmp(argv[2], "-o") == 0 && argv[1][0] != '-' )
  {
     srcfile = argv[1];
     argv++,argc--;
  }

  /* Get options from command line */
  for (i = 1; i < argc; i++)
	if (!strncmp(argv[i], "-c", 2))
		comment = argv[i][2];
	else if (!strncmp(argv[i], "-b", 2))
		backup = atoi(&(argv[i][3]));
	else if (!strncmp(argv[i], "-f", 2))
		srcfile = &(argv[i][2]);
	else if (!strncmp(argv[i], "-o", 2))
	{
		if(argv[i][2])
			outfile = &(argv[i][2]);
		else if(++i<argc)
			outfile = argv[i];
		else
			usage();
	}
	else if (!strncmp(argv[i], "-h", 2))
		headstr = &(argv[i][2]);
	else if (!strncmp(argv[i], "-d", 2))
		rulesdir = &(argv[i][2]);
	else if (argv[i][0] == '-')
		usage();
	else
		break;

  /* Have to have enough parameters for rule file names */
  if ((argc - i) < 1)
	usage();

  /* Read source file and optimze it with every rules file */
  readinfile(srcfile, comment);
  for ( ; i < argc; i++) {
	readpattern(rulesdir, argv[i]);
	optimize(backup);
	clearpattern();
  }
  writeoutf(outfile, headstr);

  exit(0);
}