# -*- coding: utf-8 -*-

# Change log
#   20220812
#       * update rerun condition: with \usepackage[aux]{rerunfilecheck}
#
#   20220526 
#       * For index .ilg debug: copy file.xtc to file_tmp.tmp 
#
#   20220220 
#       * new version of makeglossaries (2021/11) add " to the cjk font command,
#         delete " in preprocessing  
#
#   20210420 
#       * new_env = curdir 
#
#   20200725
#      * add bmode option
#
#   20190402
#      * fix bug: in the first some entry was missing in the .bib,
#        and now it has been added. 
#   20190206
#      * line 107, 136, 156
#        destdir = config.get('paths','xtemp')
#
#   20180927:
#      * line 556: call(["ps2pdf", output_ps, outputpdf]) 
#
#   20180331:
#      * use ps2pdf.exe to convert ps to pdf
#      * fix bug in latex/dvips
#
#   20180304:
#      * First version to combine luatex and pdflatex into one file
#      * luatex = 1 for lualatex and luatex = 0 for pdflatex 
#

"""
cwtex 5.1 system
(cwtex.py, tex2xtc.py, cwbiblatex.py, cwmkidx.py, cwmkgls.py, cwcjksort, cwhtml)

Copyright (C) 2018 Tsong-Min Wu and Tsong-Huey Wu
  with support of ...

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.

You should have received a copy of the GNU General Public License along
with this program; if not, see <http://www.gnu.org/licenses/>
"""

import os
import sys
import shutil
import configparser
import logging
import fileinput
import re

import time
start_time_cwpdf = time.time()

def replace_str(source, str_ori, str_new):
    f = open(source, 'r', encoding='utf-8')
    filedata = f.read()
    f.close()
    newdata = filedata.replace(str_ori, str_new)
    f = open(source, 'w', encoding='utf-8')
    f.write(newdata)
    f.close()

# from sys import argv
# script, editor, inputfile = argv

# set up logging to file
#     logging.basicConfig(
#          filename="cwpdf.xlg",
#          level=logging.INFO,
#          format= '%(message)s',
#          datefmt='%H:%M:%S'
#      )
    # set up logging to console
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(message)s')
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)
    logger = logging.getLogger(__name__)

import argparse
parser = argparse.ArgumentParser(description="cwtex preprocessor version 5.1")
parser.add_argument("infile")

parser.add_argument("-winedt", "--winedt", action="store_true", help="using winedt")
parser.add_argument("-ts_win", "--ts_win", action="store_true", help="using texstudio (Windows)")
parser.add_argument("-texshop", "--texshop", action="store_true", help="using texshop")
parser.add_argument("-ps", "--ps", action="store_true", help="typesetting with latex, dvips, and ps2pdf")

# parser.add_argument("-o", "--outputname", help="speccify output filename")
args = parser.parse_args()

luatex = 0    # luatex = 1 is the default, and cwtex will output utf8 
              # luatex = 0, cwtex will add "-l" option to output latin1
              # This only affect \verb and verbatim

ctx = 0       # file extension will be detected later; ctx = 1 means file extension is .ctx
               
if args.infile:
    inputfile = args.infile

# editor = winedt, texstudio_win, texshop, ...

curdir = os.getcwd()
config = configparser.ConfigParser()
config.sections()
cwtexini = os.path.join(sys.path[0], "cwtex.ini")

if config.read(cwtexini):
    #destdir = config['paths']['xtemp']
    destdir = config.get('paths','xtemp')
else:
    destdir = curdir

# TEXINPUTS= 加入 current dir and immediate subdirectories
#
# texlive is TEXINPUTS=/path/to/the/local/folder//:
# where // means subdirectory. Note that path seperator is : instead of ;
# miktex also use //
# in texlive, you have to add .: in the beginning, and use capital letter
# for TEXINPUTS

if args.winedt or args.ts_win:
    if os.environ.get('TEXINPUTS') is None:
        new_env = curdir + "//"
    else:
        new_env = os.environ.get('TEXINPUTS') + ';' + curdir + "//"
#        new_env = curdir + ';' + curdir + "//" + ';' + os.environ.get('TEXINPUTS')        

    if config.read(cwtexini):
        if config['paths']['TEXINPUTS'] != "":
            new_env = config['paths']['TEXINPUTS'] + ';' + new_env
elif args.texshop:
    if os.environ.get('TEXINPUTS') is None:
        new_env = ".:" + curdir + "//:"
    else:
        new_env = os.environ.get('TEXINPUTS') + ':' + curdir + "//"
    if config.read(cwtexini):
        #if config['paths']['TEXINPUTS'] != "":
        if config.get('paths','TEXINPUTS') != "": 
            new_env = config.get('paths','TEXINPUTS') + ':' + new_env
os.environ['TEXINPUTS'] = new_env

if args.winedt or args.ts_win:
    if os.environ.get('BIBINPUTS') is None:
        bib_env = curdir + "//"
    else:
        bib_env = os.environ.get('BIBINPUTS') + ';' + curdir + "//"

    if config.read(cwtexini):
        if config['paths']['BIBINPUTS'] != "":
            bib_env = config['paths']['BIBINPUTS'] + ';' + bib_env
elif args.texshop:
    if os.environ.get('BIBINPUTS') is None:
        bib_env = ".:" + curdir + "//:"
    else:
        bib_env = os.environ.get('BIBINPUTS') + ':' + curdir    # mac cannot use "//" ?

    if config.read(cwtexini):
        #if config['paths']['BIBINPUTS'] != "":
        if config.get('paths','BIBINPUTS') != "":
            bib_env = config.get('paths','BIBINPUTS') + ':' + bib_env
os.environ['BIBINPUTS'] = bib_env

from subprocess import call

try:
    ext = inputfile.split(".")[1]
except IndexError as error:                                    # there is no file extension
    file = open(inputfile, encoding='utf-8')
    outputfile = inputfile + ".tex"
    xlogfile = inputfile + ".xlg"
    outputpdf = inputfile + ".pdf"
    ctx = 1
else:                                                          # file extension is not .tex
    if inputfile.split(".")[1] != "tex":
        file = open(inputfile, encoding='utf-8')
        outputfile = inputfile.split(".")[0] + ".tex"
        outputpdf = inputfile.split(".")[0] + ".pdf"
        xlogfile = inputfile.split(".")[0] + ".xlg"
        ctx = 1

if ctx == 1:
    curxcinput = os.path.join(curdir, "xcinput" + "." + "tex")
    destxcinput = os.path.join(destdir, "xcinput" + "." + "tex")
    cwtexpy = os.path.join(sys.path[0], "cwtex51b.py")

#   destdir's drive may be changed to upper case.
#

    if destdir != '' and destdir.lower() != curdir.lower():          # copy xcinput to curdir if exists
        if os.path.isfile(destxcinput):
            shutil.copyfile(destxcinput, curxcinput)

    if luatex == 1:                                                  # utf8
        if args.winedt or args.ts_win:
            call(["python", cwtexpy, "-a", "-c", inputfile])
        else:
            call(["python3", cwtexpy, "-a", "-c", inputfile])
    elif luatex == 0:                                               # latin-1
        if args.winedt or args.ts_win:
            call(["python", cwtexpy, "-a", "-c", "-l",  inputfile])
        else:
            call(["python3", cwtexpy, "-a", "-c", "-l", inputfile])


    if destdir != '':                                                # Move files if \xtemp defined
        if destdir != curdir:                                        # xtemp is defined, and .ctx not in xtemp directory
            if curdir.lower() != destdir.lower():
                if not os.path.exists(destdir):
                    os.mkdir(destdir)
                for file in os.listdir(curdir):
                    if file.endswith(".ctx"):                        # it is possible that .tex exists, but not .ctx
                        texfile = file.split(".")[0] + ".tex"        # so copy all the .tex, and
                        curtex = os.path.join(curdir, texfile)
                        if os.path.exists(curtex):
                            curctx = os.path.join(curdir, file)
                            destctx = os.path.join(destdir, file)
                            shutil.copyfile(curctx, destctx)
                            desttex = os.path.join(destdir, texfile)
                            shutil.copyfile(curtex, desttex)
                            os.remove(curtex)
                    if file.endswith(".ctx_xbackup"):
                        texfile = file.split(".")[0] + ".tex"
                        curtex = os.path.join(curdir, texfile)       # it is possible that .tex exists, but not .ctx
                        if os.path.exists(curtex):                   # so copy all the .tex, and
                            desttex = os.path.join(destdir, texfile)
                            shutil.copyfile(curtex, desttex)
                            os.remove(curtex)
                        os.remove(file)                              # .ctx_xbackup means .ctx was copied from somewhere,
                        ctxcopyfile = file.split(".")[0] + ".ctx"    # so we should remove .ctx as well
                        os.remove(ctxcopyfile)
                    if file.endswith(".xlg"):
                        curxlog = os.path.join(curdir, xlogfile)
                        if os.path.exists(curxlog):
                            destxlog = os.path.join(destdir, xlogfile)
                            shutil.copyfile(curxlog, destxlog)
                            os.remove(curxlog)

    #            curxcinput = os.path.join(curdir, "xcinput" + "." + "tex")
    #            destxcinput = os.path.join(destdir, "xcinput" + "." + "tex")

                shutil.copyfile(curxcinput, destxcinput)
                os.remove(curxcinput)
                os.chdir(destdir)
        else:
            for file in os.listdir(curdir):
                if file.endswith(".ctx_xbackup"):
                    os.remove(file)
                    ctxcopyfile = file.split(".")[0] + ".ctx"
                    os.remove(ctxcopyfile)
    else:                                                             # xtemp is not defined
        for file in os.listdir(curdir):                               # if .ctx was copied from somewhere, we have to remove them
            if file.endswith(".ctx_xbackup"):
                os.remove(file)
                ctxcopyfile = file.split(".")[0] + ".ctx"
                os.remove(ctxcopyfile)

    # First run of pdflatex, may already in c:\xtemp

    if luatex == 1:
        if args.winedt or args.ts_win:
            if args.ps:
                call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
            else:
                call(["lualatex", "-synctex=1", "-enable-write18", outputfile])

        elif args.texshop:
            if args.ps:
                call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
            else:
                call(["lualatex", "-synctex=1", "-enable-write18", outputfile])
    elif luatex == 0:
        if args.winedt or args.ts_win:
            if args.ps:
                call(["latex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
            else:
                call(["pdflatex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
        elif args.texshop:
            if args.ps:
                call(["latex", "-synctex=1", "-enable-write18", outputfile])
            else:
                call(["pdflatex", "-synctex=1", "-enable-write18", outputfile])

    # check if cwbibtex or cwbiblatex is needed:
    #
    # If backend=biber, there would be .bcf, get .bib from the file
    # If backend=bibtex, in examp5a.aux, there will be \bibdata{examp5a-blx,tmwu-blx,abc}
    # If backend=biber, there is examp5a.aux, but not \bibdata{examp5a-blx,tmwu-blx,abc}
    #
    # for biblatex with bibtex, there will be a file %cwfile%-blx.bib
    # for biblatex with biber, there will be a file %cwfile%.bcf; cwbiblatex can handle both case
    #
    # cwbibtex/cwbiblatex has to be run in the current directory because
    # .bib maybe in the current directory, and also the main .ctx may input other .ctx
    # grep ERRORLEVEL 0 if found; ERRORLEVEL 1 if not found
    # ERRORLEVEL 1 means equal to or greater than 1
    #
    # The warning message from bibtex+natbib contains "undefined citations";
    # The message from biblatex is "undefined references", also %cwfile%-blx.bib is generated
    #
    # "undefined references" also occurs with \label and \ref commands
    #
    # grep produce 0 if found; 1 if not found
    #
    # :checkbibtex
    # grep -c -q "undefined citations" %xdrv%:\xtemp\%cwfile%.log
    # IF %ERRORLEVEL% EQU 0 goto bibtex
    #
    # grep -c -q "undefined references" %xdrv%:\xtemp\%cwfile%.log
    # IF %ERRORLEVEL% EQU 1 goto cwidx
    #
    # if exist %xdrv%:\xtemp\%cwfile%-blx.bib goto biblatex
    # if exist %xdrv%:\xtemp\%cwfile%.bcf goto biblatex

    # Package biblatex Warning: Please (re)run Biber
    # Package biblatex Warning: Please (re)run BibTeX

    input_base = inputfile.split(".")[0]
    input_log = inputfile.split(".")[0] + ".log"
    bib_biber = input_base + ".bcf" # biblatex with biber backend

    logfile = open(input_log, 'r', encoding='latin-1')

    backend = ""
    bib = 0

    if '(re)run Biber' in open(input_log, 'r', encoding='latin-1').read():
        backend = "biber"
        bib = 1
    elif 'The following entry could not be found' in open(input_log, 'r', encoding='latin-1').read():
        backend = "biber"
        bib = 1
    elif '(re)run BibTeX' in open(input_log, 'r', encoding='latin-1').read():
        backend = "bibtex"
        bib = 1

    cwbiblatexpy = os.path.join(sys.path[0], "cwbiblatex51b.py")

    # At this point, if xtemp not defined, we are already in destdir.
    # input directories list is computed here, and sent to BIBINPUTS
    # cwbiblatex will then get expanded version of BIBINPUTS

    # if args.winedt or args.ts_win:
    #     if os.environ.get('BIBINPUTS') is None:
    #         bib_env = curdir + "//"
    #     else:
    #         bib_env = os.environ.get('BIBINPUTS') + ';' + curdir + "//"
    #
    #     if config.read(cwtexini):
    #         if config['paths']['BIBINPUTS'] != "":
    #             bib_env = config['paths']['BIBINPUTS'] + ';' + bib_env
    # elif args.texshop:
    #     if os.environ.get('BIBINPUTS') is None:
    #         bib_env = ".:" + curdir + "//:"
    #     else:
    #         bib_env = os.environ.get('BIBINPUTS') + ':' + curdir    # mac cannot use "//" ?
    #
    #     if config.read(cwtexini):
    #         if config['paths']['BIBINPUTS'] != "":
    #             bib_env = config['paths']['BIBINPUTS'] + ':' + bib_env
    # os.environ['BIBINPUTS'] = bib_env
    
    # cwbiblatex call cwtex, so we have to pass engine: luatex or pdflatex
    #
    
    if bib == 1:
        if luatex == 1:
            if backend == "biber":                                       
                if args.winedt or args.ts_win:                           
                    call(["python", cwbiblatexpy, "biber", "luatex", inputfile])     
                else:                                                    
                    call(["python3", cwbiblatexpy, "biber", "luatex", inputfile])  
            elif backend == "bibtex":                                    
                if args.winedt or args.ts_win:                           
                    call(["python", cwbiblatexpy, "bibtex", "luatex", inputfile])    
                else:                                                    
                    call(["python3", cwbiblatexpy, "bibtex", "luatex", inputfile]) 
        elif luatex == 0:
            if backend == "biber":                                       
                if args.winedt or args.ts_win:                           
                    call(["python", cwbiblatexpy, "biber", "pdftex", inputfile])     
                else:                                                    
                    call(["python3", cwbiblatexpy, "biber", "pdftex", inputfile])  
            elif backend == "bibtex":                                    
                if args.winedt or args.ts_win:                           
                    call(["python", cwbiblatexpy, "bibtex", "pdftex", inputfile])    
                else:                                                    
                    call(["python3", cwbiblatexpy, "bibtex", "pdftex", inputfile]) 
        

    #
    # check if  glossaries  package is used
    #
    #   makeindex -l -s examp7.ist -o examp7.gls examp7.glo
    #   python "c:\Program Files (x86)\cwtex4\bin\cwmkgls41b.py" examp7.ctx
    #


# 2018.2.1
# index and glossary will be processed in 3 steps:
#
#  1. tex2xtc -s: this also insert auxiliary codes for the purpose or sorting (strokes or zhuying)
#  2. cwcjksort:  preprossing and then sort by makeindex
#  3. cwmkind and cwmkgls: postprocessing to take care of different format for index and glossaries
#
# NB: index and glossary's procedure is different.
#     Glossary use .gls for formatting, and the entries are taken from glo-defns.tex.
#     Index use .ind for formatting and entries
#
#     cwcjksort is extracted from cwmkidx.
#     Currently, glossary is processed by cwcjksort + cwmkgls
#     We could alos take rewrite cwmkidx to be consistent with the above, but the two procedures are somewhat different,
#     so leave it for now.

    gloss = 0
    input_glo = inputfile.split(".")[0] + ".glo"

    if os.path.isfile(input_glo):
        gloss = 1
        cwtex_tex2xtc = os.path.join(sys.path[0], "tex2xtc51b.py")
        cwtex_sort = os.path.join(sys.path[0], "cwcjksort51b.py")
        cwtex_gloss = os.path.join(sys.path[0], "cwmkgls51b.py")

        input_xtc = inputfile.split(".")[0] + ".xtc"
        input_ist = inputfile.split(".")[0] + ".ist"
        input_gls = inputfile.split(".")[0] + ".gls"
        destdir_glo = os.path.join(destdir, input_glo)

        # Original .glo format is: {\MeQ \cH 80}\z {\MaQ \cH 130}
        # so, we have to trim extra spaces: {\MeQ\cH80}\z{\MaQ\cH130} before feeding to tex2xtc

        if os.path.exists(destdir_glo):
            replace_str(input_glo, " \cH ", "\cH")
            replace_str(input_glo, "\z {", "\z{")
            replace_str(input_glo, '"\\', '\\')              ## 2022.02.22            

            if args.winedt or args.ts_win:
                call(["python", cwtex_tex2xtc, "-s", input_glo])
            else:
                call(["python3", cwtex_tex2xtc, "-s", input_glo])

            print("cjk sorting ...")
            if args.winedt or args.ts_win:
                call(["python", cwtex_sort, "-gls", input_xtc])
            else:
                call(["python3", cwtex_sort, "-gls", input_xtc])

        if args.winedt or args.ts_win:
            call(["python", cwtex_gloss, inputfile])
        else:
            call(["python3", cwtex_gloss, inputfile])

    index = 0
    input_idx = inputfile.split(".")[0] + ".idx"
    if os.path.isfile(input_idx):
        index = 1

        input_ind = inputfile.split(".")[0] + ".ind"
        input_cjk_ind = inputfile.split(".")[0] + "_cjk.ind"       ## 2018.1.31
        input_temp_ind = inputfile.split(".")[0] + "_temp.ind"     ## 2018.1.31
        input_temp_tex = inputfile.split(".")[0] + "_temp.tex"     ## 2018.1.31
        input_tmp_tmp = inputfile.split(".")[0] + "_tmp.tmp"       ## 2022/5/26
        
        input_xtc = inputfile.split(".")[0] + ".xtc"               
        destdir_idx = os.path.join(destdir, input_idx)
        destdir_ind = os.path.join(destdir, input_ind)
        destdir_tmpind = os.path.join(destdir, input_temp_ind)
        destdir_tmptex = os.path.join(destdir, input_temp_tex)

        cwtex_tex2xtc = os.path.join(sys.path[0], "tex2xtc51b.py")
        cwtex_mkidx = os.path.join(sys.path[0], "cwmkidx51b.py")

        if os.path.exists(destdir_idx):
            if args.winedt or args.ts_win:
                call(["python", cwtex_tex2xtc, "-s", input_idx])
            else:
                call(["python3", cwtex_tex2xtc, "-s", input_idx])

            if args.winedt or args.ts_win:
                call(["python", cwtex_mkidx, "-ind", input_xtc])
            else:
                call(["python3", cwtex_mkidx, "-ind", input_xtc])

            shutil.copyfile(destdir_ind, destdir_tmpind)
            
            if luatex == 1:                                                  # utf8                
                if args.winedt or args.ts_win:                                         
                    call(["python", cwtexpy, "-a", "-c", input_temp_ind])                     
                else:                                                                  
                    call(["python3", cwtexpy, "-a", "-c", input_temp_ind])                      
            elif luatex == 0:                                               # latin-1     
                if args.winedt or args.ts_win:                                             
                    call(["python", cwtexpy, "-a", "-c", "-l", input_temp_ind])                  
                else:                                                                      
                    call(["python3", cwtexpy, "-a", "-c", "-l", input_temp_ind])                

            shutil.move(destdir_tmptex, destdir_ind)
            shutil.move(input_temp_ind, input_cjk_ind)
            shutil.copyfile(input_xtc, input_tmp_tmp)          # 2022/5/26, for debug purpose:
                        
            try:
                os.remove("cwtemp.xlg")
            except OSError:
                pass

#     After checking biblatex/glossaries/index, now the second run of pdflatex
#

    if (bib == 1 or gloss == 1 or index == 1):
        if luatex == 1:
            if args.winedt or args.ts_win:
                if args.ps:
                    call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
                else:
                    call(["lualatex", "-synctex=1", "-enable-write18", outputfile])
            elif args.texshop:
                if args.ps:
                    call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
                else:
                    call(["lualatex", "-synctex=1", "-enable-write18", outputfile])
        elif luatex == 0:
            if args.winedt or args.ts_win:
                if args.ps:
                    call(["latex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
                else:
                    call(["pdflatex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
            elif args.texshop:
                if args.ps:
                    call(["latex", "-synctex=1", "-enable-write18", outputfile])
                else:
                    call(["pdflatex", "-synctex=1", "-enable-write18", outputfile])

    #
    # No biblatex/glossaries/index, but there are label and ref
    #

    # if 'Rerun to get cross-references right.' in open(input_log, 'r', encoding='latin-1').read():
    #
    #  \usepackage[aux]{rerunfilecheck}
    # 
    # if 'Please rerun LaTeX.' in open(input_log, 'r', encoding='latin-1').read():  
    #  
    while 'Please rerun LaTeX.' in open(input_log, 'r', encoding='latin-1').read():    
        if luatex == 1:
            if args.winedt or args.ts_win:
                if args.ps:
                    call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
                else:
                    call(["lualatex", "-synctex=1", "-enable-write18", outputfile])
            elif args.texshop:
                if args.ps:
                    call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
                else:
                    call(["lualatex", "-synctex=1", "-enable-write18", outputfile])
        elif luatex == 0:
            if args.winedt or args.ts_win:
                if args.ps:
                    call(["latex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
                else:
                    call(["pdflatex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
            elif args.texshop:
                if args.ps:
                    call(["latex", "-synctex=1", "-enable-write18", outputfile])
                else:
                    call(["pdflatex", "-synctex=1", "-enable-write18", outputfile])

    #
    #  \usepackage[aux]{rerunfilecheck}
    #
    while 'Package rerunfilecheck Warning: File' in open(input_log, 'r', encoding='latin-1').read():    
        if luatex == 1:
            if args.winedt or args.ts_win:
                if args.ps:
                    call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
                else:
                    call(["lualatex", "-synctex=1", "-enable-write18", outputfile])
            elif args.texshop:
                if args.ps:
                    call(["lualatex", "-synctex=1", "-enable-write18", "-output-format=dvi", outputfile])
                else:
                    call(["lualatex", "-synctex=1", "-enable-write18", outputfile])
        elif luatex == 0:
            if args.winedt or args.ts_win:
                if args.ps:
                    call(["latex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
                else:
                    call(["pdflatex", "-synctex=1", "-enable-write18", "-stack-size=10000", "-font-mem-size=2500000", outputfile])
            elif args.texshop:
                if args.ps:
                    call(["latex", "-synctex=1", "-enable-write18", outputfile])
                else:
                    call(["pdflatex", "-synctex=1", "-enable-write18", outputfile])

    if args.ps:
        output_dvi = inputfile.split(".")[0] + ".dvi"
        output_ps = inputfile.split(".")[0] + ".ps"
        outputpdf = inputfile.split(".")[0] + ".pdf"        
#         output_pdf = inputfile.split(".")[0] + ".pdf"
        call(["dvips", output_dvi])
        if args.winedt or args.ts_win:
            call(["ps2pdf.exe", output_ps, outputpdf])        
#            shutil.copyfile(output_pdf, outputpdf)
        elif args.texshop:
            call(["ps2pdf", output_ps, outputpdf])        
#            shutil.copyfile(output_pdf, outputpdf)

    syncfile = inputfile.split(".")[0] + ".synctex"
    syncgzfile = inputfile.split(".")[0] + ".synctex.gz"

    if os.path.isfile(syncgzfile):
        if args.winedt or args.ts_win:
            call(["7z", "e", "-y", syncgzfile])
        elif args.texshop:
            call(["gunzip", "-d", "-q", syncgzfile])
        if destdir != "":
            if curdir.lower() != destdir.lower():
                if os.path.isfile(syncfile):
                    curdir_sync = os.path.join(curdir, syncfile)
                    destdir_sync = os.path.join(destdir, syncfile)

                    shutil.copyfile(destdir_sync, curdir_sync)

                    curdir_pdf = os.path.join(curdir, outputpdf)
                    destdir_pdf = os.path.join(destdir, outputpdf)
                    shutil.copyfile(destdir_pdf, curdir_pdf)

                os.chdir(curdir)

    replace_str(syncfile, ".tex", ".ctx")
    print("cwpdf run: %f seconds" % (time.time() - start_time_cwpdf))

#     inputfiletime = os.path.getmtime(os.path.join(curdir, inputfile))
#     pdftime = os.path.getmtime(os.path.join(curdir, outputpdf))
#     if (pdftime > inputfiletime):
#         print("Yes")
#         try:
#             os.system('pause')  #windows, doesn't require enter
#         except whatever_it_is:
#             os.system('read -p "Press any key to continue"') #linux
#     else:
#         print("No")
#         try:
#             os.system('pause')  #windows, doesn't require enter
#         except whatever_it_is:
#             os.system('read -p "Press any key to continue"') #linux
#         os.system("TASKKILL /F /IM SumatraPDF.exe")
#        os.system("taskkill /im SumatraPDF.exe /f")
#         print("This run is not sucessful, what you will see is the output from last run.\n")
#         try:
#             os.system('pause')  #windows, doesn't require enter
#         except whatever_it_is:
#             os.system('read -p "Press any key to continue"') #linux
# os.system("taskkill /im firefox.exe /f")

    if args.winedt or args.ts_win:
        if destdir != "":
            d_destdir = destdir.replace('\\', '/')
            replace_str(syncfile, d_destdir, curdir)
            replace_str(syncfile, destdir, curdir)

        if args.winedt:
            try:
                call(["SumatraPDF", "-reuse-instance", outputpdf])
            except OSError:
                print("Please add SumatraPDF to the path.")

    elif args.texshop:
        if destdir != "":
            replace_str(syncfile, destdir, curdir)
else:
    if inputfile.split(".")[1] == "tex":             # make sure file extension is .tex
        outputfile = inputfile.split(".")[0]
        print("\nWarning:\n Your file extension is .tex.")
        print(" If your file contains cjk charactes,")
        print(" please rename .tex to .ctx, and try again.\n")

        if args.ps:
            call(["latexmk", "-synctex=1", "-pdfps", "-pv", outputfile])
        else:
            call(["latexmk", "-synctex=1", "-pdfxe", "-pv", outputfile])

        call(["latexmk", "-c"])

        syncfile = inputfile.split(".")[0] + ".synctex"
        syncgzfile = inputfile.split(".")[0] + ".synctex.gz"

# run xelatex to produce pdf, and then use Acrobat to convert to pptx
# the following are aux files
#
        snmfile = inputfile.split(".")[0] + ".snm"
        xdvfile = inputfile.split(".")[0] + ".xdv"
        navfile = inputfile.split(".")[0] + ".nav"        

        try:                        
            os.remove(snmfile)
        except OSError:             
            pass                    

        try:                        
            os.remove(xdvfile)
        except OSError:             
            pass                    

        try:                        
            os.remove(navfile)
        except OSError:             
            pass                    





