; program written by Mark New

pro GHCNcruTSpre

print, "  > Enter the inventory file: "
read, InvFile

print, "  > Enter the corresponding data file: "
read, DataFile

print, "  > Enter the CRU ts file to which to save: "
read, DumpFile

; converts ghcn precip to CRU monthly format
rptsf,loc,4,file=InvFile,$
 form='(i7,f7.2,f8.2,i5)'
rstrf,name,2,file=InvFile,$
 form='(28x,a20,10x,a13)'
;
close,/all
openr,1,DataFile
openw,2,DumpFile
on_ioerror,bad_num
oldid=1
valid=1
eof=0
i=0.0
dat=lonarr(400,12)-9999
year=lonarr(400)-9999
temp=lonarr(12)
while valid eq 1 do begin
 readf,1,id,iy,temp,form='(i7,2x,13i5)'
 n=where(temp eq -8888,nn)
 if nn gt 0 then temp(n)=0
 if oldid eq id then dat(iy-1601,0:11)=temp
 if oldid eq id then year(iy-1601)=iy
 if id ne oldid then begin
  goto,skip
  bad_num:
  eof=1
  skip:
  n=where(year ne -9999)
  yrs=rnge(year(n))
  i=i+1
  if round(i/250.0)*250 eq i then print,i
  n=where(round(loc(*,0)) eq oldid)
  printf,2,loc(n(0),0),round(loc(n(0),1:2)*100),loc(n(0),3),$
   name(n(0),0:1),yrs,form=mts_hfmt()
  for jy=yrs(0),yrs(1) do begin
   printf,2,jy,dat(jy-1601,*),form=mts_dfmt()
  endfor
  if eof eq 1 then goto,finish
  dat=lonarr(400,12)-9999
  year=lonarr(400)-9999
  dat(iy-1601,0:11)=temp
  year(iy-1601)=iy
  oldid=id
;  if i gt 20 then goto,finish
 endif
endwhile
finish:
close,/all
print,round(i),' Stations processed'
end
