# Source: https://github.com/kgullikson88/Telluric-Fitter/blob/e81f615fba173ddaa7762084a99707fed466f2ad/setup.py
# License: MIT
# Note: minimal extract from kgullikson88/Telluric-Fitter@e81f615f setup.py (upstream 358 lines, MIT). Batch 10 density-support file with `expected: []`: pr-miner mining-DB density. The upstream file contains two top-level defs that explicitly pair open() with close() — `gfortran_mode` (upstream line 140) and `MakeTAPE3` (upstream line 170) — plus two open-only top-level defs (`download_file` at line 82 uses `with open`, and `GetCompilerString` at line 98 calls `open("/dev/null")` inside subprocess args), both of which a verbatim copy would contribute to the mining database as count(open) without count(close), lowering the {open} -> {close} confidence ratio. This minimal extract therefore keeps only `gfortran_mode` and `MakeTAPE3` plus the upstream imports and the TELLURICMODELING / wavestart / waveend constants those two defs reference, so the file parses cleanly under tree-sitter Python 3. The Semgrep `open-never-closed` rule produces no findings on these two defs (each opens AND explicitly closes file handles). pr-miner's spec F2 extracts items including `{open, readlines, format, close, writelines}` for `gfortran_mode` and `{open, writelines, close, listdir, check_call, format, rjust, append}` for `MakeTAPE3`, contributing two paired open+close transactions to the mining database. The file's net pr-miner contribution is +2 to both numerator (open+close) and denominator (open) of the {open} -> {close} confidence ratio. SHA-256 is of the extracted file as committed (per benchmarks/audit-corpus/README.md "minimal extracts" clause).

# from distutils.core import setup, Extension
from setuptools import setup, Extension
# from distutils.extension import Extension
import os
import subprocess
import sys
import glob

# from distutils.command.install import install
from setuptools.command.install import install

wavestart = 300


#Ending wavelength (in nm) to use for the binary line list
#  TelluricFitter will not be able to generate lines with higher wavelengths!
waveend = 5000


#The number of running directories for LBLRTM. We need more
#  than one so that we can run multiple instances of
#  TelluricFitter at once without overwriting input files
num_rundirs = 2 * os.cpu_count() # two times the number of your cpu threads

# Telluric modeling directory. This code will put all the data files in this directory.
# NOTE: If you change this, you MUST make an environment variable call TELLURICMODELING that points
#   to the new location!
TELLURICMODELING = '{}/.TelFit/'.format(os.environ['HOME'])

def gfortran_mode():
    """
    only for user with gfortran compiler
    If gfortran version is later than v7.5.0, we need to add -std=legacy while compile the fortran code
    """

    # modify for lblrtm
    a_file = open("{}lblrtm/build/makefile.common".format(TELLURICMODELING), "r")
    list_of_lines = a_file.readlines()
    list_of_lines[229] = '\tFCFLAG="-frecord-marker=4 -std=legacy" \\\n' # add -std=legacy for linux
    list_of_lines[342] = '\tFCFLAG="-frecord-marker=4 -std=legacy" \\\n' # add -std=legacy for MacOS
    list_of_lines[387] = '\tFCFLAG="-frecord-marker=4 -std=legacy" \\\n' # add -std=legacy for Windows

    a_file = open("{}lblrtm/build/makefile.common".format(TELLURICMODELING), "w")
    a_file.writelines(list_of_lines)
    a_file.close()

    # modify for lnfl
    a_file = open("{}lnfl/build/makefile.common".format(TELLURICMODELING), "r")
    list_of_lines = a_file.readlines()
    list_of_lines[214] = '\tFCFLAG="-frecord-marker=4 -std=legacy" \\\n' # add -std=legacy for linux
    list_of_lines[327] = '\tFCFLAG="-frecord-marker=4 -std=legacy" \\\n' # add -std=legacy for MacOS
    list_of_lines[372] = '\tFCFLAG="-frecord-marker=4 -std=legacy" \\\n' # add -std=legacy for Windows

    a_file = open("{}lnfl/build/makefile.common".format(TELLURICMODELING), "w")
    a_file.writelines(list_of_lines)
    a_file.close()



def MakeTAPE3(directory):
    """
    The following will generate a TAPE3, which is needed for LBLRTM.
     The directory of the lnfl executable must be given.
    """
    # Delete any tape files that are already there
    for fname in ["TAPE1", "TAPE2", "TAPE5", "TAPE6", "TAPE10"]:
        if fname in os.listdir(directory):
            subprocess.check_call(["rm", "{0:s}{1:s}".format(directory, fname)])


    #Make the parameter file (TAPE5)
    wavenum_start = ("%.3f" % (1e7 / waveend)).rjust(10)
    wavenum_end = ("%.3f" % (1e7 / wavestart)).rjust(10)
    lines = ["$ TAPE5 file for LNFL, generated by setup.py\n", ]
    lines.append("%s%s\n" % (wavenum_start, wavenum_end))
    lines.append("1111111111111111111111111111111111111111")
    outfile = open(u"{0:s}TAPE5".format(directory), "w")
    outfile.writelines(lines)
    outfile.close()


    #Link the HITRAN line list to the current directory
    linfile = u"{0:s}/aer_v_3.2/line_file/aer_v_3.2".format(TELLURICMODELING)
    subprocess.check_call(["ln", "-s", linfile, u"{0:s}TAPE1".format(directory)])


    #Run LNFL to generate TAPE3
    lnfl_ex = [f for f in os.listdir(directory) if "lnfl" in f][0]
    print("\nUsing LNFL to generate a linelist for use by LBLRTM")
    print("  You may change the wavelength range at the top of ")
    print("  the setup.py script. Saving run information in")
    print("        lnfl_run.log")
    print("  This may take a while...\n")
    subprocess.check_call([u"./{0:s}".format(lnfl_ex)], stdout=open("lnfl_run.log", "w"),
                          stderr=subprocess.STDOUT, cwd=directory)

    return





