;
; PROGRAM FOURIER.PRO,        SAMBA analysis codes
;                             Department of Atmospheric Sciences, UCLA
;
; This program performs Fourier transforms on the SAMBA magnetometer data
; for a specific day in the specified UT range, from 1 minute to 24 hours.
; Based on the transform.pro.
;
; First created 01/09/03        by Athanasios Boudouridis
;
; Latest modification 01/16/03 - limited the plot to the specified frequencies
; Latest modification 02/04/03 - accounted for missing points by interpolation
; Latest modification 06/06/03 - added despiking of the data
; Latest modification 06/10/03 - corrected the missing-points routine
; Latest modification 11/13/03 - modified to read data from the database
; Latest modification 11/13/03 - modified to process multiple days
; Latest modification 09/24/04 - adapted for Fourier transforms
; Latest modification 09/27/04 - used Hanning window to avoid edge effects
; Latest modification 11/19/04 - added digital filtering before transforms
; Latest modification 07/31/05 - applied transform every requested bin
;				 instead of every second and then rebinning
;
;----------------------------------------------------------------------------
; Function for rounding a number to a certain decimal point
;
  FUNCTION rnd,x,d

	d=d*1.
	nx=round(10^d*x)/10^d

	return, nx
	end

;----------------------------------------------------------------------------
; Reads the ASCII data format

  pro read_asc,afile,adata

	adata=lonarr(5,86400)
	wformat='(i6,3i12,i4)'

	openr,1,afile
	while not eof(1) do begin
	readf,1,format=wformat,adata
	endwhile
	close,1

	return
	end

;----------------------------------------------------------------------------
; Reads the CDF data format

  pro read_cdf,cdffile,magdata

	fid=cdf_open(cdffile)
	inq=cdf_inquire(fid)
	natt=inq.natts

	for i=0,natt-1 do begin
	  cdf_attinq,fid,i,attname,attscope,attmax
	  cdf_attget,fid,attname,i,attval,cdf_type=cdf_char
	  print,attname+': '+attval
	endfor
	print

	varid=cdf_varnum(fid,'Magdata')
	cdf_varget,fid,varid,magdata
	cdf_close,fid

	return
	end

;----------------------------------------------------------------------------
; Reads the BINARY data format

  pro read_bin,bfile,bdata

	openr,2,bfile
	a=assoc(2,lonarr(5,86400))
	bdata=a(0)
	close,2

	return
	end

;----------------------------------------------------------------------------
; Finds the appropriate number of tickmarks for the time (x) axis
; and returns the correct ticknames and tick positions

  pro timeticks,utsh,utsm,uteh,utem,ftkint,ntk,tkint,tkvalues,tknames,nmn

; utsh       Start hour
; utsm       Start minute
; uteh       End hour
; utem       End minute
; ftkint     Forced major tick interval (no action if 0)
; ntk        Number of major tick intervals (number of major tickmarks - 1)
; tkint      Major tick interval
; tkvalues   Major tickmark values
; tknames    Major tickmark names
; nmn        Number of minor tickmarks in each major tick interval

;	print
;	print,format='(2i3,4x,2i3)',utsh,utsm,uteh,utem

	tkintv=[1,2,5,10,15,20,30,60,120] ; available major tick
					  ; intervals (min)
	mntkv=[12,8,5,10,15,4,6,12,12]  ; number of minor ticks in each above
					; major tick interval
	dtkiv=n_elements(tkintv)

	hran=uteh-utsh                  ; integer hour range
	cmin=utem+hran*60-utsm+1        ; minute count in the given time range
	mintk=utsm+indgen(cmin)         ; available minute vector

	minatk=5                        ; desired major tickmark number range
	maxatk=10                       ; (minatk < major tickmark # < maxatk)

; begin the tick interval loop to find the tick interval with the appropriate
; number of major ticks

	nmtk=intarr(dtkiv)

	for i=0,dtkiv-1 do begin
	  majint=tkintv(i)
	  mtki=where(mintk mod majint eq 0,mtkc)
	  nmtk(i)=mtkc
	endfor

; select the interval with the maximum number of major tickmarks in the
; desired number range (minatk to maxatk)

	atki=where(nmtk ge minatk and nmtk le maxatk,atkc)
	if (atkc ne 0) then begin
	  antk=max(nmtk(atki),mpos)
	  tkint=tkintv(atki(mpos))
	  nmn=mntkv(atki(mpos))
	endif else begin
	  if (min(nmtk) gt maxatk) then begin    ; choose the maximum interval
	    antk=nmtk(dtkiv-1)                   ; when # of ticks > maxatk
	    tkint=tkintv(dtkiv-1)
	    nmn=mntkv(dtkiv-1)
	  endif
	  if (max(nmtk) lt minatk) then begin    ; choose the minimum interval
	    antk=nmtk(0)                         ; when # of ticks < minatk
	    tkint=tkintv(0)
	    nmn=mntkv(0)
	  endif
	endelse

; recalculate the tickmarks for this tick interval and produce the tick values
; and tick names

	if (ftkint ne 0) then begin  ; enforce the ftkint if non-zero
	  tkint=ftkint
	  nmn=ftkint
	endif
	xtki=where(mintk mod tkint eq 0,xtkc)
	ntk=xtkc-1                            ; # of tick intervals
	mtkv=mintk(xtki)
	tkvalues=mtkv/60.+utsh                ; major tickmark values
	mtkn=strarr(xtkc)
	htkn=strarr(xtkc)
	for i=0,hran do begin
	  hi=where(mtkv ge 60*i and mtkv lt 60*(i+1),hc)
	  if (hc ne 0) then begin
	    mtkn(hi)=strtrim(string(mtkv(hi)-60*i),1)
	    htkn(hi)=strtrim(string(utsh+i),1)
	  endif
	endfor
	lt10mi=where(fix(mtkn) lt 10,lt10mc)
	if (lt10mc ne 0 ) then mtkn(lt10mi)='0'+mtkn(lt10mi)
	lt10hi=where(fix(htkn) lt 10,lt10hc)
	if (lt10hc ne 0 ) then htkn(lt10hi)='0'+htkn(lt10hi)
	if (hran le 12) then tknames=htkn+mtkn else tknames=htkn  ; tick names
	if (hran gt 12) then nmn=6

;	print
;	print,format='('+strtrim(string(dtkiv),1)+'i5)',tkintv
;	print,format='('+strtrim(string(dtkiv),1)+'i5)',nmtk
;	print,format='(3i5)',tkint,antk,nmn
;	print
;;	print,format='('+strtrim(string(cmin),1)+'i4)',mintk
;	print,format='('+strtrim(string(xtkc),1)+'i4)',mtkv
;	print,format='('+strtrim(string(xtkc),1)+'f7.3)',tkvalues
;	print
;	print,htkn
;	print,mtkn
;	print,tknames

	return
	end

;----------------------------------------------------------------------------
; Draws a box around the image position

  pro tvbox,x0,y0,nx,ny,thk,xyr

; x0,y0	Position of bottom left interior corner of the box in normalized
;       coordinates
; nx	Interior width of box in normalized coordinates
; ny	Interior height of box in normalized coordinates
; thk	Thickness of box lines in normalized coordinates
; xyr   Plot area x to y dimension ratio

	ythk=thk
	xthk=ythk/xyr

	box=REPLICATE(0B,2,2)

	x0_box=x0-xthk
	y0_box=y0-ythk
        tv,box,x0_box,y0_box,/normal,xsize=nx+2*xthk,ysize=ythk  ;bottom line

	y0_box=y0+ny      
	tv,box,x0_box,y0_box,/normal,xsize=nx+2*xthk,ysize=ythk  ;top line

	x0_box=x0-xthk
	y0_box=y0-ythk
	tv,box,x0_box,y0_box,/normal,xsize=xthk,ysize=ny+2*ythk  ;left line

	x0_box=x0+nx   
	tv,box,x0_box,y0_box,/normal,xsize=xthk,ysize=ny+2*ythk  ;right line

	return
	end

;----------------------------------------------------------------------------
; Calculates the linear tick positions of a vector (which should be in
; ascending order)

  pro lintick,ovector,mtst,rmtst,mtp,stp

; ovector The original input vector in ascending order
; mtst    Major tick step
; rmtst   Ratio of major to secondary tick step
; mtp     Major linear tick positions
; stp     Secondary linear tick positions

	nstp=n_elements(stp)
	if (nstp ne 0) then nstp=0

	odv=n_elements(ovector)
	dvec=ovector(1)-ovector(0)

       if (ovector(0) eq 0.) then sfve=1. else sfve=ovector(0)/abs(ovector(0))
	if (ovector(odv-1) eq 0.) then slve=1. else $
				slve=ovector(odv-1)/abs(ovector(odv-1))
	ex=0.001
	lve=ovector(0)*(1.d0-ex*sfve)
	rve=ovector(odv-1)*(1.d0+ex*slve)
	vector=[lve,ovector,rve]
	dv=n_elements(vector)

	fmt=ceil(vector(0)/mtst)*mtst
	lmt=floor(vector(dv-1)/mtst)*mtst
	stul=vector(dv-1)+dvec
	if (stul eq lmt+mtst) then lmt=lmt+mtst
;	print,lmt,vector(dv-1),stul
	nmt=round(abs(lmt-fmt)/mtst)+1
	mtp=dblarr(nmt)

	stst=mtst/rmtst

	for i=0,nmt-1 do begin

	   mtp(i)=fmt+i*mtst

	   for j=0,rmtst-2 do begin

	      if (i eq 0) then begin
		 tst=(fmt-mtst)+(j+1)*stst
	         if (tst ge vector(0)) and (tst le vector(dv-1)) then begin
		   if (nstp eq 0) then stp=[tst] else stp=[temporary(stp),tst]
		   nstp=n_elements(stp)
		 endif
	      endif

	      tst=mtp(i)+(j+1)*stst
	      if (tst ge vector(0)) and (tst le stul) then begin
;	      if (tst ge vector(0)) and (tst le vector(dv-1)) then begin
		 if (nstp eq 0) then stp=[tst] else stp=[temporary(stp),tst]
		 nstp=n_elements(stp)
	      endif

	   endfor

	endfor

	return
	end

;----------------------------------------------------------------------------
; Produces the color scale for the images

  pro color_scale,x0,y0,xs,ys,bth,title,labels,labelp,orien,xyr

; x0,y0	Pixel position of bottom left corner of color table
; xs	Width of color table in normalized coordinates
; ys	Height of color table in normalized coordinates
; bth	Thickness of box lines in normalized coordinates
; title Title of the color scale
; labels Label array of the labels for the color table
; labelp Label positions along the color table in normalized coordinates
; orien Orientation index of the color table (0-horizontal, 1-vertical)
; xyr   Plot area x to y dimension ratio

	nlb=n_elements(labels)

	ct=bindgen(256)

	if (orien eq 0) then begin

	   ycsl=replicate(y0-5*bth,nlb)
	   xcsl=x0+labelp
	   xtle=x0+xs/2
	   ytle=y0+ys+3*bth

	endif else begin

	   ct=reverse(rotate(temporary(ct),4))

	   mlen=max(strlen(labels))
	   xcsl=replicate(x0+xs+(8+mlen*7)*bth,nlb)
	   ycsl=y0+labelp-2*bth
	   xtle=x0-8*bth
	   ytle=y0+ys/2.

	endelse

	xyouts,xtle,ytle,title,/normal,alignment=0.5,font=0,charsize=1.4, $
							orientation=90*orien

	tv,ct,x0,y0,/normal,xsize=xs,ysize=ys         ; draw color scale

	tvbox,x0,y0,xs,ys,bth,xyr                     ; draw box around it

	xyouts,xcsl,ycsl,labels,/normal,font=0,alignment=1-(1-orien)*0.5, $
								charsize=1.3

	return
	end

;----------------------------------------------------------------------------
; Transforms the tick positions for each image in normalized(device)
; coordinates

  pro devticks,ivec,dsz,mtp,stp,logi,dmtp,dstp

; ivec    The input vector in ascending order
; dsz     The vector size in normalized(device) coordinates
; mtp     Major tick positions
; stp     Secondary tick positions
; logi    Logarithm index (1-logarithmic ticks, 0-linear ticks)
; dmtp    Normalized(device) major tick positions
; dstp    Normalized(device) secondary tick positions

	dv=n_elements(ivec)

	if (logi eq 1) then begin
	   ivec=alog10(temporary(ivec))
	   mtp=alog10(temporary(mtp))
	   stp=alog10(temporary(stp))
	   extsh=dsz/(2.*dv)
	endif else extsh=0.

	len=ivec(dv-1)-ivec(0)
	dmtp=dsz*(1-1./dv)*(mtp-ivec(0))/len+extsh
	dstp=dsz*(1-1./dv)*(stp-ivec(0))/len+extsh

;	dmtp=dsz*(1-1./dv)*(mtp-ivec(0))/len+dsz/(2.*dv)
;	dstp=dsz*(1-1./dv)*(stp-ivec(0))/len+dsz/(2.*dv)

;	if (logi eq 1) then ivec=10.d0^temporary(ivec)

	return
	end

;----------------------------------------------------------------------------
; Selects an orderly number of elements from a vector

  pro select_elem,elv,dne,nelv

; elv	Element vector
; dne	Desired number of elements to be selected
; nelv	New element vector

	delv=n_elements(elv)
	mln=1000             ; maximum loop number (dne*(mln+1)=maximum delv)
	for i=0,mln do begin
	  if ((delv gt i*dne) and (delv le (i+1)*dne)) then begin
	    melv=indgen(delv) mod (i+1)
;	    melv=fix(elv) mod (i+1)
	    dei=where(melv eq 0)
	    nelv=elv(dei)
	  endif
	endfor

	return
	end

;----------------------------------------------------------------------------
; Converts second of the day to UT string 'HHMMSS'

  pro sec2ut,sec,sut

	sec=long(sec)
	uth=sec/3600
	utm=(sec mod 3600)/60
	uts=(sec mod 3600) mod 60

	suth=strtrim(string(uth),1)
	if (uth lt 10) then suth='0'+suth
	sutm=strtrim(string(utm),1)
	if (utm lt 10) then sutm='0'+sutm
	suts=strtrim(string(uts),1)
	if (uts lt 10) then suts='0'+suts
	sut=suth+sutm+suts

	return
	end

;----------------------------------------------------------------------------
; Finds the spiky data in a vector magnetic component

  pro find_spikes,icomp,yvec,maxdevf,samlen,spi

; icomp   Magnetic component index (0-Bx,1-By,2-Bz)
; yvec    Magnetic component vector
; maxdevf Maximum allowed deviation factor
; samlen  Sample length around a point for the standard deviation calculation
; spi     Spike locations

	nd=n_elements(yvec)
	spv=intarr(nd)
	for i=0L,nd-1 do begin

	  if (yvec(i) eq 99999.) then continue

	  minind=max([0,i-samlen/2])
	  maxind=min([nd-1,i+samlen/2])

	  samvec=yvec(minind:maxind)
	  vsveci=where(samvec ne 99999.,vsvecc)

	  if (vsvecc lt 10) then continue
	  vsvec=samvec(vsveci)

	  avsam=total(vsvec)/vsvecc
	  dev=abs(yvec(i)-avsam)
	  if (dev gt 1.) then begin
	    sdevsam=stddev(vsvec)
	    maxdev=maxdevf*sdevsam
	    if (dev gt maxdev and i ne 0 and i ne nd-1) then spv(i)=1
	  endif

	  tpsec=long(0.2*nd)
	  if ((i+1) mod tpsec eq 0) then begin
	    percent_done=round((float(i)/nd/3.+icomp/3.)*100.)
	    print,format='(i4,$)',percent_done
	  endif

	endfor
	spi=where(spv eq 1)

	return
	end

;----------------------------------------------------------------------------
; Interpolates the spiky data in a vector magnetic component (calculates
; interpolated values but does not replace the original data yet)

  pro remove_spikes,magcomp,obeg,spikee,spxlen,intlen,sspp,xsspp,ssint

; magcomp  Magnetic component (Bx, By, or Bz)
; obeg     Spike beginning point
; spikee   Spike ending point
; spxlen   Extra interpolation points around the spike (equal to spike length)
; intlen   Length of points used for interpolation around the extended spike
; sspp     Spike points (including the extra interpolation points)
; xsspp    Extended spike points (including an extra point before and after)
; ssint    Interpolated magnetic component

	mdim=n_elements(magcomp)

	sbegi=max([obeg-spxlen,0])
	sendi=min([spikee+spxlen,mdim-1])
	sspp=sbegi+indgen(sendi-sbegi+1)
	dsspp=n_elements(sspp)

	ibegi=max([sbegi-intlen,0])
	iendi=min([sendi+intlen,mdim-1])
	intp=[ibegi+indgen(intlen),sendi+1+indgen(intlen)]
	dintp=n_elements(intp)

	xsspp=[sspp(0)-1,sspp,sspp(dsspp-1)+1]
	vssppi=where(magcomp(xsspp) ne 99999.,vssppc)
	xsspp=xsspp(vssppi)
	magvec=magcomp(intp)
	vintp=where(magvec ne 99999.,vintpc)
	if (vintpc ne 0) then ssint=spline(intp(vintp),magvec(vintp),xsspp) $
					 	else ssint=magcomp(xsspp)

	return
	end

;----------------------------------------------------------------------------
; Despiking master routine

  pro despike,rsec,rbx,rby,rbz,drbx,drby,drbz,spikec

	nrec=n_elements(rbx)

	smagi=replicate(1,nrec,3)    ; Initial spike array indices

	darr=fltarr(nrec,3)
	darr(*,0)=rbx
	darr(*,1)=rby
	darr(*,2)=rbz

	print,format='(a,$)',' % done'

; first find the "spiky" points

	for ic=0,2 do begin

	  yvec=darr(*,ic)
	  maxdevf=3.             ; maximum allowed deviation
	  samlen=420             ; sample length in seconds

	  find_spikes,ic,yvec,maxdevf,samlen,spi
	  if (spi(0) ne -1) then smagi(spi,ic)=0

	endfor
	print
	tsmagi=fix(total(smagi,2))/3
	spikep=where(tsmagi eq 0,spikec)

	if (spikec ne 0) then begin
	  print,'Spikes at second:'
	  for i=0,spikec-1 do begin
	    print,format='(i6,$)',rsec(0)+spikep(i)
	   if (i ne spikec-1) then if (spikep(i+1)-spikep(i) gt 20) then print
	  endfor
	  print
	endif else print,'No spikes detected.'

; ... then remove them with interpolation

	if (spikec ne 0) then begin

	  spxlen=10       ; extra seconds included in the interpolation
			  ; before and after a single spike (initial value)
			  ; The actual value is equal to the spike length
	  intlen=60       ; record length used for the interpolation before
			  ; and after the total spike length

	  for j=0,2 do begin    ; magnetic component loop

	    magcomp=darr(*,j)       ; magnetic component
	    obeg=spikep(0)          ; spike beginning point
	    isp=0                   ; spike counter

	    for i=0L,spikec-1 do begin

	      if (i ne spikec-1) then begin

	        if (spikep(i+1)-spikep(i) gt 2*spxlen) then begin
;	        if (spikep(i+1)-spikep(i) gt 1) then begin

		  spikee=spikep(i)
		  splen=spikee-obeg+1
		  nspxlen=splen
		  remove_spikes,magcomp,obeg,spikee,nspxlen,intlen, $
							sspp,xsspp,ssint
		  darr(xsspp,j)=ssint

		  obeg=spikep(i+1)
		  isp=isp+1

		endif

	      endif else begin

		spikee=spikep(i)
		splen=spikee-obeg+1
		nspxlen=splen
		remove_spikes,magcomp,obeg,spikee,nspxlen,intlen, $
							sspp,xsspp,ssint
		darr(xsspp,j)=ssint
		isp=isp+1

	      endelse

	    endfor

	  endfor
	  smagi=replicate(1,nrec,3)

	endif    ; end of the spike-removing part

	drbx=darr(*,0)
	drby=darr(*,1)
	drbz=darr(*,2)

	return
	end

;----------------------------------------------------------------------------
;------------------------------ MAIN CODE -----------------------------------
;----------------------------------------------------------------------------
; Supply the station ID vector (e.g., ['PAC','ENP','OSO'])

; *** SAMBA chain ***

;	sv=['OHI','ESC','PAC','PNT','OSO','VLD','CER','SER','ANT','PUT'] ; all

;	sv=['PAL']	; Palmer data
;	sv=['OHI']	; O'Higgins data
;	sv=['ESC']	; Escudero data
;	sv=['PAC']	; Punta Arenas data
;	sv=['ENP']	; St. Gregorio data
;	sv=['PNT']	; Puerto Natales data
;	sv=['OSO']	; Osorno data
;	sv=['VLD']	; Valdivia data
;	sv=['CER']	; Los Cerrillos data
;	sv=['SER']	; La Serena data
;	sv=['ANT']	; Antofagasta data
;	sv=['PUT']	; Putre data

; *** MEASURE chain ***

;	sv=['JAX','FIT','DSO','FRD']	; all

;	sv=['JAX']	; Jacksonville data
;	sv=['FIT']	; Florida Tech data
;	sv=['DSO']	; Darksky Observatory data
;	sv=['FRD']	; Fredricksburg data

; *** Martin Connors' chain ***

;	sv=['EDMO']	; Edmonton data
;	sv=['REDR']	; REDR data

; *** Arbitrary (combined chain) vector ***

	sv=['EDMO','REDR']

	nsv=n_elements(sv)

; Enter the start and end dates for a continuous loop generation

;	years=2002 & yeare=years
;	years=2003 & yeare=years
;	years=2004 & yeare=years
;	years=2005 & yeare=years
	years=2006 & yeare=years
	if (years mod 4 eq 0) then leapy=1 else leapy=0

	days=101 & daye=101       ; arbitrary range

;	days=001       & daye=031             ; January data
;	days=032       & daye=059+leapy       ; February data
;	days=060+leapy & daye=090+leapy       ; March data
;	days=091+leapy & daye=120+leapy       ; April data
;	days=121+leapy & daye=151+leapy       ; May data
;	days=152+leapy & daye=181+leapy       ; June data
;	days=182+leapy & daye=212+leapy       ; July data
;	days=213+leapy & daye=243+leapy       ; August data
;	days=244+leapy & daye=273+leapy       ; September data
;	days=274+leapy & daye=304+leapy       ; October data
;	days=305+leapy & daye=334+leapy       ; November data
;	days=335+leapy & daye=365+leapy       ; December data

; Supply the start and end times for the plot (e.g., '110530' for 11:05:30 UT)

;	uts='103000'         ; starting UT   (Daytime period in Chile)
;	ute='223000'         ; ending UT

	uts='003000'         ; starting UT
	ute='233000'         ; ending UT

;	uts='150000'         ; starting UT
;	ute='233000'         ; ending UT

; Supply the frequency range of interest (mHz), fs-start, fe-end.
; If commented out the result includes all available frequencies

	swave='all'

;	fs=10. & fe=60.   & swave='Pc3'     ; Pc3 range, ESC and DSO
;	fs=20. & fe=100.   & swave='Pc3'    ; Pc3 range, standard
	fs=1.  & fe=20.    & swave='Pc4-5'  ; Pc 4-5 range
;	fs=1.  & fe=100.   & swave='Pc3-5'  ; Pc 3-5 range

; Supply the variables to use (up to 3 for plot clarity)
; 0-Bx, Bx component
; 1-By, By component
; 2-Bz, Bz component
; 3-Btotal, sqrt(Bx^2+By^2+Bz^2), B magnitude
; 4-Bhorizontal, sqrt(Bx^2+By^2), Horizontal B magnitude

;	pvi=[0,1,2]          ; plot variable index (X,Y,Z)
	pvi=[0,1,4]            ; plot variable index (X,Y)
	nv=n_elements(pvi)

; optional maximum limits of the transforms for the above chosen variables
; Uncomment to activate!

	maxv1=0.5	; 1st variable
	maxv2=0.5	; 2nd variable
	maxv3=0.5	; 3rd variable

; Supply the Fourier window width in minutes

	fww=50.

; Optional digital filtering (for Pc3 range only!)

	idf=0		; (0-no digital filtering, 1-digital filtering)

; Despiking (4 times)

	idsp=1		; (0-no despiking, 1-despiking)

; Temporal rebin size

	  rbsz=60	; transform image rebin size (seconds), long periods
;	  rbsz=30	; transform image rebin size (seconds), long periods
;	  rbsz=10	; transform image rebin size (seconds), hours
;	  rbsz=1	; transform image rebin size (seconds), <hour

; for long processing periods the resulting transform image is too big
; with unecessarily high temporal resolution. The above parameter rebins
; the image in the time dimension by the given number of seconds.
; rbsz=1 does no rebining.

; Supply the input data file format (ASCII, CDF, BIN)

	dform='asc'
;	dform='cdf'
;	dform='bin'

; Begin the data analysis
; -----------------------

	set_plot,'ps'
	loadct,39

; the specific rpath is completed further down for every year/month

        rpath0='/aurora1/thanasis/magnet/analysis/resonance/Connors/'

;	rpath1='/samba1/sambaweb/sambadata/1sec/'   ; general data read path
	rpath1=rpath0+'samba/1sec/'

;	ppath='/samba2/analysis/transforms/'		; plot path
;	ppath='/samba2/backuptemp/2003/'
;	ppath='/samba2/analysis/transforms/summary/'
;	ppath='/samba2/analysis/transforms/ohiggins/'
;	ppath='/private/thanasis/magnet/analysis/codetest/fourier/'
;	ppath='/samba2/analysis/transforms/codetest/dfilter/'
;	ppath='/samba2/analysis/transforms/aguf04/fourier/'
;	ppath='/samba2/analysis/transforms/chapman05/HtoDratio/'
;	ppath='/samba2/analysis/resonance/restest/findmax/paper1/shortperiod/'
	ppath=rpath0+'fourier/spectra/'

; date string vector

	nday=daye-days+1
	datev=strarr(nday)

	for i=0,nday-1 do begin
	  iday=days+i
	  yearstr=strmid(strtrim(string(years),1),2,2)
	  daystr=strtrim(string(iday),1)
	  if (iday lt 100) then daystr='0'+daystr
	  if (iday lt 10) then daystr='0'+daystr
	  datev(i)=yearstr+daystr
	endfor

; BEGINNING OF THE STATION LOOP (ist)

	for ist=0,nsv-1 do begin

	sid=sv(ist)

	case sid of

; *** SAMBA chain ***

	  'PAL': stloc='Palmer'
	  'OHI': stloc="O'Higgins"
	  'ESC': stloc='Escudero'
	  'PAC': stloc='Punta Arenas'
	  'ENP': stloc='St. Gregorio'
	  'PNT': stloc='Puerto Natales'
	  'OSO': stloc='Osorno'
	  'VLD': stloc='Valdivia'
	  'CER': stloc='Los Cerrillos'
	  'SER': stloc='La Serena'
	  'ANT': stloc='Antofagasta'
	  'PUT': stloc='Putre'

; *** MEASURE chain ***

	  'JAX': stloc='Jacksonville'
	  'FIT': stloc='Florida Tech'
	  'USC': stloc='Univ. South Carolina'
	  'DSO': stloc='Darksky Observatory'
	  'FRD': stloc='Fredricksburg'
	  'APL': stloc='Applied Physics Lab'
	  'MSH': stloc='Millstone Hill'
	  'GTF': stloc='Grafton Test Fac.'
	  'CLK': stloc='Clarkson Univ.'
	  'OTT': stloc='Ottawa'

; *** McMAC chain ***

	  'GLYN': stloc='Glyndon'
	  'WRTH': stloc='Worthington'
	  'BENN': stloc='Bennington'
	  'AMER': stloc='Americus'
	  'PCEL': stloc='Purcell'
	  'RICH': stloc='Richardson'
	  'SATX': stloc='San Antonio'
	  'LYFD': stloc='Lyford'

; *** Martin Connors' chain ***

	  'EDMO': stloc='Edmonton'
	  'REDR': stloc='REDR'

	  else : stloc='Other'
	endcase


	utsns=strmid(uts,0,4)
	utens=strmid(ute,0,4)
	if (nday eq 1) then drstr=datev(0) else drstr=datev(0)+'-'+ $
								datev(nday-1)
	pfile='F'+drstr+'_'+sid+'_'+utsns+'-'+utens+'_'+swave+'.ps'

	psxsz=6.8 & psysz=9.5
	xyr=psxsz/psysz
	device,/portrait,/inches,/color,bits=8,xsize=psxsz,xoffset=1.3, $
				ysize=psysz,yoffset=1.,filename=ppath+pfile

; BEGINNING OF THE DAY LOOP (id)

	monstr=['January','February','March','April','May','June','July', $
		'August','September','October','November','December']
	smon=strmid(monstr,0,3)

	for id=0,nday-1 do begin

; day of the year to date conversion

	date=datev(id)
	sday=strmid(date,2,3)
	day=fix(sday)
	syear=strmid(date,0,2)
	if (fix(syear) gt 80) then year=1900+fix(syear) else year=2000+ $
								fix(syear)
	if (year mod 4 eq 0) then leapy=1 else leapy=0
	day1=[0,31,[59,90,120,151,181,212,243,273,304,334]+leapy]
	dday=day-day1
	cday=min(dday(where(dday gt 0)),cmon)

	print
	if (stloc eq 'Other') then ststr='Station '+sid else $
					ststr=stloc+' ('+sid+')'
	print,ststr+', '+monstr(cmon)+' '+strtrim(string(cday),1)+', '+ $
	  strtrim(string(year),1)+' (day '+sday+'), '+utsns+'-'+utens+' UT'
	print

; Read the appropriate data file (three possible formats, asc, cdf, bin)
;-----------------------------------------------------------------------

	rpath=rpath1+'20'+syear+'/'+smon(cmon)+'/'      ; data read path

	dfile='S'+date+sid+'1s.'+dform

	filech=findfile(rpath+dfile,count=fc)
	if (fc eq 0) then begin
	  print,'File '+dfile+' does not exist'
	  continue
	endif

	case dform of
	  'asc': read_asc,rpath+dfile,data
	  'cdf': read_cdf,rpath+dfile,data
	  'bin': read_bin,rpath+dfile,data
	endcase

	time=rotate(data(0,*),4)
	bx=rotate(data(1,*),4)/1000.
	by=rotate(data(2,*),4)/1000.
	bz=rotate(data(3,*),4)/1000.
	acfl=rotate(data(4,*),4)

; extract the requested time segment

	utsh=long(strmid(uts,0,2))
	utsm=long(strmid(uts,2,2))
	utss=long(strmid(uts,4,2))
	ssec=utsh*3600+utsm*60+utss
	shour=ssec/3600.d0

	uteh=long(strmid(ute,0,2))
	utem=long(strmid(ute,2,2))
	utes=long(strmid(ute,4,2))
	esec=uteh*3600+utem*60+utes
	ehour=esec/3600.d0

	rseci=where(time ge ssec and time le esec,rsecc)
	rsec=time(rseci) & rhour=rsec/3600.d0

; check for valid data in this interval, continue day loop if none

	rmdi=acfl(rseci)
	n9rmdi=where(rmdi ne 9,n9rmdc)
	if (n9rmdc eq 0) then begin
	  print,'No valid data in the requested time interval!'
	  continue
	endif

; Perform the transforms
; ----------------------

	sfww=strtrim(string(fix(fww)),1)
	print,'Conducting Fourier transforms with a '+sfww+ $
		' min window for '+swave+' wave range'
	print

; compute the frequencies of the Fourier tranforms

	t=fix(fww)*60
	f=dblarr(t)

	n2=t/2
	f(0)=0
	for i=0,n2-1 do f(i+1)=(i+1)/double(t)
	for i=0,n2-2 do f(n2+1+i)=-(n2-1-i)/double(t)

	f=f*1000.
	fri=where(f ge fs and f le fe,frc)

	snf=strtrim(string(frc),1)
	fform='('+snf+'f10.3)'
	print,'Requested frequencies (mHz):'
	print,format=fform,f(fri)
	print

;	print,format='(12f10.3)',f
;	print

; extended time series (to avoid edge effects on the original series)

	xssec=max([min(time),ssec-n2])
	xshour=xssec/3600.d0
	xesec=min([max(time),esec+n2])
	xehour=xesec/3600.d0
	xrseci=where(time ge xssec and time le xesec,xrsecc)
	xrsec=time(xrseci) & xrhour=xrsec/3600.d0
	xrbx=bx(xrseci)
	xrby=by(xrseci)
	xrbz=bz(xrseci)

; find missing points and interpolate them

	xracfl=acfl(xrseci)
	xmdi=lonarr(xrsecc)
	mdati=where(xracfl eq 9,mdatc,complement=vdati,ncomplement=vdatc)

	if (mdatc ne 0) then begin

;	  print,'Missing points:'
	  obeg=mdati(0)
	  intlen=5

	  for i=0L,mdatc-1L do begin

	    if (i ne mdatc-1) then begin

	      if (mdati(i+1)-mdati(i) gt intlen) then begin

		mdatp=obeg+lindgen(mdati(i)-obeg+1)
		ibegi=max([obeg-intlen,0])
		iendi=min([mdati(i)+intlen,xrsecc-1])
		case 1 of
		  obeg-ibegi eq 0: intp=reverse(iendi-indgen(iendi-mdati(i)))
		  iendi-mdati(i) eq 0: intp=ibegi+indgen(obeg-ibegi)
		  (obeg-ibegi ne 0) and (iendi-mdati(i) ne 0): $
			intp=[ibegi+indgen(obeg-ibegi), $
			reverse(iendi-indgen(iendi-mdati(i)))]
		endcase
;		intp=[ibegi+indgen(intlen),reverse(iendi-indgen(intlen))]

		nmdatp=n_elements(mdatp)
		if (nmdatp le 10) then begin
;		if (nmdatp le 60) then begin
		  xrbx(mdatp)=spline(intp,xrbx(intp),mdatp)
		  xrby(mdatp)=spline(intp,xrby(intp),mdatp)
		  xrbz(mdatp)=spline(intp,xrbz(intp),mdatp)
		endif else begin
	          case 1 of
		    obeg eq 0: begin
		      xrbx(mdatp)=xrbx(nmdatp)
		      xrby(mdatp)=xrby(nmdatp)
		      xrbz(mdatp)=xrbz(nmdatp)
			       end
		    mdati(i) eq xrsecc-1: begin
		      xrbx(mdatp)=xrbx(mdati(i)-nmdatp)
		      xrby(mdatp)=xrby(mdati(i)-nmdatp)
		      xrbz(mdatp)=xrbz(mdati(i)-nmdatp)
					  end
		    (obeg ne 0) and (mdati(i) ne xrsecc-1): begin
		      xrbx(mdatp)=(xrbx(mdatp(nmdatp-1)+1)-xrbx(mdatp(0)-1))*$
				(indgen(nmdatp)+1)/(nmdatp+1)+xrbx(mdatp(0)-1)
		      xrby(mdatp)=(xrby(mdatp(nmdatp-1)+1)-xrby(mdatp(0)-1))*$
				(indgen(nmdatp)+1)/(nmdatp+1)+xrby(mdatp(0)-1)
		      xrbz(mdatp)=(xrbz(mdatp(nmdatp-1)+1)-xrbz(mdatp(0)-1))*$
				(indgen(nmdatp)+1)/(nmdatp+1)+xrbz(mdatp(0)-1)
							    end
		  endcase
		endelse

;		xrbx(mdatp)=spline(intp,xrbx(intp),mdatp)
;		xrby(mdatp)=spline(intp,xrby(intp),mdatp)
;		xrbz(mdatp)=spline(intp,xrbz(intp),mdatp)

		begsec=obeg+xssec
		sec2ut,begsec,smbeg
		endsec=mdati(i)+xssec
		sec2ut,endsec,smend

;	       print,format='(a,i5,a)','N =',nmdatp,', '+smbeg+'-'+smend+' UT'

		obeg=mdati(i+1)

	      endif

	    endif else begin

	      mdatp=obeg+lindgen(mdati(i)-obeg+1)
	      ibegi=max([obeg-intlen,0])
	      iendi=min([mdati(i)+intlen,xrsecc-1])

	      case 1 of
		obeg-ibegi eq 0: intp=reverse(iendi-indgen(iendi-mdati(i)))
		iendi-mdati(i) eq 0: intp=ibegi+indgen(obeg-ibegi)
		(obeg-ibegi ne 0) and (iendi-mdati(i) ne 0): $
			intp=[ibegi+indgen(obeg-ibegi), $
			reverse(iendi-indgen(iendi-mdati(i)))]
	      endcase

	      nmdatp=n_elements(mdatp)
	      if (nmdatp le 10) then begin
;	      if (nmdatp le 60) then begin
		xrbx(mdatp)=spline(intp,xrbx(intp),mdatp)
		xrby(mdatp)=spline(intp,xrby(intp),mdatp)
		xrbz(mdatp)=spline(intp,xrbz(intp),mdatp)
	      endif else begin
	        case 1 of
		  obeg eq 0: begin
		    xrbx(mdatp)=xrbx(nmdatp)
		    xrby(mdatp)=xrby(nmdatp)
		    xrbz(mdatp)=xrbz(nmdatp)
			     end
		  mdati(i) eq xrsecc-1: begin
		    xrbx(mdatp)=xrbx(mdati(i)-nmdatp)
		    xrby(mdatp)=xrby(mdati(i)-nmdatp)
		    xrbz(mdatp)=xrbz(mdati(i)-nmdatp)
				        end
		  (obeg ne 0) and (mdati(i) ne xrsecc-1): begin
		    xrbx(mdatp)=(xrbx(mdatp(nmdatp-1)+1)-xrbx(mdatp(0)-1))*$
				(indgen(nmdatp)+1)/(nmdatp+1)+xrbx(mdatp(0)-1)
		    xrby(mdatp)=(xrby(mdatp(nmdatp-1)+1)-xrby(mdatp(0)-1))*$
				(indgen(nmdatp)+1)/(nmdatp+1)+xrby(mdatp(0)-1)
		    xrbz(mdatp)=(xrbz(mdatp(nmdatp-1)+1)-xrbz(mdatp(0)-1))*$
				(indgen(nmdatp)+1)/(nmdatp+1)+xrbz(mdatp(0)-1)
							  end
		endcase
	      endelse

	      begsec=obeg+xssec
	      sec2ut,begsec,smbeg
	      endsec=mdati(i)+xssec
	      sec2ut,endsec,smend

;	      print,format='(a,i5,a)','N =',nmdatp,', '+smbeg+'-'+smend+' UT'

	    endelse

	  endfor
	  xmdi(mdati)=1
;	  print

	endif

; Despike the data

	drbx=xrbx & drby=xrby & drbz=xrbz

	if (idsp eq 0) then goto,skip_despike

	print,format='(a,$)','Despiking (1st run)...'
	despike,xrsec,xrbx,xrby,xrbz,drbx,drby,drbz,spikec1

	if (spikec1 ne 0) then begin
	  print
	  print,format='(a,$)','Despiking (2nd run)...'
	  xrbx=drbx & xrby=drby & xrbz=drbz
	  despike,xrsec,xrbx,xrby,xrbz,drbx,drby,drbz,spikec2

	  if (spikec2 ne 0) then begin
	    print
	    print,format='(a,$)','Despiking (3rd run)...'
	    xrbx=drbx & xrby=drby & xrbz=drbz
	    despike,xrsec,xrbx,xrby,xrbz,drbx,drby,drbz,spikec3

	    if (spikec3 ne 0) then begin
	      print
	      print,format='(a,$)','Despiking (4th run)...'
	      xrbx=drbx & xrby=drby & xrbz=drbz
	      despike,xrsec,xrbx,xrby,xrbz,drbx,drby,drbz,spikec4
	    endif

	  endif

	endif

skip_despike:

; define the variables for transform

	xv1=drbx                           & sv1='B!IX!N'
	xv2=drby                           & sv2='B!IY!N'
	xv3=drbz                           & sv3='B!IZ!N'
	xv4=sqrt(drbx^2.+drby^2.+drbz^2.)  & sv4='B!ITOT!N'  ; B magnitude
	xv5=sqrt(drbx^2.+drby^2.)          & sv5='B!IHOR!N'  ; Horizontal B

	asvar=[sv1,sv2,sv3,sv4,sv5]
	svar=asvar(pvi)

	xavara=fltarr(xrsecc,5)
	xavara(*,0)=xv1
	xavara(*,1)=xv2
	xavara(*,2)=xv3
	xavara(*,3)=xv4
	xavara(*,4)=xv5

	xvara=xavara(*,pvi)

; apply a digital filter (optional)

	if (swave eq 'Pc3' and idf eq 1) then begin

	fvara=fltarr(xrsecc,nv)  ; filtered variable array

;	hpf=1.0		; high-pass filter period (min), ESC and DSO
	hpf=1.5		; high-pass filter period (min), default value
	hpw=fww/2.	; high-pass window period (min)
	fnyq=0.5	; Nyquist frequency (Hz)

	flow=1./(hpf*60.)/fnyq
	fhigh=1.
	nterms=hpw*60.

	print
	for iv=0,nv-1 do begin   ; variable loop

	  print,format='(a,i2)','Digital filter of variable',iv+1

	  var=xvara(*,iv)
	  var=var-total(var)/n_elements(var)
	  coeff=digital_filter(flow,fhigh,50,nterms)
	  dfvar=convol(var,coeff)

	  fvara(*,iv)=dfvar

	endfor

	endif

; Fourier transforms

	nrb=rsecc/rbsz
	tvara=dblarr(nrb,frc,nv)

	print
	for iv=0,nv-1 do begin

	  print,'Fourier transform of variable ',strtrim(string(iv+1),1)

	  for j=0L,nrb-1L do begin

	    js=j*rbsz

;	    if ((js+rbsz) mod 600 eq 0) then begin
;	      dsec=js+rbsz+ssec
;	      sec2ut,dsec,utstr
;	      print,format='(a,$)',' '+strmid(utstr,0,4)
;	    endif

	    np=min([js+ssec-xssec,n2])+min([xesec-(js+ssec),n2])
	    ws=js+1
	    we=js+np

	    if (swave eq 'Pc3' and idf eq 1) then var=fvara(ws:we,iv) $
						else var=xvara(ws:we,iv)
	    tvar=fft(var*hanning(np))

	    tvara(j,*,iv)=abs(tvar(fri))

	  endfor	; time loop
;	  print

	endfor		; variable loop
	print

	oss=where(xrsec eq ssec)
	ose=where(xrsec eq esec)
	if (swave eq 'Pc3' and idf eq 1) then $
					fvara=(temporary(fvara))(oss:ose,*)
	vara=xvara(oss:ose,*)

	mdi=xmdi(oss:ose,*)
	pmdati=where(mdi eq 1,pmdatc)

	maxtva=max(tvara)
	mintva=min(tvara)

; Plot the transforms
; -------------------

; BEGINNING OF THE PLOT LOOP (ip)

	!p.multi=[0,1,2*nv]

	for ip=0,2*nv-1 do begin

	iv=ip/2

	llxp=0. & llyp=0. & ygap=0.01
	pxsz=0.82-llxp & pysz=(1.-llyp)/(2*nv)-ygap

	px0=llxp & py0=llyp+ip*(pysz+ygap)
	px1=px0+pxsz & py1=py0+pysz

	if (ip mod 2 eq 0) then begin

; Transform images

	  tvar=tvara(*,*,iv)
	  if (total(tvar) eq 0.) then begin       ; zero image
	    dtvar=tvar
	    maxtv=2. & mintv=0.
	    tvran=maxtv-mintv
	    goto,no_image
	  endif

	  maxtv=max(tvar) & mintv=min(tvar)
	  print,format='(a,i2,a,e9.2,a,f7.2)','Variable',iv+1,', Min:',mintv,$
							'  Max:',maxtv
	  if (iv eq 0 and n_elements(maxv1) ne 0) then maxtv=maxv1
	  if (iv eq 1 and n_elements(maxv2) ne 0) then maxtv=maxv2
	  if (iv eq 2 and n_elements(maxv3) ne 0) then maxtv=maxv3
;	 if (iv eq 0 and n_elements(maxv1) ne 0) then maxtv=min([maxtv,maxv1])
;	 if (iv eq 1 and n_elements(maxv2) ne 0) then maxtv=min([maxtv,maxv2])
;	 if (iv eq 2 and n_elements(maxv3) ne 0) then maxtv=min([maxtv,maxv3])
	  tvran=maxtv-mintv

	  dtvar=255*((tvar-mintv)/tvran)
	  tli=where(dtvar lt 0.,tlc)
	  if (tlc ne 0) then dtvar(tli)=0.d0
	  thi=where(dtvar gt 255.,thc)
	  if (thc ne 0) then dtvar(thi)=255.d0

;	  dtvar=smooth(temporary(dtvar),3,/edge_truncate)

no_image:

	  tv,dtvar,px0,py0,/normal,xsize=pxsz,ysize=pysz

; display color scale at the right of each graph

	  csxsz=0.04 & csysz=1.*pysz
	  bthk=0.002
	  xcs=px1+0.08 & ycs=py0+bthk
	  cstle='!16Wave amplitude'
;	  cstle='!16Wave power'

;	  tlvec=[mintv,maxtv]
	  tlvec=[0.,maxtv]
	  if (tvran lt 1000) then mtst=1 else mtst=round(tvran)/100

	  lt1tkv=[0.5,0.4,0.2,0.1,0.05,0.04,0.02,0.01,0.005,0.004,0.002,0.001]
	  lt1tki=0
repeat_lintick:
	  lintick,tlvec,mtst,2,trmt,trst
	  if (n_elements(trmt) le 4) then begin
	    mtst=lt1tkv(lt1tki)
	    lt1tki=lt1tki+1
	    goto,repeat_lintick
	  endif
	  if (ceil(trmt(1)) ne trmt(1)) then begin
	    tksd=-floor(alog10(mtst))
	    ntrmt=rnd(trmt,tksd)
	    cslbl=strmid(strtrim(string(ntrmt),1),0,tksd+2)
	  endif else begin
	    select_elem,trmt,7,ntrmt
	    cslbl=strtrim(string(round(ntrmt)),1)
	  endelse

	  ior=1   ; vertical color scale (0 for horizontal)

	  cslen=tvran
	  if (ior eq 0) then cssz=csxsz else cssz=csysz
	  lblp=cssz*(ntrmt-mintv)/cslen

	  color_scale,xcs,ycs,csxsz,csysz,bthk,cstle,cslbl,lblp,ior,xyr

; determine the time (x-axis) tickmarks and tick labels

	  if (ip eq 0) then begin
	    ftkint=0  ; forced major tickmark interval in min (0-no action)
	    timeticks,utsh,utsm,uteh,utem,ftkint,xtk,tkint,xtkv,xtkn,xmn
	  endif

; draw the axes and labels

	  minfv=min(f(fri)) & maxfv=max(f(fri))
	  dlf=(maxfv-minfv)/frc
	  minyv=minfv-dlf/2.
	  maxyv=maxfv+dlf/2.
	  yvran=maxyv-minyv

	  csz=2.1 & ycsz=1.1
	  if (ip eq 0) then xcsz=1.2 else xcsz=0.001
	  if (ip eq 0) then xtle='!16Universal Time' else xtle=''
	  mt=''
	  if (minyv gt 0.1) then begin
	    lmaxyv=ceil(maxyv)+1
	    ytfmt='(i'+strtrim(string(lmaxyv),1)+')'
	  endif else begin
	    lminyv=abs(ceil(minyv))
	    lmaxyv=strtrim(string(ceil(maxyv)+2+lminyv),1)
	    ytfmt='(f'+lmaxyv+'.'+strtrim(string(lminyv),1)+')'
	  endelse

	  plot,[shour,ehour],[minyv,maxyv],/nodata,pos=[px0,py0,px1,py1], $
		xstyle=1,ystyle=1,title=mt,charsize=csz,xcharsize=xcsz,$
		ycharsize=ycsz,font=0,xtitle=xtle,ytitle='Frequency (mHz)',$
		yticklen=-0.015,xticklen=-0.04,xticks=xtk,xminor=xmn, $
		xtickv=xtkv,xtickname=xtkn,ytickformat=ytfmt,/noerase

	endif else begin

; Time series plots

	  if (swave eq 'Pc3' and idf eq 1) then yvar=fvara(*,iv) $
							else yvar=vara(*,iv)

; set up the plot parameters

	  minyv=min(yvar) & maxyv=max(yvar)
	  yvran=maxyv-minyv
	  minyv=minyv-yvran*(0.01/pysz)
	  maxyv=maxyv+yvran*(0.01/pysz)

	  if (ip eq 2*nv-1) then mt='Fourier spectra, '+ststr+', '+ $
		strtrim(string(cday),1)+' '+monstr(cmon)+' '+ $
		strtrim(string(year),1)+' (day '+sday+')' else mt=''
	  if (ip eq 0) then xcsz=1. else xcsz=0.001
	  if (yvran lt 4.) then ytfmt='(f8.1)' else ytfmt='(i6)'

; plot the data

	  plot,[shour,ehour],[minyv,maxyv],/nodata,pos=[px0,py0,px1,py1], $
		xstyle=1,ystyle=1,title=mt,charsize=2.1,xcharsize=xcsz, $
		ycharsize=1.,thick=3.,font=0,xtitle=xtle,ytitle='nT', $
		yticklen=-0.01,xticklen=0.04,xticks=xtk,xminor=xmn, $
		xtickv=xtkv,xtickname=xtkn,ytickformat=ytfmt,/noerase

	  for i=0L,long(rsecc-2) do begin
	    if (rsec(i+1)-rsec(i) gt 1) then continue
	    if (mdi(i+1) eq 1 or mdi(i) eq 1) then continue
	    oplot,rhour(i:i+1),yvar(i:i+1),thick=2.
	  endfor

; image titles

	  if (swave eq 'Pc3' and idf eq 1) then imt=[swave,'filter', $
			svar(iv)+' (nT)'] else imt=[svar(iv)]
	  dimt=n_elements(imt)
	  for i=0,dimt-1 do xyouts,xcs+csxsz/2.,py1-(0.5-dimt*0.1+i*0.22)*pysz,$
		imt(i),/normal,font=0,alignment=0.5,charsize=1.9

	endelse

; END OF THE PLOT LOOP (ip)

	endfor
	!p.multi=0.

; parameter note

	srbsz=strtrim(string(rbsz),1)
;	spar='window='+sfww+'min'
	spar='window='+sfww+'min, tres='+srbsz+'sec'
	xyouts,1.,-0.07,spar,/normal,alignment=1,font=0,charsize=0.7

; END OF THE DAY LOOP (id)

	endfor

	device,/close
	if (strmid(ppath,1,5) eq 'samba') then spawn,'chmod go+rw '+$
							ppath+pfile,slog

; END OF THE STATION LOOP (ist)

	endfor
	set_plot,'x'

finish:

	print
	end
