*! _quasicoint_export.ado — LaTeX / Excel / CSV export for quasicoint
*! Version 1.0.1 — 2026-05-09 (fix: file write formatting)
*! Author: Dr. Merwan Roudane

capture program drop _quasicoint_export
program define _quasicoint_export
    version 14
    syntax , format(string) saving(string) p(integer) q(integer) ///
            k(integer) rho(real) vars(string) level(real)

    local r = `p' - `q'
    local z_crit = invnormal(1 - (1-`level'/100)/2)
    local vnames `vars'

    // =====================================================================
    //  LATEX EXPORT
    // =====================================================================
    if inlist("`format'", "latex", "all") {
        local fname "`saving'_quasicoint.tex"
        di as text "  Exporting LaTeX: `fname'"

        tempname fh
        file open `fh' using "`fname'", write replace

        file write `fh' "% quasicoint - Quasi-Cointegration Results" _n
        file write `fh' "% Generated by quasicoint.ado (Duffy & Simons 2023)" _n
        file write `fh' "\begin{table}[htbp]" _n
        file write `fh' "\centering" _n
        file write `fh' "\caption{Quasi-Cointegrating Vector Estimates}" _n
        file write `fh' "\label{tab:quasicoint}" _n
        file write `fh' "\begin{tabular}{lcccc}" _n
        file write `fh' "\toprule" _n
        file write `fh' "Variable & QCS \$\hat{\beta}\$ & Johansen \$\hat{\beta}\$ & SE & \$`level'\%\$ CI \\" _n
        file write `fh' "\midrule" _n

        tempname beta_qc beta_joh V_qc
        capture matrix `beta_qc' = _qc_beta
        capture matrix `beta_joh' = _qc_beta_joh
        capture matrix `V_qc' = _qc_V

        if _rc == 0 {
            forvalues i = 1/`p' {
                local vn : word `i' of `vnames'
                local bq = `beta_qc'[`i', 1]
                local bj = 0
                capture local bj = `beta_joh'[`i', 1]

                local s_bq : di %8.4f `bq'
                local s_bj : di %8.4f `bj'

                if `i' <= `r' {
                    file write `fh' "`vn' & `s_bq' & `s_bj' & --- & --- \\" _n
                }
                else {
                    local idx = `i' - `r'
                    local se = 0
                    if `idx' <= rowsof(`V_qc') & `idx' <= colsof(`V_qc') {
                        local se = sqrt(abs(`V_qc'[`idx', `idx']))
                    }
                    local lo = `bq' - `z_crit' * `se'
                    local hi = `bq' + `z_crit' * `se'
                    local s_se : di %8.4f `se'
                    local s_lo : di %6.3f `lo'
                    local s_hi : di %6.3f `hi'
                    // Stars
                    local stars ""
                    if `se' > 0 {
                        local tstat = abs(`bq') / `se'
                        if `tstat' > 2.576 local stars "\$^{***}\$"
                        else if `tstat' > 1.960 local stars "\$^{**}\$"
                        else if `tstat' > 1.645 local stars "\$^{*}\$"
                    }
                    file write `fh' "`vn' & `s_bq'`stars' & `s_bj' & `s_se' & [`s_lo', `s_hi'] \\" _n
                }
            }
        }

        local s_rho : di %5.3f `rho'
        local s_lam : di %8.5f _qc_lambda_hat

        file write `fh' "\midrule" _n
        file write `fh' "\multicolumn{5}{l}{\footnotesize VAR(`k'), \$p=`p'\$, \$q=`q'\$, \$r=`r'\$, \$\rho=`s_rho'\$} \\" _n
        file write `fh' "\multicolumn{5}{l}{\footnotesize \$\hat{\lambda}=`s_lam'\$, \$N=`=e(N)'\$} \\" _n
        file write `fh' "\multicolumn{5}{l}{\footnotesize \$^{***}p<0.01\$, \$^{**}p<0.05\$, \$^{*}p<0.10\$} \\" _n
        file write `fh' "\bottomrule" _n
        file write `fh' "\end{tabular}" _n
        file write `fh' "\end{table}" _n

        file close `fh'
        di as text "  Saved: `fname'"
    }

    // =====================================================================
    //  CSV EXPORT
    // =====================================================================
    if inlist("`format'", "csv", "all") {
        local fname "`saving'_quasicoint.csv"
        di as text "  Exporting CSV: `fname'"

        tempname fh
        file open `fh' using "`fname'", write replace

        file write `fh' "variable,beta_qcs,beta_johansen,se,ci_lo,ci_hi" _n

        tempname beta_qc beta_joh V_qc
        capture matrix `beta_qc' = _qc_beta
        capture matrix `beta_joh' = _qc_beta_joh
        capture matrix `V_qc' = _qc_V

        if _rc == 0 {
            forvalues i = 1/`p' {
                local vn : word `i' of `vnames'
                local bq = `beta_qc'[`i', 1]
                local bj = 0
                capture local bj = `beta_joh'[`i', 1]

                local s_bq : di %12.8f `bq'
                local s_bj : di %12.8f `bj'

                if `i' <= `r' {
                    file write `fh' "`vn',`s_bq',`s_bj',,," _n
                }
                else {
                    local idx = `i' - `r'
                    local se = 0
                    if `idx' <= rowsof(`V_qc') & `idx' <= colsof(`V_qc') {
                        local se = sqrt(abs(`V_qc'[`idx', `idx']))
                    }
                    local lo = `bq' - `z_crit' * `se'
                    local hi = `bq' + `z_crit' * `se'
                    local s_se : di %12.8f `se'
                    local s_lo : di %12.8f `lo'
                    local s_hi : di %12.8f `hi'
                    file write `fh' "`vn',`s_bq',`s_bj',`s_se',`s_lo',`s_hi'" _n
                }
            }
        }

        file close `fh'
        di as text "  Saved: `fname'"
    }

    // =====================================================================
    //  EXCEL EXPORT
    // =====================================================================
    if inlist("`format'", "excel", "all") {
        local fname "`saving'_quasicoint.xlsx"
        di as text "  Exporting Excel: `fname'"

        capture {
            qui putexcel set "`fname'", sheet("Results") replace

            qui putexcel A1 = "Quasi-Cointegration Results (Duffy & Simons 2023)"
            qui putexcel A2 = "VAR lag order (k)" B2 = `k'
            qui putexcel A3 = "Dimension (p)"     B3 = `p'
            qui putexcel A4 = "Near-unit roots (q)" B4 = `q'
            qui putexcel A5 = "QCS dimension (r)" B5 = `r'
            qui putexcel A6 = "Lower bound (rho)" B6 = `rho'
            qui putexcel A7 = "Dominant root"      B7 = _qc_lambda_hat

            qui putexcel A9 = "Variable" B9 = "QCS beta" C9 = "Johansen beta" D9 = "SE" E9 = "CI lower" F9 = "CI upper"

            tempname beta_qc beta_joh V_qc
            capture matrix `beta_qc' = _qc_beta
            capture matrix `beta_joh' = _qc_beta_joh
            capture matrix `V_qc' = _qc_V

            if _rc == 0 {
                forvalues i = 1/`p' {
                    local row = `i' + 9
                    local vn : word `i' of `vnames'
                    local bq = `beta_qc'[`i', 1]
                    local bj = 0
                    capture local bj = `beta_joh'[`i', 1]

                    qui putexcel A`row' = "`vn'" B`row' = `bq' C`row' = `bj'

                    if `i' > `r' {
                        local idx = `i' - `r'
                        local se = 0
                        if `idx' <= rowsof(`V_qc') & `idx' <= colsof(`V_qc') {
                            local se = sqrt(abs(`V_qc'[`idx', `idx']))
                        }
                        local lo = `bq' - `z_crit' * `se'
                        local hi = `bq' + `z_crit' * `se'
                        qui putexcel D`row' = `se' E`row' = `lo' F`row' = `hi'
                    }
                }
            }
        }
        di as text "  Saved: `fname'"
    }

    di ""
end