File: main.c

package info (click to toggle)
bibtool 2.48alpha.2-3.1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 3,208 kB
  • ctags: 1,974
  • sloc: ansic: 18,936; xml: 1,036; makefile: 672; sh: 293; perl: 261; tcl: 51; awk: 15; sed: 8
file content (866 lines) | stat: -rw-r--r-- 36,146 bytes parent folder | download | duplicates (3)
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
/******************************************************************************
** $Id: main.c,v 2.34 1997/12/06 22:56:00 gerd Exp gerd $
**=============================================================================
** 
** This file is part of BibTool.
** It is distributed under the GNU General Public License.
** See the file COPYING for details.
** 
** (c) 1996-2004 Gerd Neugebauer
** 
** Net: gene@gerd-neugebauer.de
** 
** >>> See the file Doc/c_lib.tex for a printed documentation of the
** >>> main parts of the C source.
** 
**-----------------------------------------------------------------------------
** Description:
**	This is the \BibTool{} main module. It contains the |main()|
**	function which evaluates the command line arguments and
**	proceeds accordingly. This means that usually resource files
**	and \BibTeX{} files are read and one or more \BibTeX{} files
**	are written.
**
**	This file makes use of the \BibTool{} C library but is not
**	part of it. For this purpose it has to provide certain
**	functions which are expected by the library. These functions
**	are: 
**	\begin{quote}
**	  \texttt{save\_input\_file()}\\
**	  \texttt{save\_macro\_file()}\\
**	  \texttt{save\_output\_file()}\\
**	\end{quote}
**	The arguments and the expected behaviour of these functions is
**	described below.
**
**	If you are trying to understand the implementation of
**	\BibTool{} the file |resource.h| plays a central
**	r\^ole. Consult the description of this file for further
**	details. 
**
**	If you are trying to write your own program to manipulate
**	\BibTeX{} files then this file can serve as a starting point.
**	But you should keep in mind that this file has grown over
**	several years and it contains the full complexity of the
**	\BibTool{} program logic. Thus you can reduce this file
**	drastically if you start playing around with the \BibTool{} C
**	library. 
**
******************************************************************************/

#include <bibtool/general.h>
#include <bibtool/init.h>
#include <bibtool/tex_aux.h>
#include <bibtool/error.h>
#include <bibtool/key.h>
#include <bibtool/pxfile.h>
#include <bibtool/print.h>
#include <bibtool/rewrite.h>
#include <bibtool/rsc.h>
#include <bibtool/entry.h>
#include <bibtool/parse.h>
#include <bibtool/macros.h>
#include <bibtool/s_parse.h>
#include <bibtool/symbols.h>
#include <bibtool/sbuffer.h>
#include <bibtool/expand.h>
#include <bibtool/version.h>
#ifdef HAVE_LIBKPATHSEA
#include <kpathsea/debug.h>
#endif
#include "config.h"

/*****************************************************************************/
/* Internal Programs							     */
/*===========================================================================*/

#ifdef __STDC__
#define _ARG(A) A
#else
#define _ARG(A) ()
#endif
 int main _ARG((int argc,char *argv[]));	   /* main.c                 */
 static int dbl_check _ARG((DB db,Record rec));	   /* main.c                 */
 static int do_keys _ARG((DB db,Record rec));	   /* main.c                 */
 static int do_no_keys _ARG((DB db,Record rec));   /* main.c                 */
 static int rec_gt _ARG((Record r1,Record r2));	   /* main.c                 */
 static int rec_gt_cased _ARG((Record r1,Record r2));/* main.c               */
 static int rec_lt _ARG((Record r1,Record r2));	   /* main.c                 */
 static int rec_lt_cased _ARG((Record r1,Record r2));/* main.c               */
 static int update_crossref _ARG((DB db,Record rec));/* main.c               */
 static void usage _ARG((int fullp));		   /* main.c                 */
 void save_input_file _ARG((char *file));	   /* main.c                 */
 void save_macro_file _ARG((char *file));	   /* main.c                 */
 void save_output_file _ARG((char * file));	   /* main.c                 */

/*****************************************************************************/
/* External Programs and Variables					     */
/*===========================================================================*/

/*---------------------------------------------------------------------------*/

#ifndef __STDC__
#ifndef HAVE_GETENV

 char * getenv _ARG((char *name));		   /* main.c                 */

/*-----------------------------------------------------------------------------
** Dummy funtion returning NULL to indicate failure.
**___________________________________________________			     */
char * getenv(name)				   /*			     */
  char *name;				   	   /*			     */
{ return (char*)NULL;				   /*			     */
}						   /*------------------------*/
#endif
#endif


#ifndef OptionLeadingCharacter
#define OptionLeadingCharacter '-'
#endif

 static char *use[] =
  { "bibtool [options] [%co outfile] [[%ci] infile] ...\n",
    "\n\tOptions:\n",
    "\t%cA<c>\t\tKind of disambiguating keystrings: <c>=0|a|A\n",
    "\t%cc\t\tInclude crossreferenced entries into the output (toggle)\n",
    "\t%cd\t\tCheck double entries (toggle)\n",
    "\t%cf <format>\tKey generation enabled (formated key)\n",
    "\t%cF\t\tKey generation enabled with formated key\n",
    "\t%ch\t\tPrint this help info and exit\n",
    "\t[%ci] infile\tSpecify input file. If %ci omitted it may not start\n",
    "\t\t\twith a %c. If absent stdin is taken to read from.\n",
    "\t\t\tMultiple input files may be given.\n",
    "\t%ck\t\tKey generation enabled.\n",
    "\t%cK\t\tKey generation enabled (long key).\n",
    "\t%cm macfile\tDump macros to macfile. - is stdout\n",
    "\t%cM macfile\tDump used macros to macfile. - is stdout\n",
    "\t%co outfile\tSpecify output file as next argument\n",
    "\t\t\tIf absent stdout is taken to write to.\n",
    "\t%cq\t\tQuiet mode. No warnings.\n",
    "\t%cr resource\tLoad resource file (several are possible).\n",
    "\t%cR\t\tLoad default resource file here.\n",
    "\t%cs\t\tSort.\n",
    "\t%cS\t\tSort reverse.\n",
    "\t%cv\t\tEnable verbose mode\n",
    "\t%cV\t\tPrint version\n",
    "\t%cx file\t\tExtract from aux file.\n",
    "\t%cX <regex>\tExtract regular expression.\n",
    "\t%c- <rsc>\tEvaluate one resource command <rsc>.\n",
    "\t%c@\t\tPrint statistics (short).\n",
    "\t%c#\t\tPrint statistics.\n",
#ifdef SYMBOL_DUMP
    "\t%c$\t\tSymbol table output (debugging only)\n",
#endif
    0L,
    "Copyright (C) Gerd Neugebauer $Date: 1997/12/06 22:56:00 $",
    "gene@gerd-neugebauer.de"
  };

/*-----------------------------------------------------------------------------
** Function:	usage()
** Purpose:	Print the version number, a copyright notice, and
**		a short description of the command line options on the
**		|stderr| stream.
**		In addition certain configuration options are
**		printed. If the argument is |FALSE| then only the
**		copyright and the version number are displayed.
** Arguments:
**	fullp	Boolean. If |FALSE| only the version is displayed.
** Returns:	nothing
**___________________________________________________			     */
static void usage(fullp)			   /*			     */
  int           fullp;				   /*                        */
{ register char **cpp;				   /*			     */
  static char    *comma = ", ";			   /*                        */
  char		 *sep   = " ";			   /*                        */
						   /*			     */
  show_version();				   /*                        */
						   /*			     */
  if ( fullp )					   /*                        */
  { for ( cpp=use; *cpp; cpp++ )		   /*			     */
    { ErrPrintF2(*cpp,				   /*			     */
		 OptionLeadingCharacter,	   /*			     */
		 OptionLeadingCharacter);	   /*			     */
    }						   /*                        */
  }						   /*                        */
						   /*                        */
  ErrPrintF("\nLibrary path: %s",		   /*                        */
	    (rsc_v_rsc==NULL		   	   /*                        */
	     ? "none"				   /*                        */
	     : rsc_v_rsc));	   	   	   /*                        */
 						   /*                        */
  ErrPrint("\nSpecial configuration options:");	   /*                        */
#define SPECIAL_OPTIONS " none"
#ifdef HAVE_LIBKPATHSEA
  ErrPrintF("%skpathsea",sep);			   /*                        */
  sep = comma;					   /*                        */
#undef SPECIAL_OPTIONS
#define SPECIAL_OPTIONS ""
#endif
#ifndef REGEX
  ErrPrintF("%sNO regex",sep);			   /*                        */
  sep = comma;					   /*                        */
#undef SPECIAL_OPTIONS
#define SPECIAL_OPTIONS ""
#endif
#ifdef EMTEX_LIKE_PATH
  ErrPrintF("%semTeX like path",sep);		   /*                        */
  sep = comma;					   /*                        */
#undef SPECIAL_OPTIONS
#define SPECIAL_OPTIONS ""
#endif
  ErrPrintF("%s\n",SPECIAL_OPTIONS);		   /*                        */
}						   /*------------------------*/


#define UnknownWarning(X)     WARNING2("Unknown flag ignored: ",X)
#define NoSFileWarning	      WARNING("Missing select option. Flag ignored.")
#define NoFileError(X)	      WARNING3("File ",X," not found.")
#define MissingPattern	      WARNING("Missing pattern.")
#define MissingResource	      WARNING("Missing resource.")
#define NoRscError(X)	      WARNING3("Resource file ",X," not found.")

/*****************************************************************************/
/***			 Input File Pipe Section			   ***/
/*****************************************************************************/

#define InputFilePipeIncrement 8

 static char **input_files;
 static int  input_file_size = 0;
 static int  input_file_ptr  = 0;

#define InputPipeIsFull		(input_file_ptr >= input_file_size)
#define InputPipeIsEmpty	(input_file_ptr == 0)
#define PushToInputPipe(FILE)	input_files[input_file_ptr++] = FILE
#define ForAllInputFiles(FILE)	for (FILE=input_files;			\
				     FILE<&input_files[input_file_ptr];	\
				     FILE++)

/*-----------------------------------------------------------------------------
** Function:	save_input_file()
** Purpose:	The input file pipe is a dynamic array of strings.
**		This fifo stack is used to store the input \BibTeX{}
**		files to be processed by \BibTool.
**
**		This function is called to push an string into the pipe.
**		If neccesary the array has to be allocated or enlarged.
**		This is done in larger junks to avoid lots of calls to
**		|realloc()|.
** Arguments:
**	file	File name to save.
** Returns:	nothing
**___________________________________________________			     */
void save_input_file(file)			   /*			     */
  char *file;					   /*			     */
{						   /*			     */
  if ( file == NULL )				   /*			     */
  { WARNING("Missing input file name. Flag ignored.");/*		     */
    return;					   /*			     */
  }						   /*			     */
  if ( *file == '-' && file[1] == '\0' )	   /*			     */
  { file = NULL; }				   /*			     */
						   /*			     */
  if ( InputPipeIsFull )			   /* No space left?	     */
  { input_file_size += InputFilePipeIncrement;	   /*			     */
						   /*			     */
    if ( InputPipeIsEmpty			   /* Try to enlarge array   */
	? NULL==(input_files=			   /*			     */
		 (char**)malloc(sizeof(char*)	   /*			     */
				*(size_t)input_file_size))/*		     */
	: NULL==(input_files=			   /*			     */
		 (char**)realloc((char*)input_files,/*			     */
				 sizeof(char*)	   /*			     */
				 *(size_t)input_file_size))/*		     */
	)					   /*			     */
    { OUT_OF_MEMORY("input file pipe.");	   /*		             */
    }						   /*			     */
  }						   /*			     */
  PushToInputPipe(file);			   /*			     */
}						   /*------------------------*/


/*****************************************************************************/
/***			   Output File Section				   ***/
/*****************************************************************************/

 static char *output_file = NULL;		   /*			     */

/*-----------------------------------------------------------------------------
** Function:	save_output_file()
** Purpose:	Simply feed the output file name into the static variable.
**		This function is useful since it can be called from rsc.c
** Arguments:
**	file	File name to save
** Returns:	nothing
**___________________________________________________			     */
void save_output_file(file)			   /*			     */
  char * file;					   /*			     */
{ if ( output_file != NULL )			   /*			     */
  { WARNING2("Output file redefined: ",file); }	   /*			     */
  output_file = file;				   /*			     */
}						   /*------------------------*/


/*****************************************************************************/
/***			   Macro File Section				   ***/
/*****************************************************************************/

 static char *macro_file = NULL;		   /*			     */

/*-----------------------------------------------------------------------------
** Function:	save_macro_file()
** Purpose:	Simply feed the macro file name into the static variable.
**		This function is useful since it can be called from rsc.c
** Arguments:
**	file	File name to save
** Returns:	nothing
**___________________________________________________			     */
void save_macro_file(file)			   /*			     */
  char *file;					   /*			     */
{ if ( macro_file != NULL )			   /*			     */
  { WARNING2("Macro file redefined: ",file); }	   /*			     */
  macro_file = file;				   /*			     */
}						   /*------------------------*/


/*****************************************************************************/
/***				    MAIN				   ***/
/*****************************************************************************/


#if 0
(This is unused, and kpathsea defines true as a macro)
/*-----------------------------------------------------------------------------
** Function:	true()
** Type:	static int
** Purpose:	
**		
** Arguments:
**		
** Returns:	
**___________________________________________________			     */
static int true() { return TRUE; }
#endif

/*-----------------------------------------------------------------------------
** Function:	keep_selected()
** Type:	static int
** Purpose:	
**		
** Arguments:
**	db	
**	rec	
** Returns:	
**___________________________________________________			     */
static int keep_selected(db,rec)		   /*                        */
  DB db;					   /*                        */
  Record rec;					   /*                        */
{						   /*                        */
  if ( !is_selected(db,rec) )			   /*                        */
  { SetRecordDELETED(rec);			   /*                        */
  }						   /*                        */
 						   /*                        */
  return FALSE;					   /*                        */
}						   /*------------------------*/

#ifdef UNUSED
/*-----------------------------------------------------------------------------
** Function:	keep_xref()
** Type:	int 
** Purpose:	Undelete crossreferenced entries
**		
** Arguments:
**	db	
**	rec	
** Returns:	
**___________________________________________________			     */
int keep_xref(db,rec)				   /*                        */
  DB db;					   /*                        */
  Record rec;					   /*                        */
{						   /*                        */
  if ( !RecordIsDELETED(rec) )		   	   /*                        */
  { Uchar  *key;				   /*                        */
    int    count;				   /*                        */
 						   /*                        */
    for ( count=rsc_xref_limit;		   	   /* Prevent infinite loop  */
	  count >= 0;		   	   	   /*                        */
	  count-- )				   /*                        */
    {					   	   /*                        */
      if ( (key = get_field(db,rec,sym_crossref)) == NULL )/*                */
      { return FALSE; }			   	   /*                        */
 						   /*                        */
      key = symbol(lower(expand_rhs(key,	   /*                        */
				    sym_empty,     /*                        */
				    sym_empty, 	   /*                        */
				    db)));     	   /*                        */
      if ( (rec=db_search(db,key)) == RecordNULL ) /*                        */
      { ErrPrintF("*** BibTool: Crossref `%s' not found.\n",key);/*          */
        return FALSE;			   	   /*                        */
      }					   	   /*                        */
 						   /*                        */
      if ( !RecordIsDELETED(rec) ) { return FALSE; }/*                       */
      ClearRecordDELETED(rec);		   	   /*                        */
    }					   	   /*                        */
 						   /*                        */
    ErrPrintF("*** BibTool: Crossref limit exceeded; `%s' possibly looped.\n",
	      key);				   /*                        */
  }    					   	   /*                        */
  return FALSE;					   /*                        */
}						   /*------------------------*/
#endif


#define Toggle(X) X = !(X)

/*-----------------------------------------------------------------------------
** Function:	main()
** Purpose:	This is the main function which is automatically
**		called when the program is started. This function
**		contains the overall program logic. It has to perform
**		the appropriate initializations, evaluate command line
**		arguments, and run the main loop.
** Arguments:
**	argc	Number of arguments
**	argv	Array of arguments
** Returns:	0 upon success. Usually a failure raises an exception
**		which leads to an |exit()|. Thus this function does
**		not need to signal an error to the calling environment.
**___________________________________________________			     */
int main(argc,argv)				   /*			     */
  int	argc;				   	   /* Argument count	     */
  char	*argv[];			   	   /* Argument values	     */
{ DB	the_db;				   	   /* The \BibTool{} program */
						   /* currently handles a    */
						   /* single database at a   */
						   /* time.  The local       */
						   /* variable |the_db|      */
						   /* contains a reference to*/
						   /* this database.	     */
  int	i;				   	   /*			     */
  char	*ap;				   	   /*			     */
  FILE	*file;				   	   /*                        */
  int	need_rsc = TRUE;		   	   /*			     */
  int	(*fct)();			   	   /* Function pointer	     */
  int	c_len;					   /*                        */
  int   *c;					   /*                        */
 						   /*                        */
  init_error(stderr);				   /*                        */
  init_bibtool(argv[0]);			   /*                        */
						   /*			     */
  for ( i=1; i<argc; i++ )			   /*			     */
  { if ( *(ap=argv[i]) != OptionLeadingCharacter ) /*			     */
    { save_input_file(argv[i]);			   /*			     */
    }						   /*			     */
    else					   /*			     */
    { switch ( *++ap )				   /*			     */
      { case 'A': set_base((Uchar*)(ap+1));  break;/* disambiguation	     */
	case 'c': Toggle(rsc_xref_select);   break;/* include crossreferences*/
	case 'd': Toggle(rsc_double_check);  break;/* double entries	     */
#ifdef HAVE_LIBKPATHSEA
	case 'D': kpathsea_debug=atoi(++ap); break;/* kpathsea debugging     */
#endif
	case 'f': add_format(argv[++i]);	   /*	!!! no break !!!     */
	case 'F': rsc_make_key = TRUE;	    break; /* key generation	     */
	case 'h': usage(TRUE); return 1;	   /* print help	     */
	case 'i': save_input_file(argv[++i]); break;/*			     */
	case 'K': add_format("long");	    break; /* key generation	     */
	case 'k': add_format("short");	    break; /* key generation	     */
	case 'M':				   /* print macro table	     */
	case 'm': rsc_all_macs = (*ap=='m');	   /* print macro table	     */
	  save_macro_file(argv[++i]);		   /*			     */
	  break;				   /*			     */
	case 'o':				   /* output file	     */
	  save_output_file(argv[++i]);	    break; /*			     */
	case 'q': Toggle(rsc_quiet);	    break; /* quiet		     */
	case 'r':				   /* resource file	     */
	  if ( ++i < argc && load_rsc(argv[i]) )   /*		             */
	  { need_rsc = FALSE; }		   	   /*			     */
	  else					   /*                        */
	  {  NoRscError(argv[i]); }		   /*                        */
	  break;				   /*			     */
	case 'R': need_rsc |= !search_rsc();break; /* default resource file  */
	case 's': Toggle(rsc_sort);	    break; /* sort		     */
	case 'S':				   /*			     */
	  Toggle(rsc_sort);			   /*			     */
	  Toggle(rsc_sort_reverse);		   /*			     */
	  break;				   /* sort		     */
	case 'v': Toggle(rsc_verbose);	    break; /* verbose		     */
	case 'V': usage(FALSE);	            break; /* version		     */
	case 'x':				   /* extract		     */
	  rsc_all_macs = FALSE;			   /*                        */
	  if ( ++i < argc )			   /*			     */
	  { if ( read_aux(argv[i],save_input_file,*++ap=='v') )/*            */
	    { ERROR3("aux file ",argv[i]," not found.");/*                   */
	    }					   /*                        */
	  }					   /*                        */
	  else		    { NoSFileWarning; }	   /*			     */
	  break;				   /*			     */
	case 'X':				   /* extract pattern	     */
	  rsc_all_macs = FALSE;			   /*                        */
	  if ( ++i < argc ) { save_regex((Uchar*)argv[i]); }/*		     */
	  else		    { MissingPattern; }	   /*			     */
	  break;				   /*			     */
	case '#': Toggle(rsc_cnt_all);	    break; /* print full statistics  */
	case '@': Toggle(rsc_cnt_used);	    break; /* print short statistics */
	case '-':				   /* extended command	     */
	  if ( *++ap )	      { (void)use_rsc((Uchar*)ap); }/*		     */
	  else if ( ++i<argc ){ (void)use_rsc((Uchar*)argv[i]); }/*	     */
	  else		      { MissingResource;  }/*			     */
	  break;				   /*			     */
#ifdef SYMBOL_DUMP
	case '$': Toggle(rsc_dump_symbols); break; /* print symbol table     */
#endif
	default:				   /*			     */
	  UnknownWarning(ap);			   /*			     */
	  usage(TRUE);				   /*                        */
	  return 1;		   		   /*			     */
      }						   /*			     */
    }						   /*			     */
  }						   /*			     */
						   /*			     */
  if ( need_rsc ) { (void)search_rsc(); }	   /*			     */
						   /*			     */
  if ( InputPipeIsEmpty )			   /* If no input file given */
  { save_input_file("-"); }			   /*  then read from stdin  */
						   /*			     */
  init_read();					   /* Just in case the path  */
 						   /*  has been modified.    */
  the_db = new_db();				   /*                        */
						   /*			     */
  for ( i=0; i<input_file_ptr; i++ )		   /* For all input files    */
  {						   /*			     */
    if ( read_db(the_db,			   /*                        */
		 input_files[i],		   /*                        */
		 rsc_verbose) )	   		   /*                        */
    { NoFileError(input_files[i]); }		   /*			     */
  }						   /*			     */
 						   /*                        */
  db_forall(the_db,keep_selected);		   /*                        */
						   /*                        */
  apply_aux(the_db);				   /*                        */
 						   /*                        */
  if ( rsc_xref_select ) db_xref_undelete(the_db); /*                        */
 						   /*                        */
  if ( rsc_cnt_all || rsc_cnt_used )		   /*			     */
  { int i;					   /*                        */
    int * cnt = db_count(the_db,&c_len);	   /*                        */
 						   /*                        */
    if ( (c=(int*)malloc(c_len*sizeof(int))) == NULL )/*                     */
    { rsc_cnt_all = rsc_cnt_used = 0; }		   /*                        */
    else					   /*                        */
    { for (i=0;i<c_len;i++) c[i] = cnt[i];	   /*                        */
    }						   /*                        */
  }						   /*                        */
						   /*			     */
  if ( rsc_make_key )				   /*                        */
  {						   /*                        */
    start_key_gen();				   /*                        */
    if ( rsc_key_preserve )	   		   /*                        */
    { db_forall(the_db,mark_key); }		   /*                        */
    db_rewind(the_db);				   /*                        */
    db_forall(the_db,do_keys);		   	   /*                        */
    db_forall(the_db,update_crossref);	   	   /*                        */
    end_key_gen();				   /*                        */
  }						   /*                        */
  else						   /*                        */
  {						   /*                        */
    db_forall(the_db,do_no_keys);		   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( rsc_sort )				   /*                        */
  {				   		   /*                        */
    if ( rsc_sort_cased )			   /*                        */
    { if ( rsc_sort_reverse ) fct = rec_lt_cased;  /*                        */
      else		      fct = rec_gt_cased;  /*                        */
    }						   /*                        */
    else					   /*                        */
    { if ( rsc_sort_reverse ) fct = rec_lt;	   /*                        */
      else		      fct = rec_gt;	   /*                        */
    }						   /*                        */
    db_sort(the_db,fct);			   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( rsc_srt_macs )		   	   	   /* Maybe sort macros      */
  { db_mac_sort(the_db); }			   /*                        */
 						   /*                        */
  if ( rsc_double_check	)		   	   /* Maybe look for doubles */
  { db_forall(the_db,dbl_check); }		   /*                        */
 						   /*                        */
  if ( output_file == NULL ||			   /*                        */
       (file=fopen(output_file,"w")) == NULL )	   /*                        */
  { file = stdout; }				   /*                        */
 						   /*                        */
  if ( rsc_select ) { rsc_del_q = FALSE; }	   /*                        */
 						   /*                        */
  { char * print_spec = (char*)rsc_print_et;	   /*                        */
 						   /*                        */
    if ( rsc_expand_macros )			   /*                        */
    { char * cp;				   /*                        */
      print_spec = new_string(print_spec);	   /*                        */
      for ( cp=print_spec; *cp; cp++ )		   /*                        */
      { if ( *cp == 's' ||			   /*                        */
	     *cp == 'S' ||			   /*                        */
	     *cp == '$' ) *cp = ' ';		   /*                        */
      }						   /*                        */
    }						   /*                        */
    print_db(file,the_db,print_spec);	   	   /*                        */
    if ( rsc_expand_macros) free(print_spec);	   /*                        */
  }						   /*                        */
 						   /*                        */
  if ( file != stdout ) { fclose(file); }	   /*                        */
						   /*			     */
  if ( macro_file != NULL  && *macro_file )	   /*			     */
  { if ( rsc_verbose )				   /*			     */
    { VerbosePrint1("Writing macros"); }	   /*			     */
 						   /*                        */
    if ( strcmp(macro_file,"-") == 0 ||		   /*                        */
	 (file=fopen(macro_file,"w")) == NULL )    /*                        */
    { file = stdout; }				   /*                        */
    print_db(file,the_db,rsc_all_macs?"s":"S");	   /*                        */
    if ( file != stdout ) { fclose(file); }	   /*                        */
  }						   /*			     */
						   /*			     */
  if ( rsc_cnt_all || rsc_cnt_used )		   /*			     */
  { int i;					   /*                        */
    int *cnt = db_count(the_db,(int*)NULL);	   /*                        */
						   /*                        */
    ErrC('\n');		   	   	   	   /*			     */
    for (i=0; i<c_len; ++i)			   /*			     */
    { if ( rsc_cnt_all || c[i] > 0 )	   	   /*			     */
      { ErrPrintF3("---  %-15s %5d read  %5d written\n",/*		     */
		   get_entry_type(i),	   	   /*			     */
		   c[i],		   	   /*			     */
		   cnt[i]);		   	   /*			     */
      }						   /*			     */
    }						   /*			     */
  }						   /*                        */
						   /*			     */
#ifdef SYMBOL_DUMP
  if ( rsc_dump_symbols ) sym_dump();		   /* Write symbols.	     */
#endif
 						   /*                        */
#ifdef FREE_MEMORY
  free_db(the_db);				   /*                        */
  the_db = NULL;				   /*                        */
  sym_gc();					   /*                        */
#ifdef SYMBOL_DUMP
  sym_dump();					   /*                        */
#endif
#endif
  return 0;					   /*			     */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	rec_gt()
** Purpose:	
**		
**
** Arguments:
**	r1
**	r2
** Returns:	
**___________________________________________________			     */
static int rec_gt(r1,r2)			   /*                        */
  Record r1;					   /*                        */
  Record r2;					   /*                        */
{ return (strcmp((char*)RecordSortkey(r1),	   /*                        */
		 (char*)RecordSortkey(r2)) < 0);   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	rec_lt()
** Purpose:	
**		
**
** Arguments:
**	r1
**	r2
** Returns:	
**___________________________________________________			     */
static int rec_lt(r1,r2)			   /*                        */
  Record r1;					   /*                        */
  Record r2;					   /*                        */
{ return (strcmp((char*)RecordSortkey(r1),	   /*                        */
		 (char*)RecordSortkey(r2)) > 0);   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	rec_gt_cased()
** Type:	static int
** Purpose:	
**		
** Arguments:
**	r1	
**	r2	
** Returns:	
**___________________________________________________			     */
static int rec_gt_cased(r1,r2)			   /*                        */
  Record r1;					   /*                        */
  Record r2;					   /*                        */
{ return (strcmp((char*)get_key_name(RecordSortkey(r1)),/*                   */
		 (char*)get_key_name(RecordSortkey(r2))) < 0);/*             */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	rec_lt_cased()
** Type:	static int
** Purpose:	
**		
** Arguments:
**	r1	
**	r2	
** Returns:	
**___________________________________________________			     */
static int rec_lt_cased(r1,r2)			   /*                        */
  Record r1;					   /*                        */
  Record r2;					   /*                        */
{ return (strcmp((char*)get_key_name(RecordSortkey(r1)),/*                   */
		 (char*)get_key_name(RecordSortkey(r2))) > 0);/*             */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	do_keys()
** Purpose:	
**		
**
** Arguments:
**	rec
** Returns:	
**___________________________________________________			     */
static int do_keys(db,rec)			   /*                        */
  DB	 db;					   /*                        */
  Record rec;					   /*                        */
{						   /*                        */
  rewrite_record(db,rec);			   /*			     */
  sort_record(rec);				   /*                        */
  make_key(db,rec);				   /*                        */
  if ( rsc_sort || rsc_double_check )		   /*                        */
  { make_sort_key(db,rec); }		   	   /*                        */
  return 0;					   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	do_no_keys()
** Purpose:	
**		
**
** Arguments:
**	rec
** Returns:	
**___________________________________________________			     */
static int do_no_keys(db,rec)			   /*                        */
  DB	 db;					   /*                        */
  Record rec;					   /*                        */
{						   /*                        */
  rewrite_record(db,rec);			   /*			     */
  sort_record(rec);				   /*                        */
  mark_key(db,rec);				   /*                        */
  if ( rsc_sort || rsc_double_check )		   /*                        */
  { make_sort_key(db,rec); }		   	   /*                        */
  return 0;					   /*                        */
}						   /*------------------------*/

/*-----------------------------------------------------------------------------
** Function:	update_crossref()
** Purpose:	
**		
**
** Arguments:
**	rec
**	first_rec
** Returns:	nothing
**___________________________________________________			     */
static int update_crossref(db,rec)		   /*			     */
  DB		 db;				   /*                        */
  Record	 rec;				   /*			     */
{ register Uchar **hp;				   /*			     */
  register int   i;				   /*                        */
  Uchar		 *t,*s;			   	   /*			     */
						   /*			     */
  if ( !RecordIsXREF(rec) ) return 0;		   /*			     */
						   /*                        */
  for ( i=RecordFree(rec), hp = RecordHeap(rec);   /* search crossref field  */
	i>0 && *hp != sym_crossref;		   /*			     */
	i-=2, hp += 2 )			   	   /*			     */
  { }						   /*			     */
  if ( i <= 0 )					   /*			     */
  { DebugPrint1("*** No crossref found.");	   /*			     */
    return 0;					   /*			     */
  }						   /*			     */
						   /*			     */
  t = *++hp; t++;				   /*			     */
  (void)sp_open(t);				   /* Try to extract	     */
  if ( (s = SParseSymbol(&t)) == (Uchar*)NULL )	   /*  the crossref as symbol*/
  { return 0; }					   /*			     */
						   /*			     */
  if ( (s = db_new_key(db,s)) == (Uchar*)NULL )	   /*			     */
  { ERROR2("Crossref not found: ",(char*)s);	   /*			     */
    return 0;					   /*			     */
  }						   /*			     */
  if (rsc_key_case) { s = get_key_name(s); }	   /*                        */
  if ( (t=(Uchar*)malloc(strlen((char*)s)+3))==(Uchar*)NULL )/* get temp mem */
  { OUT_OF_MEMORY("update_crossref()"); }	   /*		             */
						   /*			     */
  (void)sprintf((char*)t,(**hp=='"'?"\"%s\"":"{%s}"),s);/* make new crossref */
  *hp = symbol(t);				   /* store new crossref     */
  free(t);					   /* free temp memory	     */
  return 0;					   /*                        */
}						   /*------------------------*/


#define equal_records(R1,R2) RecordSortkey(R1) == RecordSortkey(R2)

/*-----------------------------------------------------------------------------
** Function:	dbl_check()
** Purpose:	
**		
**
** Arguments:
**	rec
** Returns:	
**___________________________________________________			     */
static int dbl_check(db,rec)			   /*                        */
  DB	 db;					   /*                        */
  Record rec;					   /*                        */
{						   /*                        */
  if ( PrevRecord(rec) != RecordNULL		   /*                        */
       && equal_records(PrevRecord(rec),rec) )	   /*			     */
  {
    if ( !rsc_quiet )
    { Uchar *k1 = *RecordHeap(rec);
      Uchar *k2 = *RecordHeap(PrevRecord(rec));
      ErrPrint("*** BibTool WARNING: Possible double entries discovered: \n***\t");
      if ( k1 == NULL ) k1 = "";
      if ( k2 == NULL ) k2 = "";
      ErrPrint(k2);
      ErrPrint(" =?= ");
      ErrPrint(k1);
      ErrPrint("\n***\t");
      ErrPrint(RecordSortkey(rec));		   /*			     */
      ErrPrint("\n");				   /*                        */
    }						   /*                        */
    if (rsc_del_dbl)				   /*                        */
    { delete_record(db,rec); }		   	   /*                        */
    else 					   /*                        */
    { SetRecordDELETED(rec); }			   /*                        */
  }						   /*			     */
 						   /*                        */
  return 0;					   /*                        */
}						   /*------------------------*/


#ifdef DEBUG
/*-----------------------------------------------------------------------------
** Function*:	printchar()
** Purpose:	For debugging of regex.c
** Arguments:
**	c	Character to print.
** Returns:	nothing
**___________________________________________________			     */
void printchar(c)				   /*                        */
  char c;					   /*                        */
{ ErrC(c);					   /*                        */
}						   /*------------------------*/
#endif