#include <config.h>
#include "xctype.h"
#include "xstring.h"

RCSID("$Id: fix.c,v 1.6 1999/05/20 13:36:45 beebe Exp beebe $")

#include "yesorno.h"
#include "token.h"

#define SKIP_SPACE(p)	while (isspace((unsigned char)*p)) ++p

typedef struct s_name_pair
{
    const char *old_name;
    const char *new_name;
} NAME_PAIR;

extern char	current_value[];	/* string value */
extern YESorNO	fix_font_changes; 	/* brace {\em E. Coli}? */
extern YESorNO	fix_initials;		/* reformat A.U. Thor?	*/
extern YESorNO	fix_names;		/* reformat Bach, P.D.Q? */
extern NAME_PAIR month_pair[];
extern YESorNO	Scribe;			/* Scribe format input */

extern YESorNO	check_junior ARGS((const char *last_name_));
extern void	check_length ARGS((size_t n_));
extern char	shared_string[MAX_TOKEN_SIZE];

static void	brace_font_changes ARGS((void));
char		*fix_author ARGS((char *author_));
void		fix_month ARGS((void));
void		fix_namelist ARGS((void));
void		fix_pages ARGS((void));
char		*fix_periods ARGS((char *author_));
void		fix_title ARGS((void));
static const char *month_token ARGS((const char *s_, size_t *p_len_));


static void
brace_font_changes(VOID)
{
    int b_level;			/* brace level */
    size_t k;				/* index into current_value[] */
    size_t m;				/* index into s[] */
    YESorNO need_close_brace;
    char *p;				/* pointer into current_value[] */
    char *s = shared_string;		/* memory-saving device */

    /*******************************************************************
      If the user has coded a title string like

      "Signal-transducing {G} proteins in {\em Dictyostelium Discoideum}"

      or

      "Signal-transducing {G} proteins in {\em {D}ictyostelium {D}iscoideum}"

      BibTeX styles that downcase titles will downcase the name
      Dictyostelium Discoideum, even WITH the protecting braces around
      the D's.  The solution offered by this function is to rewrite
      the title string as

      "Signal-transducing {G} proteins in {{\em Dictyostelium Discoideum}}"

      This action cannot be taken without forethought, because there
      are many cases where the downcasing inside font changes is
      consistent, so the default run-time option is -no-fix-font-changes.

    *******************************************************************/

    for (b_level = 0, k = 0, m = 0, need_close_brace = NO;
	 current_value[k] ; ++k, ++m)
    {
	switch (current_value[k])
	{
	case '{':			/* '}' for balance */
	    b_level++;
	    if (b_level == 1)
	    {
		p = &current_value[k+1];
		SKIP_SPACE(p);
		if (*p == '{')		/* '}' for balance */
		    break;		/* already have extra brace level */
		if (
		    (strncmp(p,"\\bf",3) == 0) ||
		    (strncmp(p,"\\em",3) == 0) ||
		    (strncmp(p,"\\it",3) == 0) ||
		    (strncmp(p,"\\rm",3) == 0) ||
		    (strncmp(p,"\\sf",3) == 0) ||
		    (strncmp(p,"\\sl",3) == 0) ||
		    (strncmp(p,"\\tt",3) == 0) )
		{
		    s[m++] = '{';	/* '}' for balance */
		    need_close_brace = YES;
		}
	    }
	    break;
			/* '{' for balance */
	case '}':
	    if ((b_level == 1) && (need_close_brace == YES))
	    {				/* '{' for balance */
		s[m++] = '}';
		need_close_brace = NO;
	    }
	    b_level--;
	    break;

	default:
	    break;
	}
	s[m] = current_value[k];
    }
    s[m] = '\0';			/* terminate collected string */
    (void)strcpy(current_value, s);
}


#if defined(HAVE_STDC)
char *				/* normalize author names and return */
fix_author(char *author)	/* new string from static space */
#else /* K&R style */
char *
fix_author(author)		/* normalize author names and return */
char *author;			/* new string from static space */
#endif
{
    size_t a;			/* index into author[] */
    int b_level;		/* brace level */
    char *p;			/* pointer into author[] */
    char *pcomma;		/* pointer to last unbraced comma in author[] */
    static char s[MAX_TOKEN_SIZE]; /* returned to caller */

    /* Convert "Smith, J.K." to "J. K. Smith" provided "," and "." are */
    /* at brace level 0 */

    if (fix_names == NO)
	return (author);

    /* Leave untouched entries like: */
    /* author = "P. D. Q. Bach (113 MozartStrasse, Vienna, Austria)" */
    if (strchr(author,'(') != (char*)NULL)
	return (author);

    /*******************************************************************
      We now have a tricky job.  Some names have additional parts,
      which BibTeX calls "von" and "Jr.".  It permits them to be input
      as (see L. Lamport, ``LaTeX User's Guide and Reference Manual'',
      pp. 141--142)

		Brinch Hansen, Per	OR	Per {Brinch Hansen}
		Ford, Jr., Henry	OR	Henry {Ford, Jr.}
		{Steele Jr.}, Guy L.	OR	Guy L. {Steele Jr.}
		von Beethoven, Ludwig	OR	Ludwig von Beethoven
		{von Beethoven}, Ludwig	OR	Ludwig {von Beethoven}

      The last two lines are NOT equivalent; the first will be
      alphabetized under Beethoven, and the second under von.

      Other examples include names like

		Charles XII, King	OR	King Charles XII
		Ford, Sr., Henry	OR	Henry {Ford, Sr.}
		Vallee Poussin, C. L. X. J. de la 	OR
			C. L. X. J. de la Vallee Poussin
		van der Waerden, Bartel Leendert	OR
			Bartel Leendert van der Waerden

      These transformations conform to the general patterns

		B, A		-->	A B
		B C, A		-->	A B C		(von case)
		B C, A		-->	A {B C}		(Brinch Hansen case)
		B, C, A		-->	A {B, C}	(Jr. case)

      A, B, and C represent one or more space-separated words, or
      brace-delimited strings with arbitrary contents.

      Notice the conflict: the von case differs from Brinch Hansen in
      that braces may NOT be inserted when the name is reordered,
      because this changes the alphabetization.

      In order to deal with this ambiguity, we supply braces in the
      "B C, A" case ONLY when the C part matches something like Jr
      (see the juniors[] table above), or when it looks like a small
      number in Roman numerals.  The latter case is uncommon, and we
      therefore don't bother to attempt to parse it to determine
      whether it is a valid number.

      The "B, C, A" case (multiple level-zero commas) is unambiguous,
      and can be converted to the form "A {B, C}".
    *******************************************************************/

    for (a = 0, b_level = 0, pcomma = (char*)NULL; author[a]; ++a)
    {				/* convert "Smith, John" to "John Smith" */
	switch (author[a])
	{
	case '{':
	    b_level++;
	    break;

	case '}':
	    b_level--;
	    break;

	case ',':
	    if (b_level == 0)
		pcomma = &author[a];	/* remember last unbraced comma */
	    break;

	default:
	    break;
	}
    }
    if (pcomma == (char*)NULL)		/* no commas, so nothing more to do */
	return (author);

    *pcomma = '\0';			/* terminate "Smith" */

    /* have "Smith, J.K." or "Smith, Jr., J.K." */
    p = pcomma + 1;
    SKIP_SPACE(p);
    (void)strcpy(s,p);			/* s <- "J.K." */
    (void)strcat(s," ");		/* s <- "J.K. " */

    if (check_junior(author) == YES)
    {
	(void)strcat(s,"{");
	(void)strcat(s,author);		/* s <- "J.K. {Smith, Jr.}" */
	(void)strcat(s,"}");
    }
    else
	(void)strcat(s,author);		/* s <- "J.K. Smith" */

    return (strcpy(author,s));
}


void
fix_month(VOID)			/* convert full month names to macros*/
{				/* for better style-file customization */
    size_t k;				/* index into month_pair[] and s[] */
    size_t token_length;		/* token length */
    const char *p;			/* pointer to current_value[] */
    char *s = shared_string;		/* memory-saving device */
    const char *token;			/* pointer into current_value[] */

    for (p = current_value;
	 (token = month_token(p,&token_length)) != (const char*)NULL;
	 p = (const char*)NULL)
    {
	if (token_length == 1)		/* just copy single-char tokens	 */
	   *s++ = *token;
	else
	{
	    for (k = 0; month_pair[k].old_name != (const char*)NULL; ++k)
	    {
		if ((strlen(month_pair[k].old_name) == token_length) &&
		    (strnicmp(month_pair[k].old_name,token,token_length) == 0))
		{			/* change "January" to jan etc. */
		    (void)strcpy(s,"\" # ");
		    if ((s >= (shared_string + 1)) &&
			(strncmp(s-1,"\"\" # ",5) == 0))
		    {	/* eliminate any concatenation with an empty string */
			s--;
			*s = '\0';	/* need string terminator for strcat() */
		    }
		    (void)strcat(s,month_pair[k].new_name);
		    (void)strcat(s," # \"");
		    s = strchr(s,'\0');
		    token_length = 0;	/* so we don't copy twice at loop end */
		    break;		/* exit loop after first substitution */
		}
	    }				/* end for (k = 0, ...) */
	    (void)strncpy(s,token,token_length); /* no definition, just copy */
	    s += token_length;
	}
	if ((s >= (shared_string + 5)) && (strncmp(s-5," # \"\"",5) == 0))
	    s -= 5;	/* eliminate any concatenation with an empty string */
    }
    *s = '\0';				/* supply string terminator */
    k = (size_t)(s - shared_string);
    s = shared_string;
    if (strncmp(s,"\"\" # ",5) == 0)
	(void)strcpy(current_value,&s[5]); /* discard initial empty string */
    else
	(void)strcpy(current_value,s);
}


void
fix_namelist(VOID)		/* normalize list of personal names */
{				/* leaving it in global current_value[] */
    size_t m;			/* index of start of author in current_value[]*/
    size_t n;			/* length of current_value[], less 1 */
    char namelist[MAX_TOKEN_SIZE];	/* working copy of current_value[] */
    size_t v;			/* loop index into current_value[] */

    /* Convert "Smith, J.K. and Brown, P.M." to */
    /* "J. K. Smith and P. M. Brown" */
    /* We loop over names separated by " and ", and hand each off */
    /* to fix_author() */

    n = strlen(current_value) - 1;	/* namelist = "\"...\"" */

    if ((current_value[0] != '"') ||
	(current_value[n] != '"')) /* sanity check */
	return;			/* not quoted string, may be macro */

    (void)strcpy(namelist,"\"");/* supply initial quotation mark */
    current_value[n] = (char)'\0';	/* clobber final quotation mark */
    for (v = 1, m = 1; v < n; ++v) /* start past initial quotation mark */
    {
	if (strncmp(" and ",&current_value[v],5) == 0)
	{
	    current_value[v] = (char)'\0';
	    (void)strcat(namelist,fix_periods(fix_author(&current_value[m])));
	    (void)strcat(namelist," and ");
	    current_value[v] = (char)' ';
	    v += 4;
	    m = v + 1;
	}
	else if ((Scribe == YES) && (current_value[v] == ';'))
	{				/* expand semicolons to " and " */
	    current_value[v] = (char)'\0';
	    (void)strcat(namelist,fix_periods(fix_author(&current_value[m])));
	    (void)strcat(namelist," and ");
	    current_value[v] = (char)' ';
	    m = v + 1;
	}
    }
    (void)strcat(namelist,fix_periods(fix_author(&current_value[m])));
					/* handle last author */
    (void)strcat(namelist,"\"");	/* supply final quotation mark */
    (void)strcpy(current_value,namelist);
}


void
fix_pages(VOID)
{
    size_t k;			/* index into current_value[] */
    size_t m;			/* index into new_value[] */
    char new_value[MAX_TOKEN_SIZE]; /* working copy of new_value[] */
    char last_char;

    last_char = ' ';
    for (m = 0, k = 0; current_value[k]; ++k)
    {				/* squeeze out spaces around hyphens */
				/* and convert hyphen runs to en-dashes */
	if (current_value[k] == '-')
	{			/* convert hyphens to en-dash */
	    for ( ; (m > 0) && Isspace(new_value[m-1]) ; )
		--m;		/* discard preceding spaces */
	    for ( ; current_value[k+1] == '-'; )
		++k;
	    for ( ; Isspace(current_value[k+1]); )
		++k;		/* discard following spaces */
	    new_value[m++] = (char)'-'; /* save an en-dash */
	    /* [04-Mar-1996] force en-dash between digit pairs,
	       alpha pairs, and digit-alpha pairs, but not otherwise,
	       so ``pages = "A-3-A-7"'' is converted to
	       ``pages = "A-3--A-7"''. */
	    if ((Isdigit(last_char) && Isdigit(current_value[k+1])) ||
	        (Isalpha(last_char) && Isalpha(current_value[k+1])) ||
	        (Isdigit(last_char) && Isalpha(current_value[k+1])) ||
		(current_value[k+1] == '?'))
		new_value[m++] = (char)'-';
	}
	else
	{
	    new_value[m++] = current_value[k];
	    if (!Isspace(current_value[k])) /* remember last non-blank non-hyphen char */
		last_char = current_value[k];
	}
    }
    new_value[m] = (char)'\0';
    (void)strcpy(current_value,new_value);
}


#if defined(HAVE_STDC)
char *
fix_periods(char *author)
#else /* K&R style */
char *
fix_periods(author)
char *author;
#endif
{
    int b_level;			/* brace level */
    size_t a;				/* index in author[] */
    size_t n;				/* index in name[] */
    char *name = shared_string;		/* memory-saving device */

    if (fix_initials == NO)
      return author;

    /* Convert "J.K. Smith" to "J. K. Smith" if "." at brace level 0 */

    for (b_level = 0, a = 0, n = 0; /* NO-OP (exit below) */ ; ++a, ++n)
    {
	name[n] = author[a];		/* copy character */
	if (author[a] == '\0')
	    break;			/* here's the loop exit */
	switch (author[a])
	{
	case '{':
	    b_level++;
	    break;

	case '}':
	    b_level--;
	    break;

	case '.':
	    if (b_level == 0)
	    {
		if ((a > 0) && Isupper(author[a-1]) && Isupper(author[a+1]))
		    name[++n] = (char)' '; /* supply space between initials */
	    }
	    break;
	}
    }
    return (name);
}


void
fix_title(VOID)				/* protect upper-case acronyms */
{
    YESorNO brace_letter;
    int b_level;			/* brace level */
    size_t k;				/* index into s[] */
    char *s = shared_string;		/* memory-saving device */
    size_t t;				/* index into title[] */

    if (current_value[0] != '\"')
	return;					/* leave macros alone */

    for (k = 0, b_level = 0, t = 0; current_value[t]; )
    {
	switch (current_value[t])
	{
	case '{':
	    b_level++;
	    s[k++] = current_value[t++];
	    break;

	case '}':
	    b_level--;
	    s[k++] = current_value[t++];
	    break;

	default:
	    if (b_level > 0)
		brace_letter = NO;	/* already braced, so no changes */
	    else if (Isupper(current_value[t]))	/* maybe brace <upper-case>+ */
	    {				/* or <upper-case><digits> */
		if (Isupper(current_value[t+1]) || Isdigit(current_value[t+1]))
		    brace_letter = YES;	/* XY -> {XY}, X11 -> {X11} */
		else if (!Isalpha(current_value[t+1]))
		{
		    if ((t == 1) && (current_value[t] == 'A'))
			brace_letter = NO; /* "A gnat" -> "A gnat" */
		    else
			brace_letter = YES; /* "The C book" -> "The {C} Book" */
		}
		else
		    brace_letter = NO;	/* everything else unchanged */
	    }
	    else if (current_value[t] == '\\') /* TeX control word? */
	    {
		size_t n;
		size_t nupper;

		for (nupper = 0, n = t + 1; Isalpha(current_value[n]); ++n)
		{			/* scan over control word */
		    if (Isupper(current_value[n]))
			nupper++;
		}
		if (n > (t + 1))	/* then saw control word */
		{
		    if (nupper > 0)	/* then saw upper case letters */
		    {			/* so must brace control word */
			s[k++] = (char)'{';
			while (t < n)
			    s[k++] = current_value[t++];
			s[k++] = (char)'}';
			if ((current_value[t] == '{') &&
			    (current_value[t+1] == '}'))
			    t += 2;	/* \TeX{} -> {\TeX} */
			else if ((current_value[t] == '\\') &&
			    (current_value[t+1] == ' '))
			    t++;	/* \TeX\<space> -> {\TeX}<space> */
			break;		/* jump out of switch() */
		    }
		}
		brace_letter = NO;
	    }
	    else
		brace_letter = NO;
	    if (brace_letter)
	    {			/* Convert XWS to {XWS} and X11 to {X11} */
		s[k++] = (char)'{';
		while (Isupper(current_value[t]) || Isdigit(current_value[t]))
		    s[k++] = current_value[t++];
		s[k++] = (char)'}';
	    }
	    else
		s[k++] = current_value[t++];
	    break;
	}
    }
    s[k] = (char)'\0';
    check_length(k);
    (void)strcpy(current_value,s);
    if (fix_font_changes == YES)
	brace_font_changes();
}


#if defined(HAVE_STDC)
static const char *
month_token(const char *s, size_t *p_len)
#else /* K&R style */
static const char *
month_token(s, p_len)
const char *s;
size_t *p_len;
#endif
{   /* Return pointer to next token in s[], with its length in *p_len */
    /* if s is NULL, the parsing continues from where it was last. */
    /* A token is either a sequence of letters, possibly with a terminal */
    /* period, or else a single character.   Outside quoted strings, all */
    /* characters are considered non-letters. This code is vaguely modelled */
    /* on Standard C's strtok() function. */

    /* Bug fix for version 2.11.4 [09-May-1998]:  Prior to this version,
       a value

           mar # "\slash" # apr

       would be incorrectly transformed

           month = mar # "\slash" # " # apr # "

       because in_quoted_string was incorrect for the remainder of
       the value.

       If the input value was changed to

           mar # "\slash " # apr

       then that space inside the quoted string preserved the
       correctness of in_quoted_string, and the output was correct.

       For version 2.11.4, the body of this function has been entirely
       rewritten to simplify the logic, and ensure its correctness. */

    static int b_level = 0;		/* remembered across calls */
    static YESorNO in_quoted_string = NO; /* remembered across calls */
    static const char *next = (const char *)NULL; /* remembered across calls */
    const char *token;			/* pointer to returned token */

    if (s != (const char*)NULL)		/* do we have a new s[]? */
    {
	next = s;			/* yes, remember it */
	b_level = 0;			/* and reinitialize state */
	in_quoted_string = NO;		/* variables */
    }

    *p_len = 0;
    token = next;

    switch (*next)
    {
    case '"':
	if (b_level == 0)
	    in_quoted_string = (in_quoted_string == YES) ? NO : YES;
	break;

    case '{':				/* '}' for brace balance */
	b_level++;
	break;
					/* '{' for brace balance */
    case '}':
	b_level--;
	break;

    default:
	break;
    }

#define ADVANCE ((*p_len)++, next++)

    if ((in_quoted_string == YES) && Isalpha(*next))
    {			/* collect possibly-dot-terminated alphabetic token */
	while (Isalpha(*next))
	    ADVANCE;
	if (*next == '.')
	    ADVANCE;
    }
    else if (*next != '\0')		/* collect single-character token */
	ADVANCE;

#undef ADVANCE

    return ((*p_len == 0) ? (const char*)NULL : token);
}
