'''
Created on 23-03-2012

@author: mlenart
'''
import sys
import os
import logging
from utils import *

def checkAndCorrect(teiRoot, pmlRoot, what, correct=False):
    for teiFile in execute('find "%s" -name ann_%s.xml | sort' % (teiRoot, what)):
        context = etree.iterparse(teiFile, tag="{%s}p" % teins)
        print teiFile
        for _, par in context:
            teiId = os.path.basename(os.path.dirname(teiFile)).replace('-', '')
#            print 'grep -rl "%s" `find "%s" -name "NKJP_1M_%s-*.xml"`' % (getXmlId(par).replace('named', 'morph'), pmlRoot, teiId)
            pmlFile = execute('grep -rl "%s" `find "%s" -name "NKJP_1M_%s-*.xml"`'
                    % (getXmlId(par).replace(what, 'morph'), pmlRoot, teiId))[0]
#            print teiFile, getXmlId(par), pmlFile
            pmlTree = etree.parse(pmlFile)
            for seg in xpath(par, './tei:s/tei:seg'):
#                print getXmlId(seg), getXmlId(seg).replace(what, 'morph')
                pmlSeg = xpath(
                               pmlTree, 
                               '//*[@id="%s" or @id="%s"]'
                               % (getXmlId(seg), getXmlId(seg).replace(what, 'morph')))[0]
                teiOrth = xpath(seg, './/tei:f[@name="orth"]/tei:string/text()')[0]
                pmlOrth = xpath(pmlSeg, 'pml:orth/text()')[0]
                if teiOrth != pmlOrth:
                    logging.warn(
                                 '%s#%s --- Orths do not match: "%s" != "%s"', 
                                 pmlFile, 
                                 pmlSeg.attrib['id'], 
                                 pmlOrth, 
                                 teiOrth)
            par.clear()

if __name__ == "__main__":
    TEI_ROOT = sys.argv[1]
    PML_ROOT = sys.argv[2]
    what = sys.argv[3]
    checkAndCorrect(TEI_ROOT, PML_ROOT, what)
