; cleandtb.pro
; IDL program written by Tim Mitchell on 07.11.02
; designed to run with cleandtb.f90
;   but can be used by itself

; ******************************************************************************

pro GrabDumpData,DumpFile,DumpData,DumpYearAD,DumpWMO,DumpName,DumpCty,DumpText,DumpPlot,DumpTitle

DumpWMO=0L & DumpName="" & DumpCty="" & DumpYearN=0 & DumpText="" & DumpTitle=""
GVcommand = "" & IPcommand = "" & DumpPlot=0
Int0=0L & Int1=0L & Int2=0L & Int3=0L & Int4=0L & Int5=0L
Int6=0L & Int7=0L & Int8=0L & Int9=0L & Int10=0L & Int11=0L

openr, lunDump, DumpFile, /get_lun
readf, lunDump, DumpWMO, DumpName, DumpCty, DumpYearN, DumpText, DumpPlot, $
		format="(i8,x,a20,x,a13,x,i4,x,a8,x,i2)"
readf, lunDump, DumpTitle

DumpData=fltarr(12,DumpYearN) & DumpYearAD=intarr(DumpYearN)
      
for XDumpYear = 0, DumpYearN-1 do begin
  readf,lunDump,HYear,Int0,Int1,Int2,Int3,Int4,Int5,Int6,Int7,Int8,Int9,Int10,Int11,format="(i4,12i5)"
  DumpYearAD(XDumpYear)=HYear
  DumpData(0,XDumpYear)=float(Int0)   & DumpData(1,XDumpYear)=float(Int1) 
  DumpData(2,XDumpYear)=float(Int2)   & DumpData(3,XDumpYear)=float(Int3) 
  DumpData(4,XDumpYear)=float(Int4)   & DumpData(5,XDumpYear)=float(Int5) 
  DumpData(6,XDumpYear)=float(Int6)   & DumpData(7,XDumpYear)=float(Int7) 
  DumpData(8,XDumpYear)=float(Int8)   & DumpData(9,XDumpYear)=float(Int9) 
  DumpData(10,XDumpYear)=float(Int10) & DumpData(11,XDumpYear)=float(Int11) 
endfor

free_lun, lunDump

end

; ******************************************************************************

pro GrabBegEnd,DumpData,DumpMissVal,XYear0,XYear1

DimDumpData=size(DumpData) & DumpYearN=DimDumpData(2)

XYear0=-1 & XDumpYear=-1
while (XYear0 LT 0 AND XDumpYear NE DumpYearN) do begin
  XDumpYear = XDumpYear + 1
  for XMonth = 0, 11 do begin
    if (DumpData(XMonth,XDumpYear) NE DumpMissVal) then XYear0 = XDumpYear
  endfor
endwhile
      
XYear1=-1 & XDumpYear=DumpYearN
while (XYear1 LT 0 AND XDumpYear NE -1) do begin
  XDumpYear = XDumpYear - 1
  for XMonth = 0, 11 do begin
    if (DumpData(XMonth,XDumpYear) NE DumpMissVal) then XYear1 = XDumpYear
  endfor
endwhile

end

; ******************************************************************************

pro CleanDTB, $
	SetDivisor=SetDivisor, $
	NoMetaPlot=NoMetaPlot, $	; remove meta info from plot
	XSizeMulti=XSizeMulti, $	; default = 1.0
	YSizeMulti=YSizeMulti, $	; default = 1.0
	ForceScale=ForceScale, $	; 61(absT),62(anoT),63(absP),64(anoP)
	ForceMin=ForceMin, $		; force minimum of scale
	ForceMax=ForceMax, $		; force maximum of scale
	Silent=Silent

; *************************************** intro

if ( NOT arg_present(Silent)) then begin
  print, ""
  print, "  > ***** CleanDTB.pro: plots station time-series *****"
  print, "  > ***** you many minimise this terminal *****"
  print, ""
endif

Black = 0 & Grey = 254 & White = 255
MissVal  = -999.0 & MissCol = White
ScaleSegN = 10 & BatchFileN = 0 & GivenYear = 0 & SuspectBreak = -999
InputText = "" & GivenFile = "" & LastDumpText="standard"
RangeFract = 0.0D & ColSelect  = 0.0D
Int0=0L & Int1=0L & Int2=0L & Int3=0L & Int4=0L & Int5=0L
Int6=0L & Int7=0L & Int8=0L & Int9=0L & Int10=0L & Int11=0L
DumpWMO=0L & DumpName="" & DumpCty="" & DumpYearN=0 & DumpText="" 
DumpTitle="" & DumpPlot=0
MemYearAD0=-999 & MemYearAD1=-999 & QFound=-1

Months = [0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5,10.5,11.5]
XLabel = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

if (keyword_set(NoMetaPlot)) then begin
  PlotCorners  = [0.10,0.05,0.80,0.95]
  ScaleCorners = [0.85,0.05,0.95,0.95]
endif else begin
  PlotCorners  = [0.10,0.12,0.80,0.88]
  ScaleCorners = [0.85,0.08,0.95,0.88]
endelse

XPixels=12 & YPixels=12
if (keyword_set(XSizeMulti)) then XPixels = XPixels * XSizeMulti
if (keyword_set(YSizeMulti)) then YPixels = YPixels * YSizeMulti

; *************************************** specify variable

spawn, 'rm /cru/scratch2/f709762/f90toidl.pipe', StOut
spawn, 'mkfifo -m a=rw /cru/scratch2/f709762/f90toidl.pipe'
spawn, 'tail < /cru/scratch2/f709762/f90toidl.pipe', F90info

VariableSuffix = "" & VariableSuffix = strtrim(F90info(0),2)

if            (VariableSuffix EQ ".pre") then begin
  TmpPre=1 & Divisor=10
endif else if (VariableSuffix EQ ".tmp") then begin
  TmpPre=0 & Divisor=10
endif else if (VariableSuffix EQ ".dtr") then begin
  TmpPre=0 & Divisor=10
endif else if (VariableSuffix EQ ".cld") then begin
  TmpPre=1 & Divisor=10
endif else if (VariableSuffix EQ ".spc") then begin
  TmpPre=0 & Divisor=10
endif else if (VariableSuffix EQ ".wet") then begin
  TmpPre=1 & Divisor=100
endif else if (VariableSuffix EQ ".rhm") then begin
  TmpPre=1 & Divisor=10
endif else if (VariableSuffix EQ ".vap") then begin
  TmpPre=1 & Divisor=10
endif else begin
  print, "  > @@@@@ ERROR: variable unrecognised @@@@@"
endelse

AbsScale=61 & AnoScale=62 & StDevRange=10
if (TmpPre EQ 1) then begin
  AbsScale=63 & AnoScale=64 & StDevRange=5
endif

if (keyword_set(ForceScale)) then begin
  loadanyct, ForceScale
endif else begin
  loadanyct, AbsScale
endelse

DumpMissVal = -9999.0/Divisor

; *************************************** main station loop

DumpFile="" & CurrentStn=0L

while (DumpFile NE "end") do begin
  spawn, 'tail < /cru/scratch2/f709762/f90toidl.pipe', F90info	; get file path
  DumpFile = strtrim(F90info(0),2)
  if ( NOT arg_present(Silent)) then print, "file  = ", strtrim(DumpFile,2)
  
  if (strtrim(DumpFile,2) NE 'end') then begin
    GrabDumpData,DumpFile,DumpData,DumpYearAD,DumpWMO,DumpName,DumpCty,DumpText, $
    		DumpPlot,DumpTitle	; get data
    
    DumpData(*,*) = DumpData(*,*) / Divisor		; convert to *1.0 values
    
    LastSlash   = strpos(DumpFile,"/",/Reverse_Search)
    FirstDigit  = LastSlash + 8
    AfterEnd    = strpos(DumpFile,".",FirstDigit)
    StnCodeText = strmid(DumpFile,FirstDigit,(AfterEnd-FirstDigit))
    StnCode     = long(StnCodeText)
    
    if (StnCode NE CurrentStn) then begin			; get beg/end years
        GrabBegEnd,DumpData,DumpMissVal,XYear0,XYear1
        PlotYearAD0=DumpYearAD(XYear0) & PlotYearAD1=DumpYearAD(XYear1)
        if ( NOT arg_present(Silent)) then print, $
        	"NEW STATION DETECTED: ",PlotYearAD0,PlotYearAD1
        CurrentStn = StnCode
    endif

    Missings = where (DumpData EQ DumpMissVal, Count)		; shrink to desired data
    if (Count GT 0) then DumpData [Missings] = !Values.F_NaN
    Reformed = reform(DumpData(*,XYear0:XYear1))
    Years = DumpYearAD(XYear0:XYear1)
    
    if  	  (strmid(DumpText,0,4) EQ 'Homo') then begin	; get data range
      DataMin = -4.0 & DataMax = 4.0
    endif else if (strmid(DumpText,0,4) EQ 'Abso') then begin
      if (strmid(DumpText,4,4) EQ 'Orig') then begin
        DataMin = min(Reformed,max=DataMax, /nan)
        AbsoDataMin=DataMin & AbsoDataMax=DataMax
      endif else begin
        DataMin=AbsoDataMin & DataMax=AbsoDataMax
      endelse
    endif else if (strmid(DumpText,0,4) EQ 'Anom') then begin
      if (strmid(DumpText,4,4) EQ 'Orig') then begin
        DataMin = min(Reformed,max=DataMax, /nan)
        if (DataMax LT abs(DataMin)) then begin
          DataMax=abs(DataMin)
        endif else begin
          DataMin=0.0-DataMax
        endelse
        AnomDataMin=DataMin & AnomDataMax=DataMax
      endif else begin
        DataMin=AnomDataMin & DataMax=AnomDataMax
      endelse
    endif else if (strmid(DumpText,0,4) EQ 'Step') then begin
      if (strmid(DumpText,4,4) EQ 'Orig') then begin
        DataMin = min(Reformed,max=DataMax, /nan)
        if (DataMax LT abs(DataMin)) then begin
          DataMax=abs(DataMin)
        endif else begin
          DataMin=0.0-DataMax
        endelse
        StepDataMin=DataMin & StepDataMax=DataMax
      endif else begin
        DataMin=StepDataMin & DataMax=StepDataMax
      endelse
    endif
    
    PlotTitle = strtrim(DumpName,2) + ' (' + strtrim(DumpCty,2) + ', ' + $
    				strtrim(string(DumpWMO),2) + ')'
    StrLoc = strpos(DumpFile,'/',/reverse_search)
    StrLen = strlen(DumpFile)
    StrSub = strmid(DumpFile,(StrLoc+1),(StrLen-StrLoc-4))
    SavePath = '/cru/scratch2/f709762/' + StrSub + 'eps'
    
    YearADFlt = float(Years)/10.0
    YearADInt = round(YearADFlt)
    YTickVal  = where (float(YearADInt) EQ YearADFlt, YTickCount)    
    YearADInt = YearADInt * 10
    
    if (ytickcount eq 0) then begin	; no decade data range, do start/end instead
    	YearADInt = Years
    	YearADIntDim = size (YearADInt)
    	ytickcount = 2
    	ytickval = intarr(ytickcount)
    	ytickval(*) = [0,YearADIntDim[1]-1]
    endif
    
    if (strmid(DumpText,0,4) EQ 'Anom' OR strmid(DumpText,0,4) EQ 'Homo') $
    		then loadanyct, AnoScale
    
    if (keyword_set(ForceMin)) then DataMin = ForceMin
    if (keyword_set(ForceMax)) then DataMax = ForceMax
    GetContours, [DataMin,DataMax], [1,253], Contours, ContourColors, 21
    ContoursSparse = fltarr(5)
    for XSparse = 0, 4 do begin
      ContoursSparse(XSparse) = DataMin + (XSparse * ((DataMax-DataMin) / 4))
    endfor
    
    TrimToScale, Reformed, TrimSlice, [DataMin,DataMax], /SinglePrec
    
    Set_Plot, 'ps', /copy
    device, filename=SavePath, bits_per_pixel=8, xsize=XPixels, ysize=YPixels,/Color,/encapsulated
    
    if (keyword_set(NoMetaPlot)) then begin
      plot, [PlotYearAD0,PlotYearAD1], xrange=[0.5,11.5], yrange=[PlotYearAD0,PlotYearAD1], position=PlotCorners, $
    	ticklen=1.0,color=Black,/noerase,/nodata,charsize=0.8, $
    	xstyle=1, xticks=11, xthick=1, xtickv=months, xtickname=xlabel, font=5,  $
    	ystyle=1, yticks=YTickCount-1, ythick=1, ytickv=YearADInt[YTickVal]
    endif else begin
      plot, [PlotYearAD0,PlotYearAD1], xrange=[0.5,11.5], yrange=[PlotYearAD0,PlotYearAD1], position=PlotCorners, $
    	ticklen=1.0,color=Black,/noerase,/nodata,subtitle=PlotTitle,title=DumpTitle,charsize=0.8, $
    	xstyle=1, xticks=11, xthick=1, xtickv=months, xtickname=xlabel, font=5,  $
    	ystyle=1, yticks=YTickCount-1, ythick=1, ytickv=YearADInt[YTickVal]
    endelse
    
    contour, TrimSlice, Months, Years, levels=Contours, $
    	c_colors=ContourColors, /cell_fill, /overplot,/noerase
    
    if (keyword_set(NoMetaPlot)) then begin
      plot, [PlotYearAD0,PlotYearAD1], xrange=[0.5,11.5], yrange=[PlotYearAD0,PlotYearAD1], position=PlotCorners, $
    	ticklen=1.0,color=Black,/noerase,/nodata,charsize=0.8, $
    	xstyle=1, xticks=11, xthick=1, xtickv=months, xtickname=xlabel, font=5, $
    	ystyle=1, yticks=YTickCount-1, ythick=1, ytickv=YearADInt[YTickVal]
    endif else begin
      plot, [PlotYearAD0,PlotYearAD1], xrange=[0.5,11.5], yrange=[PlotYearAD0,PlotYearAD1], position=PlotCorners, $
    	ticklen=1.0,color=Black,/noerase,/nodata,subtitle=PlotTitle,title=DumpTitle,charsize=0.8, $
    	xstyle=1, xticks=11, xthick=1, xtickv=months, xtickname=xlabel, font=5, $
    	ystyle=1, yticks=YTickCount-1, ythick=1, ytickv=YearADInt[YTickVal]
    endelse
    
    DrawConScale,ScaleCorners,Contours,ContourColors,ContoursSparse,"(f7.2)",0.8,1,"",XPixels,YPixels,0
    
    device, /close
    set_plot, 'X'	

    if (strmid(DumpText,0,4) EQ 'Anom' OR strmid(DumpText,0,4) EQ 'Homo') $
    		then loadanyct, AbsScale
    
    if ( NOT arg_present(Silent)) then print, "save  = ", strtrim(SavePath,2)
    GVcommand = 'ghostview ' + strtrim(SavePath,2) + ' &'
    if (DumpPlot NE 2) then spawn, GVcommand, GVoutput
  endif
endwhile

; *************************************** end

if ( NOT arg_present(Silent)) then print, ""

spawn, 'rm /cru/scratch2/f709762/f90toidl.pipe'

end 
