#!/usr/bin/env python3
#
# Copyright (C) 2023 Jonathan A. Poritz
# 
# 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 3 of the License, or
# (at your option) 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.
#
# importing
#
import argparse
import warnings
import fileinput
import sys
import os
import re
import time
if not sys.warnoptions:
    warnings.simplefilter("ignore")
#
# setting up arguments
#
parser = argparse.ArgumentParser(description='Capitalizes all "figure"s in an html file such as one produced by OOprep, when in constructions such as "figure n", "fig. n".')
parser.add_argument("input_file", help="Source html file")
parser.add_argument("-l", "--logfile", help='Filename for logfile to which will be appended detailed progress information; default is "cap_figs.log".', default="cap_figs.log", type=argparse.FileType('a'))
parser.add_argument('-v', '--verbose', help="print on console all information also going in to the logfile", action='store_true')
parser.add_argument("-o", "--output", help='Name to use as output file. If absent, will be "capfig_" prepended to input file name.', default="")
args = parser.parse_args()
#
# setting up logfile and logging helper
#
args.logfile.write("------------------------------------\n")
def log_and_print(s):
  t=time.strftime('%H:%M:%S')+" "+s
  args.logfile.write(t+"\n")
  if args.verbose:
    print(t)
log_and_print("On "+time.strftime('%d/%m/%Y')+", doing ")
log_and_print(' '.join(sys.argv)+" in directory "+os.getcwd())
#
# initializing counts of found objects
#
figures = 0
figureps = 0
Figureps = 0
figs = 0
Figs = 0
figps = 0
Figps = 0
Figures = 0
#
# patterns to find those things to fix
#
figurepat = re.compile('figure ([1-9])')
figureppat = re.compile('figure\. ([1-9])')
Figureppat = re.compile('Figure\. ([1-9])')
figpat = re.compile('fig ([1-9])')
Figpat = re.compile('Fig ([1-9])')
figppat = re.compile('fig\. ([1-9])')
Figppat = re.compile('Fig\. ([1-9])')
Figurepat = re.compile('Figure ([1-9])')
#
# get input file contents for handling a few special GD classes -> HTML and
#  to import into BeautifulSoup for parsing
#
with open(args.input_file,'r') as in_fh:
  book=in_fh.read()
#
# do all the subs
#
Figuresbefore = len(Figurepat.findall(book))
(book1, figures) = figurepat.subn(r'Figure \1',book)
(book2, figureps) = figureppat.subn(r'Figure \1',book1)
(book3, Figureps) = Figureppat.subn(r'Figure \1',book2)
(book4, figs) = figpat.subn(r'Figure \1',book3)
(book5, Figs) = Figpat.subn(r'Figure \1',book4)
(book6, figps) = figppat.subn(r'Figure \1',book5)
(book7, Figps) = Figppat.subn(r'Figure \1',book6)
Figuresafter = len(Figurepat.findall(book7))
#
# summarize work done
#
log_and_print(f'''Started with {Figuresbefore} "Figure [1-9]"s before in input file.
Fixed
{figures} "figure [1-9]"s
{figureps} "figure. [1-9]"s
{Figureps} "Figure. [1-9]"s
{figs} "fig [1-9]"s
{Figs} "Fig [1-9]"s
{figps} "fig. [1-9]"s
{Figps} "Fig. [1-9]"s
ending with {Figuresafter} "Figure [1-9]"s in input file
(which {"makes sense" if (Figuresbefore+figures+figureps+Figureps+figs+Figs+figps+Figps)==Figuresafter else "is weird!"})''')
#
# build output filename either as specified or from input filename
#   should be OS indpendent
#
if args.output:
  out_fn = args.output
else:
  [dir,fn] = os.path.split(args.input_file)
  out_fn = os.path.join(dir,'capfig_'+fn)
#
# write output
#
with open(out_fn, 'w') as out_fh:
  chars_written = out_fh.write(book7)
log_and_print(f'Wrote {chars_written} characters to {out_fn}.')
log_and_print("Done (on "+time.strftime('%d/%m/%Y')+")!")
args.logfile.write("------------------------------------\n")
args.logfile.close()
