
#
# SPECTRA package
# Tools for Fast fourier transforms
#

proc gui_fft {infile}  { 
    global viz vp wp_infile fft

    catch {destroy .fft}
    toplevel .fft -relief raised -bd 2

    label .fft.title -text "Fourier Transform"
    scan [get_dims $infile] %d d1
    set res [expr {($d1 < 2000) ? $d1 : 2000}]
    scalentry .fft.res  -variable fft(res) -label "Resolution" -from 0 -to $res -length 250
    scalentry .fft.wsize -variable fft(wsize) -label "Window Size" -from 1 -to [expr $res/4] -length 250

    label .fft.t -height 1 -width 32

    pack append .fft .fft.title {top pady 15} .fft.res top .fft.wsize top .fft.t fill 

    pack append .fft [frame .fft.bot] {pady 10 frame e padx 10 fill}
    mkOkSave .fft.bot.r fft {do_fft $datadir/$infile $fft(wp) $fft(res) $fft(wsize) $fft(window_type)} {Save FFT spectrum as ...}
    pack append .fft.bot .fft.bot.r {right expand}
    button .fft.bot.r.h -text Help  -command {InfoBox {This tool computes the Fourier transform of the input signal.  You can apply a window function to your data to minimize spectral leakage.  You can also convolve signals and perform filtering in the frequency domain.  You can save the finished spectrum in a file. }}
    pack append .fft.bot.r  .fft.bot.r.h fill

    pack append .fft.bot \
        [mkRadioPanel .fft.bot.dwt "Window type" \
            {Bartlett fft(window_type) bartlett} \
            {Hamming fft(window_type) hamming} \
            {Hanning fft(window_type) hanning} \
            {None fft(window_type) { } } ] \
            {left expand fill}

# Display the Fourier Spectrum
    set fft(res) 256
    set fft(wsize) 10
    set fft(window_type) { }
# This updates the fft control panel display before the fft finishes.
    update idletasks
    set fft(wp) [window_$viz "Fast Fourier Transform"]
    if ($fft(launch)) {.fft.bot.r.ok invoke}
    bind .fft <Destroy> {exec rm -f fft.out fft.tmp}
}



proc do_fft { infile window nfreq window_size wflag } {
    global viz fft
    
    .fft.t configure -text "Working..."  ;  Reverse .fft.t  ;  update
    scan [get_dims $infile] %d d1
    set wflag [expr {($fft(window_type) == { }) ? "" : "-w $window_size $fft(window_type)"}]
    catch {eval exec spectrum $infile -fft -fn [last2 $nfreq] $wflag} msg
    exec echo $msg >> spectra.log
    exec awk {{print $1, $2}} fft.out > fft.tmp
    .fft.t configure -text Done  ;  Reverse .fft.t
    plot_$viz $window linear-log {fft.tmp xy curve}
}


