(* Fixing *.bib file *)
ClearAll["Global`*"];
bibstyle = "plain";
dir = NotebookDirectory[];
SetDirectory[dir];
file = "refs.bib";
txt = Import[file, "Text"];
trefs = StringCases[txt, 
   RegularExpression["(?s)@(\\w+)[{](\\w*)[,](.*?)\n[}]"]];
refs = StringCases[txt, 
   RegularExpression["(?s)@(\\w+)[{](\\w*)[,](.*?)\n[}]"] :> {"$1", 
     "$2", "$3"}];
mrefs = Length[refs];
{types, keys, fields} = Transpose[refs];
Print["Read ", mrefs, " references of types: ", 
  types // Union // TableForm];
(* Re-numeration *)
smrefs = ToString[mrefs];
mdig = StringLength[smrefs];
keys = Table[
   StringTake[ToString[10^(mdig + 3) + n], -mdig], {n, mrefs}];
(* Reading AUTHOR field *)
authors = Table[
   field = fields[[n]];
   author = 
    StringCases[field, 
     RegularExpression[
       "(?i)(?s)\\Wauthor\\s*=\\s*[ ][{](.*?)[}](([,]\\s)|(\\s*$))"] :>
       "$1"];
   m = Length[author];
   If[m == 0, 
    Print["Error: no AUTHOR found in the reference No.", n, 
     refs[[n]]];
    author = {"NoAuthorFieldFound"}];
   If[m > 1, 
    Print["Error: Multiple AUTHOR field found in the reference No.", 
     n, refs[[n]], "Authors: ", author]];
   author[[1]], {n, mrefs}];
(* Reading TITLE field *)
titles = Table[
   field = fields[[n]];
   title = 
    StringCases[field, 
     RegularExpression[
       "(?i)(?s)\\Wtitle\\s*=\\s*[ \
]\"[{](.*?)[}]\"(([,]\\s)|(\\s*$))"] :> "$1"];
   If[title === {},
    title = 
     StringCases[field, 
      RegularExpression[
        "(?i)(?s)\\Wtitle\\s*=\\s*[ ][{](.*?)[}](([,]\\s)|(\\s*$))"] :>
        "$1"]];
   m = Length[title];
   If[m == 0, 
    Print["Error: no TITLE found in the reference No.", n, 
     refs[[n]]];
    title = {"NoTitleFieldFound"}];
   If[m > 1, 
    Print["Error: Multiple TITLE field found in the reference No.", n,
      refs[[n]], "Titles: ", title]];
   title[[1]], {n, mrefs}];
(* Fixing titles *)
newwords = {};
mywords = Import["mydict.txt", "Lines"];
reps = Get["titlefix.txt"];
titles = Table[
   title = titles[[n]];
   If[StringMatchQ[title, RegularExpression[".*[a-z].*"]],
    Goto[endtitle]]; (* Don't change title *)
   While[StringMatchQ[title, 
     RegularExpression["(?s).*?(^|\\W)[A-Z]\\w*($|\\W).*"]],
    word = 
     StringReplace[title, 
      RegularExpression["(?s).*?(^|\\W)([A-Z]\\w*)($|\\W).*"] :> 
       "$2"];
    rwords = 
     Select[mywords, StringMatchQ[word, #, IgnoreCase -> True] &];
    If[rwords === {},
     rwords = DictionaryLookup[word, IgnoreCase -> True]];
    If[rwords === {},
     word = 
      ToUpperCase[StringTake[word, 1]] <> 
       ToLowerCase[StringTake[word, {2, StringLength[word]}]];
     newwords = Append[newwords, word],
     word = rwords[[1]]];
    word = 
     StringReplace[word, 
      RegularExpression["^([A-Z])(.*)$"] :> "uppercase$1$2"];
    title = 
     StringReplace[title, 
      RegularExpression["(?s)^(.*?)(^|\\W)([A-Z]\\w*)($|\\W)(.*)$"] :>
        "$1$2" <> word <> "$4$5"]];
   title = StringReplace[title, "uppercase" -> ""];
   title = 
    StringReplace[title, 
     RegularExpression["(?s)^(\\W*?)(\\w)(.*)$"] :> 
      "$1" <> ToUpperCase["$2"] <> "$3"];
   Label[endtitle];
   (* Fine-tuning *)
   title = StringReplace[title, reps];
   (* Fixing field *)
   oldfield = fields[[n]];
   newfield = 
    StringCases[oldfield, 
     RegularExpression[
       "(?i)(?s)^(.*\\Wtitle\\s*=\\s*[ \
]\"[{])(.*?)([}]\"(([,]\\s.*)|(\\s*$)))"] :> "$1" <> title <> "$3"];
   If[newfield === {},
    newfield = 
      StringCases[oldfield, 
       RegularExpression[
         "(?i)(?s)^(.*\\Wtitle\\s*=\\s*[ \
][{])(.*?)([}](([,]\\s.*)|(\\s*$)))"] :> "$1" <> title <> "$3"];
    ];
   If[newfield === {},
    Print[
     "Internal error: Unable to replace a title in the field No. ", n,
      ": ", oldfield, title]];
   fields[[n]] = newfield[[1]];
   title, {n, mrefs}];
newwords = Union[newwords];
Export["newdict.txt", newwords, "Text"];
(* Copy newdict.txt to mydict.txt and capitalize some letters if \
necessary! *) 
Export["newtitles.txt", titles, "Lines"];
(* Reading YEAR field *)
years = Table[
   field = fields[[n]];
   year = 
    StringCases[field, 
     RegularExpression[
       "(?i)(?s)\\Wyear\\s*=\\s*[ ][{](.*?)[}](([,]\\s)|(\\s*$))"] :> 
      "$1"];
   m = Length[year];
   If[m == 0, 
    Print["Error: no YEAR found in the reference No.", n, refs[[n]]];
    author = {"NoYearFieldFound"}];
   If[m > 1, 
    Print["Error: Multiple YEAR field found in the reference No.", n, 
     refs[[n]], "Authors: ", year]];
   year[[1]], {n, mrefs}];
(* Exporting new *.bib *)
trefs = Table[
   "@" <> types[[n]] <> "{" <> keys[[n]] <> "," <> fields[[n]] <> 
    "}\n\n", {n, mrefs}];
txt = StringJoin @@ trefs;
Export["fixedrfs.bib", txt, "Text"];
(* Sorting in YAT order *)
dyears = Union[years];
Print["Different years: ", dyears];
yats = Table[{years[[n]], authors[[n]], titles[[n]], keys[[n]]}, {n, 
    mrefs}];
yorders = Table[
   ats = Select[yats, #[[1]] === year &];
   ats = SortBy[ats, #[[{2, 3}]] &];
   yorder = Transpose[ats][[4]];
   {year, yorder}, {year, dyears}];

(* Generating LaTeX file for printing all references *)
txt = "\\documentclass{article}
   \\begin{document}
   \\bibliographystyle{" <> bibstyle <> "}
   \\bibliography{fixedrfs}
   % Produces the bibliography via BibTeX.
   \\nocite{*}
   \\end{document}";
Export["allrefs.tex", txt, "Text"];
Print["Running BibTeX and creating allrefs.bbl ..."];
If[FileType["allrefs.bbl"] === File, DeleteFile["allrefs.bbl"]];
Run["bibtex allrefs"];
Print["For possible warnings, see log file allrefs.blg"];
Print["Running LaTeX and creating list of all references (this step \
could be skipped) ..."];
If[FileType["allrefs.dvi"] === File, DeleteFile["allrefs.dvi"]];
Run["latex allrefs"];
Print["For possible warnings, see log file allrefs.log"];
Print["See printed list of all references in a file allrefs.dvi"];
(* Reading BBL file *)
txt = Import["allrefs.bbl", "Text"];
txt = StringSplit[txt, "\n\n"];
txt1 = First[txt];
txt = Drop[txt, 1];
txt2 = Last[txt];
bibs = Drop[txt, -1];
mbibs = Length[bibs];
If[mrefs != mbibs,
  Print["Warning: possible error: mrefs\[NotEqual]mbibs: ", {mrefs, 
    mbibs}]];
bibk[_] := "Undefined bib-item";
bkeys = Table[
   bib = bibs[[n]];
   key = StringCases[bib, 
     RegularExpression[".*\\\\bibitem[{](\\w*)[}]\n.*"] :> "$1"];
   m = Length[key];
   If[m == 0, 
    Print["Error: no KEY found in the bibitem No.", n, bib];
    key = {"NoKeyFieldFound"}];
   If[m > 1, 
    Print["Error: Multiple KEY field found in the bibitem No.", n, 
     bib]];
   key = key[[1]];
   bibk[key] = bib;
   key, {n, mbibs}];
(* Creating final LaTeX file *)
txt = "\\documentclass[12pt]{article}
  \\usepackage{graphicx}
  \\begin{document}
  \\title{Bibliography for $D$-scaling}
  \\date{}
  \\maketitle
  \\begin{minipage}[c]{0.8\\textwidth}
  {\\includegraphics[width=5.0in]{ppy}}
  \\end{minipage}
  ";
label = 0;
Do[
  {y, order} = yorder;
  txt = txt <>
    "\n\\renewcommand\\refname{Year " <> y <> 
    "}\n\n\\begin{thebibliography}{" <> smrefs <> "}\n\n";
  (* For other than article, replace refname -> bibname *)
  Do[
   bib = bibk[k];
   label++;
   bib = StringReplace[bib, 
     "\\bibitem{" -> "\\bibitem[" <> ToString[label] <> "]{"];
   txt = txt <> bib <> "\n\n", {k, order}];
  txt = txt <> "\end{thebibliography}\n\n", {yorder, yorders}];
txt = txt <> "\\end{document}";
Export["final.tex", txt, "Text"];
(* Generating diagram of publications per year *)
ys = ToExpression[years];
miny = Min[ys];
maxy = Max[ys];
npub[year_] := 0;
Do[
  {y, o} = yorder;
  npub[y // ToExpression] = Length[o];
  , {yorder, yorders}];
data = Table[{y, npub[y]}, {y, miny, maxy}];
plt = ListLinePlot[data, ColorFunction -> "Rainbow", Filling -> Axis,
  Frame -> True, 
  FrameLabel -> {"Year", "Number of publications per year"},
  ImageSize -> 400, PlotRange -> All, AspectRatio -> 1/2]
Export["C:\\temp\\ppy.gif", plt, ImageResolution -> 150];
Export["ppy.pdf", plt];
Print["Running PDFLaTeX and creating final PDF file ..."];
Run["pdflatex final"];