#0 Required prerequisites
#0.1Importing dependencies
import ctypes as ct
import numpy as np
import shutil
import os

#0.2 Changing working directory
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

#1.0 PAth for results, and formatting to F90 readable:
#1.1 Optional path where results are to be stored (For V2)
fileLocation = r"C:\\"
DLL_Location_64bit = r"C:\\Program Files (x86)\\DNV\\PILSS V2.2-00\\bin\\x64\\PILSS_DLL.dll"
DLL_Location_32bit = r"C:\\Program Files (x86)\\DNV\\PILSS V2.2-00\\bin\\x86\\PILSS_DLL.dll"
caseName =""
def create_fortran_string_buffer(py_string):
    #Constant for maximu m string length.
    MAX_STR_LEN = 4096  
    byte_string = py_string.encode('utf-8')  # Convert Python string to bytes
    if len(byte_string) >= MAX_STR_LEN:
        raise ValueError("String is too long for Fortran buffer")

    padded_string = byte_string.ljust(MAX_STR_LEN, b' ')  # Pad with spaces
    return ct.create_string_buffer(padded_string, MAX_STR_LEN)

#1.2 Required input data (loop in order to be able to minimize the code):
##Specification of input data:
##Cross section
D_hydro = 0.4033 #Hydrodynamic pipe diameter
D = 0.4033 #Outer pipe diameter including any coating layer
w_s = 484.76 #Submerged pipe weight per unit length
w_s_i = 484.76 #Submerged pipe weight per unit length, installation condition
w_s_w = 484.76 #Submerged pipe weight per unit length in waterfilled condition
m = 180.74 #Dry pipe mass per unit length
t_mgrt = 0.0 #Marine growth thickness
k_lay_user = 1.0 #User defined lay factor
EI = 0.0 #Pipe bending stiffness
T0 = 0.0 #Lay tension, horizontal component
alpha_m = 0.0 #Damping coeff for mass-proportional rayleigh damping

##Hydro parameters
rho_w = 1028.0 # water density
U_m = 0.0 #Flow velocity amplitude, used for regular waves
T = 0.0 #Regular wave period
U_c = 0.358 #Steady current velocity perpendicular to pipe
Phi_t = 0.0 #Phase displacement of regular wave
FH_m = 0.0 #Horizontal force amplitude, only if horizontal sine force is appliued
depth = 108.0 #water depth [m]
Tsim = 10800 #Simulation length
WaveVelRef_h = 0.20165 #Reference height for generation of wave-induced particle velocity
Hs = 14.3 #Significant wave height for design sea state
Tp = 15.80 # Peak period for design spectrum
SpectrumPeakedness = 3.30 # Peak-enhancement factor for design spectrum
theta_w = 90.0 # Relative angle between pipe and wave heading
n_spreading = 8.0 # Spectral spreading exponent
r_H = 1.0 # Dummy parameter. Set to: 1.0
r_L = 1.0 # Reduction factor on hydrodynamic lift load
HydroModel = 4 # Force model option: 4 - Database force model, 5 - Horizontal sine force
flowtype = 1 # Not in use. Set to: 1
roughness = 2 # Pipe surface roguhness: 1 - Smooth, 2 - Rough, 3 - Very rough (roughness = 3 only applicable for HydroModel = 4)
GenerateRegularWave = 2 # A regular wave signal should be generated: 1 - True, 2 � False
SmoothWaveVelocity = 2 # Wake velocity should be smoothed prior to differentiation: 1 - True, 2 � False. Default value: 2
WaveOrder = 1 # Wave order option: 1 - Linear, 2 - Second order
SpectrumSpecification = 1 # Applicable Wave spectrum: 1 - JONSWAP
numseeds = 5 # Number of random seastates to be analysed
HydrodynamicDiameter_int = 2 # Option for specifying user defined hydrodynamic diameter: 1 � True, 2 � False
IncludeLiftReduction_int = 2 # Option for including reduction factor on hydrodynamic lift: 1 � True, 2 � False

##Seeds
seedArray_phase = np.require(np.array([81663, 2142, 56225, 24849, 29681]), dtype=np.int32, requirements=['C'])
seedArray_crest = np.require(np.array([36657, 36657, 36657, 36657, 36657]), dtype=np.int32, requirements=['C'])

##Soil variables:
k_soil = 65000.0 # Elastic stiffness of the soil. Recommended value is 65000 N/m/m
mu = 0.6 # Friction coefficient. Specified by user for Coulomb friction. Set to 0.6 for sand and 0.2 for clay
gamma_mark = 10212.0 # Submerged (effective) unit weight of soil
rho_su = 0.0 # Depth gradient of undrained shear strength. Only used for SAFEBUCK and Geotechnical clay models
Nc = 0.0 # Bearing capacity factor for clay. Only used for initial penetration according to the Geotechnical clay model
su_z0 = 0.0 # Undrained shear strength of soil at seabed (z = 0). Only used for SAFEBUCK and Geotechnical clay models
delta_mobilization = 0.0 # Mobilization distance required to reach failure at the relevant penetration depth. Expressed as fraction of the pipe-soil contact width B, which is calculated by the program. Only used for initial penetration calculations according to the SAFEBUCK and Geotechnical clay models
St = 1.0 # Sensitivity (ratio of intact to remoulded shear strength). Only used for SAFEBUCK and Geotechnical clay models when remoulded soil is considered
alpha_soil = 0.02 # Damping coefficient for soil damping in elastic regime (c_soil = alpha_soil * k_soil)
su_sigmav_NC = 0.0 # Ratio of the normally consolidated shear resistance to the consolidation normal stress. Typical range is between 0.25 and 0.5. Only used for Geotechnical clay model
alpha_brk = 0.0 # Pipe-soil adhesion factor. Only used for Geotechnical clay model
gamma_pre = 0.0 # Consolidation preloading effect. Taken as the ratio of preloading (e.g. waterfilled submerged weight) to the submerged weight in the condition considered. Only used for Geotechnical clay model
m_OCR = 0.0 # Exponent accounting for long-term effect of overconsolidation. Only used for Geotechnical clay model
kappa_active = 0.0 # Active earth pressure coefficient. A value of 2 is recommended to account for inclined loading (horizontal + lift). Only used for Geotechnical clay model when suction is included
kappa_passive = 0.0 # Passive earth pressure coefficient. A value of 2 is recommended to account for inclined loading (horizontal + lift). Only used for Geotechnical clay model
su_active = 0.0 # Average undrained shear strength within the active failure zone. Only used for Geotechnical clay model when suction is included
su_passive = 0.0 # Average undrained shear strength within the passive failure zone. Only used for Geotechnical clay model
gamma_total = 0.0 # Total unit soil weight in air. Only used for clay (in Verley and Lund model and after break-out in the other models). Verley and Lund recommend a value of 18000 N/m3 regardless of the value of submerged unit weight.
su = 0.0 # Undrained shear strength of soil. Only used for Verley and Lund clay model
z_ini_user = 0.0 # User defined initial penetration
z_t = 0.0 # Trench depth
theta_t = 0.0 # Trench-wall angle
SoilModel = 2 # Soil model option: 1 - Coulomb friction, 2 - Pipe-sand, 3 - Pipe-clay
CalculatedLayFactor_int = 2 # Option for including a lay factor calculated by PILSS to increase static contact pressure for initial penetration calculation. 1 - True, 2 � False
UserDefinedLayFactor_int = 2 # Option for including a user defined lay factor to increase static contact pressure for initial penetration calculation. 1 � True, 2 � False
InitialPenetrationModel = 1 # Penetration calculation model option for pipe-clay: 1 - Verley and Lund (1995), 2 - SAFEBUCK, 3 - Geotechnical model
remoulded_int =  2 # Option for reducing shear strength due to remoulded soil (used for the combination SoilModel = 3 and InitialPenetrationModel = 2 or 3). 1 - True, 2 � False
suction_int = 2 # Option to account for clay suction: 1 - True, 2 � False
waterFilled_int = 2 # Option to account for weight of water-filled pipe when calculating initial penetration: 1 � True, 2 - False
UserDefinedInitialPenetration_int = 2 # Option to include user defined initial penetration: 1 � True, 2 - False
IncludeTrench_int = 2 # Option to include reduction factors on hydrodynamic loads due to trench. 1 � True, 2 - False

##Time series variables:
t_start = 0.0 # Start time for dynamic analysis. Set to: 0.0
delta_t = 0.01 # Timestep for dynamic analysis. Typical timestep size is 0.001s
delta_t_signal = 0.35 # Timestep for wave-induced particle velocity signal. Recommended value is 0.35 s. Cannot be less than delta t
delta_t_res = 1.0 # Resolution of results vectors used for plots and writing results to file.
delta_t_plot = 1.0 # Resolution of plot vectors


##Dynamic solution variables:
RampUpPeriod = 0.0 # Duration of ramp-up period. Hydrodynamic loads increase linearly from zero to full strength during ramp-up period. Recommended duration is approximately 20% of the storm duration, or 2000 s for a three-hour storm
MaxNrOfIterations = 10 # Maximum number of equilibrium iterations in each timestep
RampUp_int = 2 # Set to 1 if storm ramp up introduces a linear reduction to hydrodynamic loads for the ramp-up period: 1 � True, 2 � False

##Optionals 
printToFile = 3 # 1 - Print all results to .txt file, 2 - Do not print results to file, 3 - Only print ResultsOverview to file
readWaveVelFromFile = 2
generatePlots = False
ExplicitAcceleration = True

#1.3 Specification of version number:
Version_number=1 # 1 - version 1.0, 2 - version 2.2

#1.4 Bitness specification
bitness = 64

#1.4 Specify whether postprocessing in Python is to be performed 
postproc=1 #1 - yes, 2-no

#2.0: Version run scripts
#2.1 PILSS V1 run:
def run_PILSS_interfacev1(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,
                        inSoil_real, inSoil_int, inTime_real, inTime_int,
                        delta_t, delta_t_signal, delta_t_res, delta_t_plot,
                        Tsimulation, numseeds, printToFile, readWaveVelFromFile,
                        generatePlots, ExplicitAcceleration):

    # Loading the .DLL
    if bitness == 64:
        fortlib = ct.CDLL(DLL_Location_64bit)
    else:
        fortlib = ct.CDLL(DLL_Location_32bit)
    # Specify input array properties
    fortlib.PILSSInterface.argtypes = [
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inCross_real
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inHydro_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inHydro_int
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # seedArray_phase
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # seedArray_crests
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inSoil_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inSoil_int
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inTime_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inTime_int
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfTimesteps
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfTimesteps_signal
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfTimesteps_res
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inDyn_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inDyn_int
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # t_vector_U
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # U_t_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # A_t_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # F_H_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # F_L_matrix
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfPlotsteps
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # addedPlotRows
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=0, flags='C_CONTIGUOUS'),  # delta_t_plot
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # stepLength
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # printToFile
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # readWaveVelFromFile
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # generatePlots
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # ExplicitAcceleration
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # dummyBoolean1
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # dummyBoolean2
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # result_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # maxMatrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # minMatrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # maxAbsMatrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # t_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # y_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # z_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # v_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # a_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # Fsoil_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # Fstiff_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # FHrel_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # FLrel_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # yref_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=2, flags='C_CONTIGUOUS'),    # iElPl_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=2, flags='C_CONTIGUOUS')     # outVar_int_matrix
    ]

    # Example of input arrays/values/bools which are passed onto Fortran
    inDyn_real = np.require(np.zeros(numseeds), dtype=np.float64, requirements=['C'])
    inDyn_int = np.require(np.array([10.0, 2.0]), dtype=np.int32, requirements=['C'])

    # Time steps
    NrOfTimesteps = np.require((np.ceil(Tsimulation / delta_t) + 1), dtype=np.int32, requirements=['C'])
    NrOfTimesteps_signal = np.require((np.ceil(Tsimulation / delta_t_signal) + 1), dtype=np.int32, requirements=['C'])
    NrOfTimesteps_res = np.require((np.ceil(Tsimulation / delta_t_res) + 1), dtype=np.int32, requirements=['C'])
    NrOfPlotsteps = np.require((np.ceil(Tsimulation / delta_t_plot) + 1), dtype=np.int32, requirements=['C'])
    t_vector_U = np.require(np.zeros(NrOfTimesteps_signal), dtype=np.float64, requirements=['C'])

    # Results
    U_t_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    A_t_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    F_H_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    F_L_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    result_matrix = np.require(np.zeros((6, 2)), dtype=np.float64, requirements=['C'])
    maxMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])
    minMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])
    maxAbsMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])

    # Plot
    addedPlotRows = 0 if NrOfPlotsteps % 1 == 0 else 1
    if NrOfPlotsteps % 1 == 0:
        addedPlotRows = np.require(0, dtype=np.int32, requirements=['C'])
    else:
        addedPlotRows = np.require(1, dtype=np.int32, requirements=['C'])

    t_matrix_plot = np.require(np.zeros((1, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    y_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    z_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    v_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    a_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    Fsoil_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    Fstiff_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    FHrel_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    FLrel_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    yref_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    iElPl_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps), dtype=np.int32), requirements=['C'])
    outvar_int_matrix = np.require(np.zeros((numseeds, 5), dtype=np.int32), requirements=['C'])
    dummyInteger = np.require(1, dtype=np.int32, requirements=['C'])
    dummyBoolean = np.require(False, dtype=bool, requirements=['C'])
    dummyBoolean2 = np.require(True, dtype=bool, requirements=['C'])
    legacyApi = False

    # Call the Fortran function
    res = fortlib.PILSSInterface(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,
                                  inSoil_real, inSoil_int, inTime_real, inTime_int,
                                  NrOfTimesteps, NrOfTimesteps_signal, NrOfTimesteps_res,
                                  inDyn_real, inDyn_int, t_vector_U,
                                  U_t_matrix, A_t_matrix, F_H_matrix, F_L_matrix,
                                  NrOfPlotsteps, addedPlotRows, delta_t_plot,
                                  dummyInteger, printToFile, readWaveVelFromFile,
                                  generatePlots, ExplicitAcceleration, dummyBoolean,
                                  dummyBoolean2, result_matrix, maxMatrix, minMatrix,
                                  maxAbsMatrix, t_matrix_plot, y_matrix_plot,
                                  z_matrix_plot, v_matrix_plot, a_matrix_plot,
                                  Fsoil_matrix_plot, Fstiff_matrix_plot,
                                  FHrel_matrix_plot, FLrel_matrix_plot,
                                  yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix)
    if postproc == 1:
        return result_matrix, maxMatrix, minMatrix,maxAbsMatrix, t_matrix_plot, y_matrix_plot,z_matrix_plot, v_matrix_plot, a_matrix_plot,Fsoil_matrix_plot, Fstiff_matrix_plot,FHrel_matrix_plot, FLrel_matrix_plot,yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix
    else:
        ll =0

#2.2 PILSS V2 run:
def run_PILSS_interfacev2(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,
                        inSoil_real, inSoil_int, inTime_real, inTime_int,
                        delta_t, delta_t_signal, delta_t_res, delta_t_plot,
                        Tsimulation, numseeds, printToFile, readWaveVelFromFile,
                        generatePlots, ExplicitAcceleration, fileLocation,caseName1,inDyn_real,inDyn_int):

    # Loading the .DLL
    if bitness == 64:
        fortlib = ct.CDLL(DLL_Location_64bit)
    else:
        fortlib = ct.CDLL(DLL_Location_32bit)

    # Specify input array properties
    fortlib.PILSSInterface_v2.argtypes = [
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inCross_real
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inHydro_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inHydro_int
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # seedArray_phase
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # seedArray_crests
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inSoil_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inSoil_int
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inTime_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inTime_int
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfTimesteps
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfTimesteps_signal
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfTimesteps_res
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # inDyn_real
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=1, flags='C_CONTIGUOUS'),     # inDyn_int
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),  # t_vector_U
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # U_t_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # A_t_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # F_H_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # F_L_matrix
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # NrOfPlotsteps
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # addedPlotRows
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=0, flags='C_CONTIGUOUS'),  # delta_t_plot
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # stepLength
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # printToFile
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=0, flags='C_CONTIGUOUS'),  # readWaveVelFromFile
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # generatePlots
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # ExplicitAcceleration
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # dummyBoolean1
        np.ctypeslib.ndpointer(dtype=bool, ndim=0, flags='C_CONTIGUOUS'),  # dummyBoolean2
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # result_matrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # maxMatrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # minMatrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # maxAbsMatrix
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # t_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # y_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # z_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # v_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # a_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # Fsoil_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # Fstiff_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # FHrel_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # FLrel_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),  # yref_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=2, flags='C_CONTIGUOUS'),    # iElPl_matrix_plot
        np.ctypeslib.ndpointer(dtype=np.int32, ndim=2, flags='C_CONTIGUOUS'),     # outVar_int_matrix
        ct.c_char_p,  # resultsPath
        ct.c_char_p   # caseName
        ]

    # Example of input arrays/values/bools which are passed onto Fortran
    resultsPath = create_fortran_string_buffer(fileLocation)
    caseName = create_fortran_string_buffer(caseName1)
    # Time steps
    NrOfTimesteps = np.require((np.ceil(Tsimulation / delta_t) + 1), dtype=np.int32, requirements=['C'])
    NrOfTimesteps_signal = np.require((np.ceil(Tsimulation / delta_t_signal) + 1), dtype=np.int32, requirements=['C'])
    NrOfTimesteps_res = np.require((np.ceil(Tsimulation / delta_t_res) + 1), dtype=np.int32, requirements=['C'])
    NrOfPlotsteps = np.require((np.ceil(Tsimulation / delta_t_plot) + 1), dtype=np.int32, requirements=['C'])
    t_vector_U = np.require(np.zeros(NrOfTimesteps_signal), dtype=np.float64, requirements=['C'])

    # Results
    U_t_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    A_t_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    F_H_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    F_L_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
    result_matrix = np.require(np.zeros((6, 2)), dtype=np.float64, requirements=['C'])
    maxMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])
    minMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])
    maxAbsMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])

    # Plot
    addedPlotRows = 0 if NrOfPlotsteps % 1 == 0 else 1
    if NrOfPlotsteps % 1 == 0:
        addedPlotRows = np.require(0, dtype=np.int32, requirements=['C'])
    else:
        addedPlotRows = np.require(1, dtype=np.int32, requirements=['C'])

    t_matrix_plot = np.require(np.zeros((1, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    y_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    z_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    v_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    a_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    Fsoil_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    Fstiff_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    FHrel_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    FLrel_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    yref_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
    iElPl_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps), dtype=np.int32), requirements=['C'])
    outvar_int_matrix = np.require(np.zeros((numseeds, 5), dtype=np.int32), requirements=['C'])
    dummyInteger = np.require(1, dtype=np.int32, requirements=['C'])
    dummyBoolean = np.require(False, dtype=bool, requirements=['C'])
    dummyBoolean2 = np.require(True, dtype=bool, requirements=['C'])
    legacyApi = False

    ## Call the Fortran function
    fortlib.PILSSInterface_v2(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,
                                  inSoil_real, inSoil_int, inTime_real, inTime_int,
                                  NrOfTimesteps, NrOfTimesteps_signal, NrOfTimesteps_res,
                                  inDyn_real, inDyn_int, t_vector_U,
                                  U_t_matrix, A_t_matrix, F_H_matrix, F_L_matrix,
                                  NrOfPlotsteps, addedPlotRows, delta_t_plot,
                                  dummyInteger, printToFile, readWaveVelFromFile,
                                  generatePlots, ExplicitAcceleration, dummyBoolean,
                                  dummyBoolean2, result_matrix, maxMatrix, minMatrix,
                                  maxAbsMatrix, t_matrix_plot, y_matrix_plot,
                                  z_matrix_plot, v_matrix_plot, a_matrix_plot,
                                  Fsoil_matrix_plot, Fstiff_matrix_plot,
                                  FHrel_matrix_plot, FLrel_matrix_plot,
                                  yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix, resultsPath,caseName)
    if postproc == 1:
        return result_matrix, maxMatrix, minMatrix,maxAbsMatrix, t_matrix_plot, y_matrix_plot,z_matrix_plot, v_matrix_plot, a_matrix_plot,Fsoil_matrix_plot, Fstiff_matrix_plot,FHrel_matrix_plot, FLrel_matrix_plot,yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix
    else:
        ll =0
#3.0 Automatic processes (Don't change)
#3.1 Formatting input data for PILSS interface (don't change):
##Formatting input data for PILSS interface (don't change):
inCross_real = np.require(np.array([D_hydro,D, w_s,w_s_i,w_s_w,m,0.0,t_mgrt,k_lay_user,EI,T0,alpha_m]), dtype=np.float64, requirements=['C'])
inHydro_real = np.require(np.array([rho_w, U_m, T, U_c, Phi_t, FH_m,0, depth, Tsim, WaveVelRef_h, Hs, Tp, SpectrumPeakedness, theta_w, n_spreading, r_H, r_L]), dtype=np.float64, requirements=['C'])
inHydro_int = np.require(np.array([HydroModel, flowtype, roughness, GenerateRegularWave, SmoothWaveVelocity, WaveOrder,SpectrumSpecification, numseeds, HydrodynamicDiameter_int, IncludeLiftReduction_int]), dtype=np.int32, requirements=['C'])
seedArray_phase = np.require(seedArray_phase, dtype=np.int32, requirements=['C'])
seedArray_crest = np.require(seedArray_crest, dtype=np.int32, requirements=['C'])
inSoil_real = np.require(np.array([k_soil, mu, gamma_mark, rho_su, Nc, su_z0, delta_mobilization, St, alpha_soil, su_sigmav_NC, alpha_brk,gamma_pre, m_OCR, kappa_active, kappa_passive, su_active, su_passive, gamma_total, su, z_ini_user, z_t,theta_t]), dtype=np.float64, requirements=['C'])
inSoil_int = np.require(np.array([SoilModel, CalculatedLayFactor_int, UserDefinedLayFactor_int, InitialPenetrationModel, remoulded_int,suction_int, waterFilled_int, UserDefinedInitialPenetration_int, IncludeTrench_int]), dtype=np.int32, requirements=['C'])
inTime_real = np.require(np.array([t_start, delta_t, delta_t_signal, delta_t_res]), dtype=np.float64, requirements=['C'])
inTime_int = np.require(np.array([1]), dtype=np.int32, requirements=['C'])
inDyn_real = np.require(np.array([RampUpPeriod]), dtype=np.float64, requirements=['C'])
inDyn_int = np.require(np.array([MaxNrOfIterations, RampUp_int]), dtype=np.int32, requirements=['C'])
delta_t_plot = np.require(delta_t_plot, dtype=np.float64, requirements=['C'])
printToFile = np.require(printToFile, dtype=np.int32, requirements=['C'])  # 1 - Print all results to .txt file, 2 - Do not print results to file, 3 - Only print ResultsOverview to file
generatePlots = np.require(generatePlots, dtype=bool, requirements=['C'])
readWaveVelFromFile = np.require(readWaveVelFromFile, dtype=np.int32, requirements=['C'])
ExplicitAcceleration = np.require(ExplicitAcceleration, dtype=bool, requirements=['C'])

# Results
NrOfTimesteps_signal = np.require((np.ceil(Tsim / delta_t_signal) + 1), dtype=np.int32, requirements=['C'])
U_t_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
A_t_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
F_H_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
F_L_matrix = np.require(np.zeros((numseeds, NrOfTimesteps_signal)), dtype=np.float64, requirements=['C'])
result_matrix = np.require(np.zeros((6, 2)), dtype=np.float64, requirements=['C'])
maxMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])
minMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])
maxAbsMatrix = np.require(np.zeros((numseeds, 10)), dtype=np.float64, requirements=['C'])
NrOfPlotsteps = np.require((np.ceil(Tsim / delta_t_plot) + 1), dtype=np.int32, requirements=['C'])

# Plot
addedPlotRows = 0 if NrOfPlotsteps % 1 == 0 else 1
if NrOfPlotsteps % 1 == 0:
    addedPlotRows = np.require(0, dtype=np.int32, requirements=['C'])
else:
    addedPlotRows = np.require(1, dtype=np.int32, requirements=['C'])

t_matrix_plot = np.require(np.zeros((1, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
y_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
z_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
v_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
a_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
Fsoil_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
Fstiff_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
FHrel_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
FLrel_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
yref_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps)), dtype=np.float64, requirements=['C'])
iElPl_matrix_plot = np.require(np.zeros((numseeds, NrOfPlotsteps), dtype=np.int32), requirements=['C'])
outvar_int_matrix = np.require(np.zeros((numseeds, 5), dtype=np.int32), requirements=['C'])
dummyInteger = np.require(1, dtype=np.int32, requirements=['C'])
dummyBoolean = np.require(False, dtype=bool, requirements=['C'])
dummyBoolean2 = np.require(True, dtype=bool, requirements=['C'])

#3.2 Running the functions depending on version number:
if Version_number==1:
    if postproc ==1:
        result_matrix, maxMatrix, minMatrix,maxAbsMatrix, t_matrix_plot, y_matrix_plot,z_matrix_plot, v_matrix_plot, a_matrix_plot,Fsoil_matrix_plot, Fstiff_matrix_plot,FHrel_matrix_plot, FLrel_matrix_plot,yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix = run_PILSS_interfacev1(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,inSoil_real, inSoil_int, inTime_real, inTime_int, delta_t, delta_t_signal, delta_t_res, delta_t_plot, Tsim, numseeds, printToFile, readWaveVelFromFile, generatePlots, ExplicitAcceleration)
    else:
        run_PILSS_interfacev1(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,inSoil_real, inSoil_int, inTime_real, inTime_int, delta_t, delta_t_signal, delta_t_res, delta_t_plot, Tsim, numseeds, printToFile, readWaveVelFromFile, generatePlots, ExplicitAcceleration)
elif Version_number==2:
    if postproc==1:
        result_matrix, maxMatrix, minMatrix,maxAbsMatrix, t_matrix_plot, y_matrix_plot,z_matrix_plot, v_matrix_plot, a_matrix_plot,Fsoil_matrix_plot, Fstiff_matrix_plot,FHrel_matrix_plot, FLrel_matrix_plot,yref_matrix_plot, iElPl_matrix_plot, outvar_int_matrix = run_PILSS_interfacev2(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,inSoil_real, inSoil_int, inTime_real, inTime_int, delta_t, delta_t_signal, delta_t_res, delta_t_plot, Tsim, numseeds, printToFile, readWaveVelFromFile, generatePlots, ExplicitAcceleration, fileLocation, caseName,inDyn_real,inDyn_int)
    else:
        run_PILSS_interfacev2(inCross_real, inHydro_real, inHydro_int, seedArray_phase, seedArray_crest,inSoil_real, inSoil_int, inTime_real, inTime_int, delta_t, delta_t_signal, delta_t_res, delta_t_plot, Tsim, numseeds, printToFile, readWaveVelFromFile, generatePlots, ExplicitAcceleration, fileLocation, caseName,inDyn_real,inDyn_int)
else:
    print("Please specify version number")

#4.0 Optional postprocessing of the Results data:
