; written by csmith. makes lots of assumptions about sizes. undef("writets") function writets (x, mon1,mon2,year1,year2,filename,filenamecsv,description) local nyears,N,M,ierr,x1 begin ; get array shape/sizes ierr=0 nyears=(year2-year1)+1 nmons=(mon2-mon1)+1 if(.not.any(ismissing(x))) then x@missing_value=-99.0 else x(ind(ismissing(x))) = -99.0 end if delete(x@missing_value) x@missing_value=-99. ntot=dimsizes(x) N = nyears ; number of nyears rows M = nmons ; number of columns square = N*M print(square+" "+N+" "+M+" "+ntot) if(square.ne.ntot)then jmiss = square-ntot x2 = new((/jmiss/),"float",x@missing_value) xnew = array_append_record (x, x2, 0 ) xnew@missing_value = x@missing_value else xnew = x xnew@missing_value = x@missing_value end if x1 = onedtond(xnew,(/N,M/)) k = 0 linevar = new( N+10, "string") linevarcsv = new( (N*M)+1, "string") linevar(0) = " "+year1+" "+year2 fmt1 = "%9.3f" fmt2 = "%2.2d" totaltime = N*M do it = 0,N-1 nnyear=it+year1 if(M.eq.12)then linevar(it+1)=nnyear+" "+sprintf(fmt1,x1(it,0))+" "+sprintf(fmt1,x1(it,1))+" "+sprintf(fmt1,x1(it,2))+" "+sprintf(fmt1,x1(it,3))+" "+sprintf(fmt1,x1(it,4))+" "+sprintf(fmt1,x1(it,5))+" "+sprintf(fmt1,x1(it,6))+" "+sprintf(fmt1,x1(it,7))+" "+sprintf(fmt1,x1(it,8))+" "+sprintf(fmt1,x1(it,9))+" "+sprintf(fmt1,x1(it,10))+" "+sprintf(fmt1,x1(it,11)) else linevar(it+1)=nnyear+" "+sprintf(fmt1,x1(it,0)) end if end do linevarcsv(0)="Date, "+description(0)+" "+description(1)+" "+description(2) ii=1 do it=0,N-1 do im=0,M-1 nnyear=it+year1 cm=sprinti(fmt2,im+1) if(M.eq.12)then linevarcsv(ii)=nnyear+"-"+cm+"-01,"+sprintf(fmt1,x1(it,im)) else linevarcsv(ii)=nnyear+","+sprintf(fmt1,x1(it,im)) end if ii=ii+1 delete(cm) end do end do linevar(N+1)=x@missing_value linevar(N+2)=description(0) linevar(N+3)=description(1) linevar(N+4)=description(2) linevar(N+5)=description(3) linevar(N+6)=description(4) linevar(N+7)=description(5) linevar(N+8)=description(6) linevar(N+9)=description(7) asciiwrite(filename,linevar) print ("Writing CSV "+filenamecsv) asciiwrite(filenamecsv,linevarcsv) return(ierr) end