# Date created: 13/01/2020
# Julia Conversion: Gerry Gralton
# Original author: Katherine Harborne

using ImageFiltering,
        OffsetArrays,
        Statistics

"""
    blur_cube(ifu_cube,
                observe)

Takes an IFU cube generated by `ifu_cube()` and convolves it with a
point spread function kernel as specified by the blur argument.
"""
function blur_cube(ifu_cube::Array{Float64, 3},
                    observe::Observation)

    if (observe.sbin < 25 && (observe.sbin % 2) != 0)
        psf_dim = observe.sbin
    elseif (observe.sbin < 25 && (observe.sbin % 2) == 0)
        psf_dim = observe.sbin-1
    else psf_dim = 25
    end

    if typeof(observe.blur) == Gaussian_blur
        fwhm = observe.blur.scaled_fwhm.scaled_lsf
        kernel = reflect(ProFit.gaussian_cuba(fwhm, psf_dim))
    elseif typeof(observe.blur) == Moffat_blur
        β = observe.blur.β
        α = observe.blur.scaled_α.scaled_lsf
        mag = 1.
        kernel = reflect(ProFit.moffat_cuba(β, α, mag, psf_dim))
    else
        error("Blur type:", typeof(observe.blur), "is not supported.")
    end

    blur_cube = zeros(Float64, (observe.sbin, observe.sbin, observe.vbin))

    for bin in 1:observe.vbin
        blur_cube[:,:,bin] = imfilter(ifu_cube[:,:,bin], kernel)
        blur_cube[:,:,bin] = blur_cube[:,:,bin] .* observe.ap_region #Set all cells outside aperture to zero
    end

    return blur_cube
end
