Function calc_compound(P,J,K,C,Meth, sum78s, totInterest, pmtNum, term )
	if J <> 0 and (Meth = "Normal" or Meth = "Interest only") then
		if K > C then
			K = C
		end if
		calc_compound = P * (1 + J/C) ^ K
		calc_compound = calc_compound - P
		calc_compound = FormatNumber(calc_compound , 2)
	else if Meth = "Rule-of-78's" then
		count = term - pmtNum
		calc_compound = totInterest*(count/sum78s)
	else
		calc_compound = 0
	end if	
	end if		
End Function


Function calc_compound_rate_per_period (J,C,F, Meth)
	if J <> 0 and (Meth = "Normal" or Meth = "Interest only" or Meth = "Rule-of-78's") then
		calc_compound_rate_per_period = (1+J/C)^(C/F)-1
	else
		calc_compound_rate_per_period = 0
	end if
End Function

Function calc_term(P,J,M)
	if M <> 0 then
		if J <> 0 and (1 - J * CDbl(P) / CDbl(M) >= 0) then
			value1 = Log(1 - J * CDbl(P) / CDbl(M))
			value2 = Log(1 + J)
			calc_term  = value1 / value2
			calc_term  = Abs(calc_term)
			calc_term  = FormatNumber(calc_term, 0)
		else
			calc_term  = ""
		end if
	else
		calc_term  = ""		
	end if
End Function


Function calc_pymt(P,J,K,C,F,Meth)
	if J <> 0 then
		calc_pymt = P * ( J / (1 - (1 + J) ^ -K))
		calc_pymt = FormatNumber(calc_pymt, 2)
 		if Meth = "Interest only" then
 			calc_pymt = calc_pymt - P
 		end if
 		
	else
		calc_pymt = P
	end if					
End Function

Function calc_prin(M,J,K)
	if J <> 0 then
		calc_prin = ((M/J) *  (1-(1/(1+(J))^K)))
		calc_prin = FormatNumber(calc_prin, 2)
	else
		calc_prin = "0"
	end if			
End Function


function calc_rate(P, K, M, C, F, Meth) 

	GuessHigh   = 100   'maximum value 
	GuessMiddle = 2.5   'first guess 
	GuessLow    = 0      'minimum value 
	GuessPMT    = 0      'result of test calculation
	 
	do while CDbl(GuessPMT) <> CDbl(M)
	
		J = calc_compound_rate_per_period(GuessMiddle/100,C,F,Meth)
		J = J * F
 		GuessPMT = calc_pymt(P,J,K,C,F,Meth)

   		if CDbl(GuessPMT) > CDbl(M) then
      		GuessHigh   = GuessMiddle 
      		GuessMiddle = GuessMiddle + GuessLow 
      		GuessMiddle = GuessMiddle / 2 
   		end if 
    
   		if CDbl(GuessPMT) <  CDbl(M) then
      		GuessLow    = GuessMiddle 
      		GuessMiddle = GuessMiddle + GuessHigh 
      		GuessMiddle = GuessMiddle / 2 
   		end if 


   		if GuessMiddle = GuessHigh then
   			exit do
   		end if
   		if GuessMiddle = GuessLow then
   			exit do
   		end if


   		calc_rate = FormatNumber(GuessMiddle, 9)
   		if calc_rate = 0 then
      		exit do 
      	end if
   loop

End Function
