Problems with showing lower TimeFrame's ZigZag On the current chart, help needed!

 
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   ArrayInitialize(CiDuanBuffer,0);
   ArrayInitialize(DuanBuffer,0);
// Copied a lower time frame ZigZag
   if(CopyBuffer(XianDuanHandler,0,0,MathFloor(rates_total/3),CiDuanBuffer)<=0)
      return(0);

   ArraySetAsSeries(CiDuanBuffer,true);
   ArraySetAsSeries(time,true);
   ArraySetAsSeries(high,true);   

   ArraySetAsSeries(low,true);



   int i, j, start=ArraySize(CiDuanBuffer)-1, count=0;
   GapK=CalculatePeriod();

   for(i=1;i<start && !IsStopped();i++)
     {
      if(!CiDuanBuffer[i])
         continue;

      int location = i<=GapK ? 0 : MathFloor((i-GapK)/ 15)+1;
      // All Ks will be 
      DuanBuffer[location] = CiDuanBuffer[i];
     }


//--- return value of prev_calculated for next call
   return(rates_total);
  }


/* Calculate the "gap" Ks. Will be explained above
 */
int CalculatePeriod()
  {
   datetime current_tick = TimeCurrent();
   MqlDateTime current;
   TimeToStruct(current_tick,current);
   double minutes = current.min;
   int gap_k=0;     
// 
   while(MathMod(minutes,LowerTimeFrameMultiplier)!=0&&!IsStopped())
     {
      minutes--;
      gap_k++;
     }
   return gap_k;
  }



-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



CiDuanBuffer stores an indicator which could be think as Zigzag (almost the same). What I want to do here is to show "Zigzag from a lower timeframe" on the chart(which is a higher timeframe).

An example would be to show a 1min Zigzag on 15min chart. So I first get the current minute(assume the market is openning), then decide a gap_k. For example, if the current min is 47,then the

current 15min K(**:45:00) will have a gap_K of 2. So if there is a zigzag value (not equal to 0) in position 1 or 2, the value will be displayed on the current 15min K. From then on, each zigzag value will be corresponding to position index  MathFloor((i-GapK)/15)+1. For example position 6 will be on position 1 (on the current 15min chart), position 22 will be on position 2, etc

It works well in the most recent bars. Perhaps first 2000 bars. And then it starts to shift right, some of the positions are wrongly showed 1 bars, 2bars behind. Then it gets worse, 5 bars, 6 bars, and then totally mess. Anyone tell me what happened? I can't figure out why.

Thanks for any help!