*! mktex.ado version 2.1
*! Convert Microsoft Word documents to complete LaTeX documents
*! Authors: Wu Lianghai(AHUT), Chen Liwen(AHUT),
*!          Wu Hanyan(NUAA), Wu Xinzhuo(UB),
*!          Ma Defang(CNU)
*! Created: 30Jan2026
*! Updated: Enhanced with complete LaTeX document structure
*!           and MacOSX compatibility with global pandoc path

program define mktex, rclass
    version 18.0

    * Use explicit single-letter options with 'or' syntax
    syntax using/ [, REPLace COMPile Language(str) r c]

    * Check for single-letter options and map to full names
    if "`r'" != "" {
        local replace "replace"
    }

    if "`c'" != "" {
        local compile "compile"
    }

    local filename `"`using'"'

    di as text "{hline 70}"
    di as text "mktex - Version 2.1"
    di as text "Convert Word (.docx) to complete LaTeX document with TOC"
    di as text "Authors: Wu Lianghai, Chen Liwen, Wu Hanyan, Wu Xinzhuo, Ma Defang"
    di as text "{hline 70}"
    di as text "Converting: `filename'"

    * Basic validation: file must be .docx
    if !regexm(`"`filename'"', "\.docx$") {
        di as error "File must be a .docx file"
        exit 198
    }

    * Check if file exists
    cap confirm file `"`filename'"'
    if _rc {
        di as error "File not found: `filename'"
        exit 601
    }

    * Extract filename and path
    local basefile = subinstr(`"`filename'"', ".docx", "", .)
    local texfile = "`basefile'.tex"
    local pdffile = "`basefile'.pdf"

    di as text "Output LaTeX file: `texfile'"

    * Check output file existence if replace option not specified
    if "`replace'" == "" {
        cap confirm file "`texfile'"
        if !_rc {
            di as error "File exists: `texfile'"
            di as text "Use the 'replace' option to overwrite"
            exit 602
        }
    }

    * Step 1: Convert to LaTeX using pandoc
    di as text "{hline 40}"
    di as text "Step 1: Converting with pandoc..."

    * Create temporary file for pandoc output
    local tempfile = "`basefile'_temp.tex"

    * Determine pandoc command based on OS and global variable
    local pandoc_cmd "pandoc"

    * Check if we're on MacOSX and if global pandoc is defined
    if c(os) == "MacOSX" & `"$pandoc"' != "" {
        local pandoc_cmd `"$pandoc"'
        di as text "Using pandoc from global path: `pandoc_cmd'"
    }
    else if c(os) == "MacOSX" {
        di as text "Note: For MacOSX, you can set pandoc path in profile.do:"
        di as text "     glo pandoc /path/to/pandoc"
        di as text "Using system pandoc command..."
    }

    * Use pandoc with basic LaTeX conversion
    di as text "Running: `pandoc_cmd' `filename' -t latex -o `tempfile'"
    shell `pandoc_cmd' "`filename'" -t latex -o "`tempfile'"

    * Check if conversion was successful
    cap confirm file "`tempfile'"
    if _rc {
        di as error "Pandoc conversion failed"
        di as text "Tried command: `pandoc_cmd'"
        if c(os) == "MacOSX" {
            di as text "For MacOSX, try setting pandoc path in profile.do:"
            di as text "glo pandoc /opt/homebrew/bin/pandoc"
            di as text "or wherever pandoc is installed"
        }
        exit 603
    }

    di as text "✓ Pandoc conversion completed"

    * Step 2: Create complete LaTeX document with TOC
    di as text "{hline 40}"
    di as text "Step 2: Creating complete LaTeX document with table of contents..."

    * Determine document class based on language
    local doc_class = "article"
    local ctex_option = ""

    if "`language'" != "" {
        local lang_lower = lower("`language'")
        if regexm("`lang_lower'", "chinese|zh|cn") {
            local doc_class = "article"
            local ctex_option = "ctex"
        }
    }
    else {
        local doc_class = "article"
        local ctex_option = "ctex"
        local language = "chinese"
    }

    * Create final LaTeX file
    tempname fh_out fh_in
    cap file open `fh_out' using "`texfile'", write text replace
    if _rc {
        di as error "Cannot create output LaTeX file"
        exit 604
    }

    * Write LaTeX document header
    file write `fh_out' "% Compile with XeLaTeX or LuaLaTeX for Chinese support" _n
    file write `fh_out' "% Generated by mktex for Stata" _n
    file write `fh_out' "% Authors: Wu Lianghai, Chen Liwen, Wu Hanyan, Wu Xinzhuo, Ma Defang" _n
    file write `fh_out' "% Date: 30Jan2026" _n _n

    * Document class and packages
    file write `fh_out' "\documentclass[12pt]{`doc_class'}" _n

    * Add ctex package for Chinese if needed
    if "`ctex_option'" != "" {
        file write `fh_out' "\usepackage{ctex}" _n
    }

    file write `fh_out' "\usepackage[a4paper,margin=2.5cm]{geometry}" _n
    file write `fh_out' "\usepackage{hyperref}" _n
    file write `fh_out' "\usepackage{booktabs}" _n
    file write `fh_out' "\usepackage{graphicx}" _n
    file write `fh_out' "\usepackage{amsmath}" _n
    file write `fh_out' "\usepackage{amssymb}" _n _n

    * Hyperref configuration for clickable links
    file write `fh_out' "\hypersetup{" _n
    file write `fh_out' "    colorlinks=true," _n
    file write `fh_out' "    linkcolor=blue," _n
    file write `fh_out' "    citecolor=blue," _n
    file write `fh_out' "    filecolor=blue," _n
    file write `fh_out' "    urlcolor=blue," _n
    file write `fh_out' "    pdftitle={Document converted from: `filename'}," _n
    file write `fh_out' "    pdfauthor={mktex for Stata}" _n
    file write `fh_out' "}" _n _n

    * Document title information
    file write `fh_out' "\title{Document converted from: `filename'}" _n
    file write `fh_out' "\author{mktex for Stata}" _n
    file write `fh_out' "\date{\today}" _n _n

    * Begin document
    file write `fh_out' "\begin{document}" _n
    file write `fh_out' "\maketitle" _n
    file write `fh_out' "\tableofcontents" _n
    file write `fh_out' "\newpage" _n _n

    * Step 3: Copy converted content from temporary file
    di as text "Step 3: Copying converted content..."

    cap file open `fh_in' using "`tempfile'", read text
    if _rc {
        di as error "Cannot read temporary file"
        file close `fh_out'
        exit 605
    }

    local linenum = 0
    local charcount = 0

    * Read and copy content line by line
    file read `fh_in' line
    while r(eof) == 0 {
        local linenum = `linenum' + 1
        local charcount = `charcount' + length(`"`line'"')

        * Direct copy of content
        file write `fh_out' `"`line'"' _n

        * Display progress every 100 lines
        if mod(`linenum', 100) == 0 {
            di as text "  Copied `linenum' lines..."
        }

        file read `fh_in' line
    }

    file close `fh_in'

    * End document
    file write `fh_out' _n "\end{document}" _n
    file close `fh_out'

    * Clean up temporary file
    cap erase "`tempfile'"

    di as text "✓ Copied `linenum' lines, `charcount' characters"

    * Step 4: Post-processing and results display
    di as text "{hline 40}"

    * Verify final file was created
    cap confirm file "`texfile'"
    if _rc {
        di as error "Output LaTeX file not created!"
        exit 607
    }

    * Get file size information
    tempname fh_size
    file open `fh_size' using "`texfile'", read binary
    file seek `fh_size' eof
    local filesize = r(loc)
    file close `fh_size'

    di as text "✓ Complete LaTeX document created: `texfile'"
    di as text "✓ File size: `filesize' bytes"
    di as text "✓ Table of contents included"

    * Step 5: Compile to PDF if requested
    if "`compile'" != "" {
        di as text "{hline 40}"
        di as text "Step 4: Compiling to PDF with XeLaTeX..." _n

        * First compilation (generates TOC)
        di as text "First compilation (generates TOC)..."
        shell xelatex -interaction=nonstopmode "`texfile'"

        * Second compilation for proper TOC and references
        di as text "Second compilation (updates TOC)..."
        shell xelatex -interaction=nonstopmode "`texfile'"

        * Check if PDF was created successfully
        cap confirm file "`pdffile'"
        if !_rc {
            * Get PDF file size
            tempname fh_pdf
            file open `fh_pdf' using "`pdffile'", read binary
            file seek `fh_pdf' eof
            local pdfsize = r(loc)
            file close `fh_pdf'

            di as text "✓ PDF created successfully: `pdffile'"
            di as text "✓ PDF size: `pdfsize' bytes"
            di as text "✓ Table of contents is functional in PDF"
        }
        else {
            di as text "Note: PDF compilation may need manual intervention"
            di as text "Try manual compilation: xelatex `texfile'"
            di as text "(Run twice for proper table of contents)"
        }

        di as text "{hline 40}"
    }

    * Final summary
    di as text "{hline 70}"
    di as text "✓ Conversion completed successfully!"
    di as text "Output LaTeX file: `texfile'"
    di as text "Features: Complete document structure with table of contents"

    if "`compile'" != "" {
        cap confirm file "`pdffile'"
        if !_rc {
            di as text "Output PDF file: `pdffile'"
            di as text "PDF includes clickable table of contents"
        }
    }

    di as text "{hline 70}"

    * Return results to calling program
    return local texfile "`texfile'"
    return local pdffile "`pdffile'"
    return scalar lines = `linenum'
    return scalar charcount = `charcount'
    return scalar filesize = `filesize'
    return scalar success = 1

    * Display help message for MacOSX users if global not set
    if c(os) == "MacOSX" & `"$pandoc"' == "" {
        di as text _n "Note for MacOSX users:"
        di as text "To ensure pandoc works correctly, add this line to your profile.do:"
        di as text "    glo pandoc /path/to/pandoc"
        di as text "Common locations:"
        di as text "    /opt/homebrew/bin/pandoc  (Homebrew)"
        di as text "    /usr/local/bin/pandoc     (MacPorts)"
        di as text "    /Applications/pandoc/bin/pandoc (Direct install)"
    }
end