module hermite_nom
    implicit none
    contains
    Recursive function phi(n,y) result(out)
        implicit none 
        integer, parameter :: DP = selected_real_kind(r = 50,p = 14)
        real(kind = DP) :: y
        real(kind = DP),parameter :: PI=4.D0*DATAN(1.D0)
        integer :: n
        complex(kind = DP) :: out

        if(n<0) then 
            out = 1.0_DP
        else if(n ==0) then
            out = PI**(-0.25_DP)*exp(-0.5_DP*y**2)
        else if(n ==1) then
            out = PI**(-0.25_DP)*sqrt(2.0_DP)*y*exp(-0.5_DP*y**2)
        else if(n>=2) then
            out = sqrt(2.0_DP/(n))*y*phi(n-1,y)-sqrt((n-1.0_DP)/n)*phi(n-2,y)
        end if
    end function

    function ddy(y,o,phi_ij,phi_ij01)
        implicit none
        integer, parameter :: DP = selected_real_kind(r = 50,p = 14)
        real(kind = DP) :: y
        integer :: o
        real(kind = DP),parameter :: PI=4.D0*DATAN(1.D0)
        complex(kind = DP) :: ddy, phi_ij,phi_ij01
        if(o ==0) then
            ddy = -y*PI**(-0.25_DP)*exp(-0.5_DP*y**2)
        else if(o ==1) then
            ddy = sqrt(2.0_DP)*PI**(-0.25_DP)*exp(-0.5_DP*y**2)*(1.0_DP-y**2)
        else if(o>=2) then
            ddy = -y*phi_ij + sqrt(2.0_DP*o)*phi_ij01
        end if
    end function

    function dddy(y,o,phi_ij)
        implicit none
        integer, parameter :: DP = selected_real_kind(r = 50,p = 14)
        real(kind = DP) :: y
        integer :: o
        complex(kind = DP) :: dddy,phi_ij
        dddy = (-(2*o+1)+y**2) *phi_ij
    end function
end module
