TEMA indicator not working properly by reducing number of bars

 

So I have found this TEMA indicator and I just wanted to limit the number of Bars it needs to process by adding a new parameter "BarsBack".

The problem is that by doing this it messes up the indicator line.


The attached code is as follows

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 DarkBlue
#property  indicator_width1  2
//---- input parameters
extern int       EMA_period=14;
extern int       BarsBack=1500;
//---- buffers
double TemaBuffer[];
double Ema[];
double EmaOfEma[];
double EmaOfEmaOfEma[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   IndicatorBuffers(4);
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,TemaBuffer);
   SetIndexBuffer(1,Ema);
   SetIndexBuffer(2,EmaOfEma);
   SetIndexBuffer(3,EmaOfEmaOfEma);
   SetIndexDrawBegin(0, Bars - BarsBack);
   IndicatorShortName("TEMA("+EMA_period+")");
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   int i,limit,limit2,limit3,counted_bars=IndicatorCounted();
//---++
      
      
      if(Bars>BarsBack)
      {
      limit=BarsBack;
      }
      else     
      {
      limit=Bars-counted_bars-1;
      }
      limit2=limit;
      limit3=limit2;
     
   for (i=limit;i>=0;i--) Ema[i]=iMA(NULL,0,EMA_period,0,MODE_EMA,PRICE_CLOSE,i);
   for (i=limit2;i>=0;i--) EmaOfEma[i]=iMAOnArray(Ema,0,EMA_period,0,MODE_EMA,i);
   for (i=limit3;i>=0;i--) EmaOfEmaOfEma[i]=iMAOnArray(EmaOfEma,0,EMA_period,0,MODE_EMA,i);
   for (i=limit3;i>=0;i--) TemaBuffer[i]=3*Ema[i]-3*EmaOfEma[i]+EmaOfEmaOfEma[i];
//----
   return(0);
  }
//+------------------------------------------------------------------+

I have attached also an image with the jumbled mess that appears on the leftmost part of the indicator when I try to limit the amount of bars with this piece of code.

if(Bars>BarsBack)
      {
      limit=BarsBack;
     }

If i limit the bars like this  for a simple moving average code I do not get the mess that you see in the attached image. 

I strongly believe there is something I don't understand I personally believe it has something to do with the IMAOnArray part.

If I limit the bars even more like to 500 it just doesn't display properly at all.

Can you guys please help me here, shed some light on this?

Files: