# Tension Spline R Code. T Cropper 2013 (modified from H. Bjornsson)
{
if (length(mondata)!=12) stop("the variable mondata is your monthly mean series and must have exactly twelve monthly values")
monlen = c(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # number of days in each month
numdays = c(1:367) # number of days in year add one
montoyear = rep(mondata,monlen) # creates a series where all of one months daily values equal the monthly mean
cumyear = cumsum(c(0,montoyear)) # cumulative daily total
endyear = c(0,cumsum(monlen))+1 # marks the end of each month during the year
ltrend = seq(from=0, to=cumyear[length(cumyear)], length.out =length(cumyear))
cumyearanom = cumyear-ltrend
tensionspline = spline(y = cumyearanom[endyear], x = endyear, xout=numdays, method ="periodic")
AnnualSpline = diff(tensionspline$y)+diff(ltrend) # annual cycle of daily data that retains the monthly average as estimated by the tension spline method
# basic plot of spline and is written to a txt file
plot(AnnualSpline, col="2", xlab="Julian Day")
lines(montoyear)
write.csv(AnnualSpline, file="tensionspline.csv")
}