import sys
import os
import re

global fileData
fileData = {}

def readFile(name):
    text = ""
    with open(name) as f:
        for l in f:
            text += l
    return text

def basePath(name):
    p = os.path.dirname(name)
    if p != "":
        p = p + "/"
    return p

def getFile(name, path=None):
    global fileData
    if path is None:
        path = basePath(name)
    if name not in fileData:
        fileData[name] = readFile(name)
        fileData[name] = parse(fileData[name], path)
    return fileData[name]

def parse(text, path=None):
    c = re.compile("!\[\[([^]]*)]]")
    tPath = path or ""
    for m in c.findall(text):
       text = text.replace(f"![[{m}]]", "\n" + getFile(tPath + m + ".md", path)) 
    c = re.compile("\[\[([^]]*)]]")
    for m in c.findall(text):
       text = text.replace(f"[[{m}]]", "\n" + getFile(tPath + m + ".md", path)) 
    return text

if __name__ == "__main__":
    fileData = {}
    for arg in sys.argv[1:]:
        print(getFile(arg, basePath(arg)))
