PROGRAM FTCTempAnalysis1

! Written by Kate T-C
! August 27, 2009
! This program calculates a trend and correlation coefficient in 
! a 1-dimensional array of data

implicit none

integer, parameter :: years = 41, months=12
real, dimension(years*months) :: TimeIndexes, AvgMonthlyTemps
integer :: counter = 0, n=years*months
real :: AvgTemp = 0, SumTime=0, SumTimeSquare=0, SumTemps=0, SumTempsTime=0
real :: slope = 0, intercept = 0, error=0, variance=0, rsquare=0

	! Read in my data from the command line
	do counter=1,years*months
		read *, AvgMonthlyTemps(counter)  
		TimeIndexes(counter) = counter
	end do
	
	! Calculate the average Temperature for all Temps
	AvgTemp = sum(AvgMonthlyTemps)/real(years*months)
	
	! Calculate the four sums that we need
	SumTime = sum(TimeIndexes)
	SumTemps = sum(AvgMonthlyTemps)
	
	do counter=1,years*months
		SumTimeSquare = SumTimeSquare + TimeIndexes(counter)**2
		SumTempsTime = SumTempsTime + AvgMonthlyTemps(counter)*TimeIndexes(counter)
	end do

	! Calculate the slope of the trend
	slope = (n*SumTempsTime - SumTemps*SumTime)/(n*SumTimeSquare - SumTime**2)
	! Calculate the intercept of the trendline
	intercept = SumTemps/n - slope*SumTime/n
	
	! Calculate the corrolation coefficient
	do counter=1,years*months
		error = error + (AvgMonthlyTemps(counter) - (slope*TimeIndexes(counter)+intercept))**2
		variance = variance + (AvgMonthlyTemps(counter) - AvgTemp)**2
	end do
		
	rsquare = 1 - error/variance

	print *, 'Slope of the best-fit line: ', slope
	print *, 'Intercept of the line: ', intercept
	print *, 'Corrolation coefficient: ', rsquare
END
