#!/usr/bin/python3
"""
L-20 MCS 507 Fri 6 Oct 2023 : web_det.py

The script prepares the input to compute the determinant
of a matrix entered via a web browser.
The determinant is computed with the script compute_det.py.
"""
import cgi

def print_header(title):
    """
    Writes title and header of page.
    """
    print("""Content-type: text/html

    <html>
    <head>
    <title>%s</title>
    </head> 
    <body>""" % title)

def ask_dimension():
    """
    Form to enter the dimension.
    """
    print("""<form method = "post"
                   action = "web_det.py">
    <p>
      Give dimension:
      <input type = "text" name = "dim"
             size = 4 value = 2>
      <input type = "submit">
    </p>
    </form>""")

def ask_matrix(dim):
    """
    Form to enter a dim-by-dim matrix.
    """
    print("""<form method = "post"
                   action = "compute_det.py">""")
    print("""The dimension:
       <input type = "text" name = "dim"
              size = 4 value = %d>""" % dim)
    print("<p>Enter matrix :</p>")
    print("<table>")
    for i in range(0, dim):
        print("<tr>")
        for j in range(0, dim):
            print("""<td><input type = "text"
            name = %d,%d size = 4></td>""" % (i, j))
    print("</table>")
    print("""<input type = "submit">""")
    print("</form>")

def main():
    """
    Web interface to compute a determinant.
    """
    print_header("compute determinant")
    form = cgi.FieldStorage()
    if "dim" not in form:
        ask_dimension()
    else:
        dim = int(form["dim"].value)
        ask_matrix(dim)
    print("</body></html>\n")

main()
