# -*- coding: iso-8859-1 -*-

from numpy import *

def result():
        
    # loop over the incoming results: 
    for timesignal in results:
        if not isinstance(timesignal,ADC_Result): 
            continue   

        # get list of parameters:
        pars = timesignal.get_description_dictionary()

        # make a copy of timesignal:
        fid = timesignal + 0

        # correct for the baseline offset:
        fid.baseline()
        
        # compute the initial phase:
        phi0 = arctan2(fid.y[1][0], fid.y[0][0]) * 180 / pi

        # do FFT: 
        fid.exp_window(line_broadening=10)
        spectrum = fid.fft(samples=2*pars['SI'])
        spectrum.baseline()
        spectrum.phase(-phi0)

        # provide timesignal and spectrum to the display tab:
        data['Timesignal'] = timesignal
        data["Spectrum"] = spectrum

        # ------------- optional measurements: --------------

        # measure signal intensity:
        signal = (timesignal +0).phase(-phi0)
        signal_intensity = sum(signal.y[0:10])      

        # measure spectrum integral:
        #spectrum_integral = cumsum(spectrum.y[0])
        spectrum_magnitude = (spectrum+0).magnitude()
        spectrum_integral =  cumsum(spectrum_magnitude.y[0]) 

        # find the centre of gravity of the spectrum:        
        cg = argwhere(spectrum_integral > 0.5*spectrum_integral[-1])[0] 

        print ''
        print '%s%.3e'%('FID intensity = ', signal_intensity)
        print '%s%.3e'%('Spectrum integral = ', spectrum_integral[-1])
        print '%s%g%s'%("Spectrum middle frequency = ", spectrum.x[cg], ' Hz')
        print ''

pass