average range custom indicator

 
Hello. I'm trying to develop an indicator that plots the average range, which is simply the summation of the highs minus the lows divided by the number of bars. I'm relatively new to the metaquotes language, so I simply modified the code for the moving average custom indicator which came pre-installed. Here is what I came up with:

Inputs : ARPeriod(9), Factor(1);

var:X(0), AvgRange(0), prevbars(0), first(True), shift(0), loopbegin(0);

SetLoopCount(0);
If ARPeriod < 1 Then Exit;
If Bars < prevbars Or Bars-prevbars>1 Then first = True;
prevbars = Bars;
If first Then Begin
loopbegin = Bars-ARPeriod-1;
If loopbegin < 0 Then Exit;
first = False;
End;

loopbegin = loopbegin+1;
For shift = loopbegin Downto 0 Begin
AvgRange = 0;
for X = 0 to(ARPeriod-1) Begin
AvgRange = AvgRange + High[X] - Low[X];
End;
AvgRange = AvgRange/ARPeriod;
SetIndexValue(shift,iMA(ARPeriod,MODE_SMA,shift)+AvgRange*Factor);
SetIndexValue2(shift,iMA(ARPeriod,MODE_SMA,shift)-AvgRange*Factor);
loopbegin = loopbegin-1;
End;

Unfortunately, I don't really know what half of this code really does. It looked pretty close, but I spotchecked a point on the graph and it was slightly off. Can anyone help me correct this code to compute the average range correctly? Thanks, J