#!/usr/bin/bash
# -*- coding: utf-8 -*-

import re
import glob
import codecs
import os.path
import argparse

parser = argparse.ArgumentParser("Replace ((())) with spans for sub_footnotes in markdownfiles")
parser.add_argument('folder', help="Folder with the bookfolders with markdownfiles")
args = parser.parse_args()

for bookfolder in glob.glob("{0}/book*".format(os.path.normpath(args.folder))):
  for mdpath in glob.glob("{0}/*.md".format(os.path.normpath(bookfolder))):
    print mdpath

    mdstring = None

    with codecs.open(mdpath, mode='r', encoding='utf-8') as mdfile:
      mdstring = mdfile.read()
      mdstring = re.sub(r"\({3}(.+?)\){3}", "<span class=\"drifted_footnotes\">\g<1></span>", mdstring, flags=re.MULTILINE+re.DOTALL)
      
      # \#for m in re.findall(r"\({3}", mdstring, re.MULTILINE):
      # for m in re.findall(r"\({3}.+?\){3}", mdstring, re.MULTILINE+re.DOTALL):
      #   print m, '\n\n';

    # print mdstring

    if mdstring:
      with codecs.open(mdpath, mode='w', encoding='utf-8') as mdfile:
        mdfile.write(mdstring)