//+------------------------------------------------------------------+
//|                                                  BB Macd nrp.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 5
#property indicator_color1  clrDimGray
#property indicator_color2  clrDimGray
#property indicator_color3  clrLimeGreen
#property indicator_color4  clrRed
#property indicator_color5  clrRed
#property indicator_width3  2
#property indicator_width4  2
#property indicator_width5  2

//
//
//
//
//
enum enTimeFrames
{
   tf_cu  = PERIOD_CURRENT, // Current time frame
   tf_m1  = PERIOD_M1,      // 1 minute
   tf_m5  = PERIOD_M5,      // 5 minutes
   tf_m15 = PERIOD_M15,     // 15 minutes
   tf_m30 = PERIOD_M30,     // 30 minutes
   tf_h1  = PERIOD_H1,      // 1 hour
   tf_h4  = PERIOD_H4,      // 4 hours
   tf_d1  = PERIOD_D1,      // Daily
   tf_w1  = PERIOD_W1,      // Weekly
   tf_mn1 = PERIOD_MN1,     // Monthly
   tf_n1  = -1,             // First higher time frame
   tf_n2  = -2,             // Second higher time frame
   tf_n3  = -3              // Third higher time frame
};
//
//


enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased   // Heiken ashi trend biased price
};

extern enTimeFrames    TimeFrame          = tf_cu;   // Time frame
extern string           ForSymbol            = "";
extern double           FastCycles           = 0.5;
extern int              FastFilter           = 1.0;
extern double           SlowCycles           = 1.0;
extern int              SlowFilter           = 1.0;
extern int              Length               = 10;
extern enPrices         Price                = pr_close; // Price to use 
extern double           ConfidenceLevel      = 95;
extern int              ConfidenceBandsShift = 0;
extern bool             arrowsVisible        = false;
extern bool             arrowsOnFirst        = false;
extern bool             arrowsShowBreakOut   = true;
extern bool             arrowsShowRetrace    = true;
extern string           arrowsIdentifier     = "cb macd arrows";
extern double           arrowsUpperGap       = 0.5;
extern double           arrowsLowerGap       = 0.5;
extern color            arrowsUpColor        = clrLimeGreen;
extern color            arrowsDnColor        = clrRed;
extern int              arrowsUpCode         = 241;
extern int              arrowsDnCode         = 242;
extern bool             alertsOn             = true;
extern bool             alertsOnCurrent      = false;
extern bool             alertsMessage        = true;
extern bool             alertsSound          = false;
extern bool             alertsNotify         = false;
extern bool             alertsEmail          = false;
extern string           soundFile            = "alert2.wav";
extern bool             Interpolate          = true;
extern bool             drawDots             = false;

//
//
//
//
//

double buffer1[];
double buffer2[];
double bbMacd[];
double buffer4[];
double buffer5[];
double buffer6[];
double trendSlope[];
double trendValue[];
double ConfidenceZ;
string indicatorFileName;
bool   returnBars;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0, buffer1);
   SetIndexBuffer(1, buffer2);
   SetIndexBuffer(2, bbMacd);
   SetIndexBuffer(3, buffer4);
   SetIndexBuffer(4, buffer5);
   SetIndexBuffer(5, buffer6);
   SetIndexBuffer(6, trendSlope);
   SetIndexBuffer(7, trendValue);
      if (drawDots) {
            SetIndexStyle(2, DRAW_ARROW); SetIndexArrow(2, 159);
            SetIndexStyle(3, DRAW_ARROW); SetIndexArrow(3, 159);
            SetIndexStyle(4, DRAW_NONE);
         }
      else
         {
            SetIndexStyle(2, DRAW_LINE);
            SetIndexStyle(3, DRAW_LINE);
            SetIndexStyle(4, DRAW_LINE);
         }
         
         ConfidenceLevel   = MathMax(MathMin(ConfidenceLevel,99.9999999999),0.0000000001);
         ConfidenceZ       = NormalCDFInverse((ConfidenceLevel+(100-ConfidenceLevel)/2.0)/100.0);
         indicatorFileName = WindowExpertName();
         returnBars        = TimeFrame==-99;
         TimeFrame         = (enTimeFrames)timeFrameValue(TimeFrame);
         
      //
      //
      //
      //
      //
         
   IndicatorDigits(5);
   if (ForSymbol=="") ForSymbol = Symbol();
   IndicatorShortName(ForSymbol+" "+timeFrameToString(TimeFrame)+" CBand PAMacd (" + DoubleToStr(FastCycles,2) + "," + DoubleToStr(SlowCycles,2) + "," + Length+")");
      SetIndexLabel(0, "Upperband");
      SetIndexLabel(1, "Lowerband");  
      SetIndexLabel(2, "BB Macd");
      SetIndexLabel(3, NULL);
      SetIndexLabel(4, NULL);
return(0);
}

int deinit()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double work[][2];

int start()
{
   int i,r,limit,counted_bars = IndicatorCounted();

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
       limit = MathMin(Bars - counted_bars,Bars-1);
       if (returnBars) { buffer1[0] = limit+1; return(0); }


   //
   //
   //
   //
   //

   if (ForSymbol == Symbol() && TimeFrame == Period()) 
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      if (!drawDots) if (trendSlope[limit]==-1) CleanPoint(limit,buffer4,buffer5);
      double alpha = 2.0 / (Length + 1.0);
      for(i = limit,r=Bars-i-1; i >= 0 ; i--,r++)
      {
         double price  = getPrice(Price,Open,Close,High,Low,i);
         double alphaf = 2.0 / (1.0 + iHilbertPhase(price,FastFilter,FastCycles,i,0));
         double alphas = 2.0 / (1.0 + iHilbertPhase(price,SlowFilter,SlowCycles,i,1));
   
            if (r<=1)
               {
                  work[r][0] = price;
                  work[r][1] = price;
                  continue;
               }
            
         work[r][0] = work[r-1][0]+alphaf*(price-work[r-1][0]);
         work[r][1] = work[r-1][1]+alphas*(price-work[r-1][1]);
         bbMacd[i]  = work[r][0]-work[r][1];
         
         //
         //
         //
         //
         //
         
         buffer6[i] = buffer6[i+1] + alpha*(bbMacd[i]-buffer6[i+1]);
         double dev = iDeviation(bbMacd,Length,buffer6[i+ConfidenceBandsShift],i+ConfidenceBandsShift);
         double me  = ConfidenceZ*dev/MathSqrt(Length);
         buffer1[i] = buffer6[i+ConfidenceBandsShift] + me; 
         buffer2[i] = buffer6[i+ConfidenceBandsShift] - me;
         buffer4[i] = EMPTY_VALUE;
         buffer5[i] = EMPTY_VALUE;
               
         //
         //
         //
         //
         //
               
         trendSlope[i] = trendSlope[i+1];
            if (bbMacd[i]>bbMacd[i+1]) trendSlope[i] =  1;
            if (bbMacd[i]<bbMacd[i+1]) trendSlope[i] = -1;
            if (trendSlope[i]==-1)
               if (drawDots)     buffer4[i] = bbMacd[i];
               else  PlotPoint(i,buffer4,buffer5,bbMacd);
         trendValue[i] = trendValue[i+1];
            if (bbMacd[i]>buffer1[i])                         trendValue[i] =  1;
            if (bbMacd[i]<buffer2[i])                         trendValue[i] = -1;
            if (bbMacd[i]<buffer1[i] && bbMacd[i]>buffer2[i]) trendValue[i] =  0;
            
            //
            //
            //
            //
            //
            
            if (arrowsVisible && ForSymbol==Symbol())
            {
               ObjectDelete(arrowsIdentifier+":"+Time[i]);
               if (trendValue[i]!=trendValue[i+1])
               {
                 if (arrowsShowBreakOut && trendValue[i] == 1)                        drawArrow(i,arrowsUpColor,arrowsUpCode,false);
                 if (arrowsShowBreakOut && trendValue[i] ==-1)                        drawArrow(i,arrowsDnColor,arrowsDnCode,true);
                 if (arrowsShowRetrace  && trendValue[i] == 0 && trendValue[i+1]== 1) drawArrow(i,arrowsDnColor,arrowsDnCode,true);
                 if (arrowsShowRetrace  && trendValue[i] == 0 && trendValue[i+1]==-1) drawArrow(i,arrowsUpColor,arrowsUpCode,false);
               }
            }
      }
      
     //
     //
     //
     //
     //
      
     if (alertsOn)
     {
        if (alertsOnCurrent)
            int whichBar = 0;
        else     whichBar = 1; 
        if (trendValue[whichBar] != trendValue[whichBar+1])
        {
          if (trendValue[whichBar] == 1)                               doAlert(whichBar,"up");
          if (trendValue[whichBar] ==-1)                               doAlert(whichBar,"down");
          if (trendValue[whichBar] == 0 && trendValue[whichBar+1]== 1) doAlert(whichBar,"back from up into zone");
          if (trendValue[whichBar] ==-0 && trendValue[whichBar+1]==-1) doAlert(whichBar,"back from down into zone");
        }         
     } 
     return(0);
   }      

   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(ForSymbol,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   if (!drawDots) if (trendSlope[limit]==-1) CleanPoint(limit,buffer4,buffer5);
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(ForSymbol,TimeFrame,Time[i]);
         buffer1[i]    = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,Length,Price,ConfidenceLevel,ConfidenceBandsShift,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,0,y);
         buffer2[i]    = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,Length,Price,ConfidenceLevel,ConfidenceBandsShift,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,1,y);
         bbMacd[i]     = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,Length,Price,ConfidenceLevel,ConfidenceBandsShift,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,2,y);
         trendSlope[i] = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",FastCycles,FastFilter,SlowCycles,SlowFilter,Length,Price,ConfidenceLevel,ConfidenceBandsShift,arrowsVisible,arrowsOnFirst,arrowsShowBreakOut,arrowsShowRetrace,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,6,y);
         buffer4[i]    = EMPTY_VALUE;
         buffer5[i]    = EMPTY_VALUE;
            
         if (drawDots && trendSlope[i]==-1) buffer4[i] = bbMacd[i];
            
         //
         //
         //
         //
         //
      
         if (!Interpolate || y==iBarShift(NULL,TimeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,TimeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(int k = 1; k < n; k++)
            {
               bbMacd[i+k]  = bbMacd[i]  + (bbMacd[i+n] -bbMacd[i])*k/n;
               buffer1[i+k] = buffer1[i] + (buffer1[i+n]-buffer1[i])*k/n;
               buffer2[i+k] = buffer2[i] + (buffer2[i+n]-buffer2[i])*k/n;
               if (buffer4[i+k] != EMPTY_VALUE) buffer4[i+k] = bbMacd[i+k];
            }               
   }
   if (!drawDots) for (i=limit;i>=0;i--) if (trendSlope[i]==-1) PlotPoint(i,buffer4,buffer5,bbMacd);
return(0);
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double iDeviation(double& array[], double period, double ma, int i, bool isSample=true)
{
   double sum = 0.00; for(int k=0; k<period; k++) sum += MathPow((array[i+k]-ma),2);
   if (isSample)      
         return(MathSqrt(sum/(period-1.0)));
   else  return(MathSqrt(sum/period));
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

double workHil[][18];
#define _price      0
#define _smooth     1
#define _detrender  2
#define _period     3
#define _instPeriod 4
#define _phase      5
#define _deltaPhase 6
#define _Q1         7
#define _I1         8

#define Pi 3.14159265358979323846264338327950288

//
//
//
//
//

double iHilbertPhase(double price, double filter, double cyclesToReach, int i, int s=0)
{
   if (ArrayRange(workHil,0)!=Bars) ArrayResize(workHil,Bars);
   int r = Bars-i-1; s = s*9;
      
   //
   //
   //
   //
   //
      
      workHil[r][s+_price]      = price;
      workHil[r][s+_smooth]     = (4.0*workHil[r][s+_price]+3.0*workHil[r-1][s+_price]+2.0*workHil[r-2][s+_price]+workHil[r-3][s+_price])/10.0;
      workHil[r][s+_detrender]  = calcComp(r,_smooth,s);
      workHil[r][s+_Q1]         = 0.15*calcComp(r,_detrender,s)  +0.85*workHil[r-1][s+_Q1];
      workHil[r][s+_I1]         = 0.15*workHil[r-3][s+_detrender]+0.85*workHil[r-1][s+_I1];
      workHil[r][s+_phase]      = workHil[r-1][s+_phase];
      workHil[r][s+_instPeriod] = workHil[r-1][s+_instPeriod];

      //
      //
      //
      //
      //
           
         if (MathAbs(workHil[r][s+_I1])>0)
                     workHil[r][s+_phase] = 180.0/Pi*MathArctan(MathAbs(workHil[r][s+_Q1]/workHil[r][s+_I1]));
           
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]>0) workHil[r][s+_phase] = 180.0-workHil[r][s+_phase];
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 180.0+workHil[r][s+_phase];
         if (workHil[r][s+_I1]>0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 360.0-workHil[r][s+_phase];

      //
      //
      //
      //
      //
                        
      workHil[r][s+_deltaPhase] = workHil[r-1][s+_phase]-workHil[r][s+_phase];

         if (workHil[r-1][s+_phase]<90.0 && workHil[r][s+_phase]>270.0)
             workHil[r][s+_deltaPhase] = 360.0+workHil[r-1][s+_phase]-workHil[r][s+_phase];
             workHil[r][s+_deltaPhase] = MathMax(MathMin(workHil[r][s+_deltaPhase],60),7);
      
            //
            //
            //
            //
            //
                  
            double alpha    = 2.0/(1.0+MathMax(filter,1));
            double phaseSum = 0; for (int k=0; phaseSum<cyclesToReach*360.0 && (r-k)>0; k++) phaseSum += workHil[r-k][s+_deltaPhase];
         
               if (k>0) workHil[r][s+_instPeriod]= k;
                  workHil[r][s+_period] = workHil[r-1][s+_period]+alpha*(workHil[r][s+_instPeriod]-workHil[r-1][s+_period]);
   return (workHil[r][s+_period]);
}

//
//
//
//
//

double calcComp(int r, int from, int s)
{
   return((0.0962*workHil[r  ][s+from] + 
           0.5769*workHil[r-2][s+from] - 
           0.5769*workHil[r-4][s+from] - 
           0.0962*workHil[r-6][s+from]) * (0.075*workHil[r-1][s+_period] + 0.54));
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

double workHa[][4];
double getPrice(int price, const double& open[], const double& close[], const double& high[], const double& low[], int i, int instanceNo=0)
{
  if (price>=pr_haclose && price<=pr_hatbiased)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars);
         int r = Bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen;
         if (r>0)
                haOpen  = (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0;
         else   haOpen  = (open[i]+close[i])/2;
         double haClose = (open[i] + high[i] + low[i] + close[i]) / 4.0;
         double haHigh  = MathMax(high[i], MathMax(haOpen,haClose));
         double haLow   = MathMin(low[i] , MathMin(haOpen,haClose));

         if(haOpen  <haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else                 { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                                workHa[r][instanceNo+2] = haOpen;
                                workHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (price)
         {
            case pr_haclose:     return(haClose);
            case pr_haopen:      return(haOpen);
            case pr_hahigh:      return(haHigh);
            case pr_halow:       return(haLow);
            case pr_hamedian:    return((haHigh+haLow)/2.0);
            case pr_hamedianb:   return((haOpen+haClose)/2.0);
            case pr_hatypical:   return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:  return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:   return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (price)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
   }
   return(0);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}
int timeFrameValue(int _tf)
{
   int add  = (_tf>=0) ? 0 : MathAbs(_tf);
   if (add != 0) _tf = _Period;
   int size = ArraySize(iTfTable); 
      int i =0; for (;i<size; i++) if (iTfTable[i]==_tf) break;
                                   if (i==size) return(_Period);
                                                return(iTfTable[(int)MathMin(i+add,size-1)]);
}
//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = 3.0*iATR(NULL,0,20,i)/4.0;   
   int    add  = 0; if (!arrowsOnFirst) add = _Period*60-1;
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i]+add,0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+ arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] - arrowsLowerGap * gap);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
      if (previousAlert != doWhat || previousTime != Time[forBar]) {
          previousAlert  = doWhat;
          previousTime   = Time[forBar];

          //
          //
          //
          //
          //

          message =  StringConcatenate(Symbol()," ",timeFrameToString(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," CB PAMacd ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," CB PAMacd "),message);
             if (alertsNotify)  SendNotification(message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i]   = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

//
//
//
//
//

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (first[i+1] == EMPTY_VALUE)
      {
         if (first[i+2] == EMPTY_VALUE) {
                first[i]   = from[i];
                first[i+1] = from[i+1];
                second[i]  = EMPTY_VALUE;
            }
         else {
                second[i]   =  from[i];
                second[i+1] =  from[i+1];
                first[i]    = EMPTY_VALUE;
            }
      }
   else
      {
         first[i]   = from[i];
         second[i]  = EMPTY_VALUE;
      }
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double RationalApproximation(double t)
{
    double c[] = {2.515517, 0.802853, 0.010328};
    double d[] = {1.432788, 0.189269, 0.001308};
    return (t - (( c[2]*t + c[1])*t + c[0]) / 
                (((d[2]*t + d[1])*t + d[0])*t + 1.0));
}

//
//
//
//
//

double NormalCDFInverse(double p)
{
    if (p <= 0.0 || p >= 1.0) return(0);
    if (p < 0.5)
           return (-RationalApproximation(MathSqrt(-2.0*MathLog(p))));
    else   return ( RationalApproximation(MathSqrt(-2.0*MathLog(1.0-p))));
}


