//
//  calcPerfClass.m
//  H135
//
//  Created by Claus Richter on 10/29/17.
//
//

#import "calcPerfClass.h"

#import "ViewController.h"

#import "calcPerfC172.h"

#define yellowSpecialColor [UIColor colorWithRed: 265.0/255.0 green: 216.0/255.0 blue: 0.0/255.0 alpha: 1.0] // this is yellow
#define verylightBlueColor [UIColor colorWithRed: 179.0/255.0 green: 202/255.0 blue: 238/255.0 alpha: 1.0] // this is dark gray

float resultGroundRoll = 0, engineRPMcruise = 0, resultWindDifferenceGR_TO = 0 , resultWindDifference50ft_TO = 0, resultWindDifferenceGR_LD = 0 , resultWindDifference50ft_LD = 0;
float resultDistanceOverObstacle = 0;
float resultClimbSpeed = 0, resultClimbTime= 0, resultClimbFuel= 0, resultClimbDistance= 0, resultClimbRoC= 0, resultCruiseKTAS = 0, resultCruiseFuelBurn = 0, resultCruiseBHP =0, resultRPMmin = 0, resultRPMmax = 0, ISAdiffExtern = 0 ;

float windDirectionTO = 0;
float windDirectionLD = 0;
float windSpeedTO = 0;
float windSpeedLD = 0;
float windSpeedClimb = 0;
float windSpeedCruise = 0;
float headwindcomponentTO = 0;
float headwindcomponentLD = 0;
int lockACweightOverrideTO = 1;
int lockACweightOverrideLD = 1;
float ACweightTO = 0;
float ACweightLD = 0;
float ACweightClimb = 0;
float ACweightCruise = 0;

float totalAirspeedPenalty= 0;
float totalFuelFlowPenalty= 0;
float totalRangePenalty = 0;

int allowFixedWingSliderSaving = 0;

@interface calcPerfClass (){
    
    calcPerfC172 *calcPerfC172Class_;
    
}

@end

@implementation calcPerfClass

#define colorSet [UIColor colorWithRed: 255.0/255.0 green: 0.0/255.0 blue: 0.0/255.0 alpha: 1.0] // this is red
#define colorSetOrange [UIColor colorWithRed: 255/255.0 green: 124/255.0 blue: 0/255.0 alpha: 1.0] // this is orange

//#define colorSet [UIColor colorWithRed: 255.0/255.0 green: 0.0/255.0 blue: 231/255.0 alpha: 1.0] // this is pink

// blue #define colorSet [UIColor colorWithRed: 0/255.0 green: 157/255.0 blue: 255/255.0 alpha: 1.0]


- (void) resetPreviousChartName {
    
    previousChartName = @"9999";
    
    chartImagesDictionary = [[NSMutableDictionary alloc] init];
    
}



- (void) transferMethod:  (float)receivedOAT  sendPA:(float)receivedPA  sendAltimeterUSA:(float)receivedAltimeterUSA sendHeadWindKts:(float)receivedHeadWindKts sendACweight:(float)receivedACweight sendACLandingweight:(float)receivedACLandingweight sendSelectedChartButton:(float)receivedSelectedChartButton   sendISADiff:(float)receivedISADiff   sendAltimeterInches:(float)receivedAltimeterInches sendPenaltyWeight:(float)receivedPenaltyWeight sendPenaltyFtMin:(float)receivedPenaltyFtMin sendFuelWeight:(float)receivedFuelWeight sendDA:(float)receivedDA sendACWeightUnit:(NSString*)receivedACWeightUnit sendIAS:(float)receivedIAS sendRatingIndex:(float)receivedRatingIndex sendPROPRPM:(float)receivedPROPRPM sendselectedUnitForItems:(NSString*)receivedSelectedUnitsForItems {
    
 
   
    
    IAS = receivedIAS;
    RATINGINDEX = receivedRatingIndex;
    PROPRPM = receivedPROPRPM;
    
    ACweightUnitsUsed = receivedACWeightUnit;
    
    selectedUnitsForItems = receivedSelectedUnitsForItems;
    fuelWeight = receivedFuelWeight;
    
    //NSLog(@"1 selectedUnitsForItems %@", selectedUnitsForItems);
    
    
    
    
    acWeight = receivedACweight ;
    acLandingWeight = receivedACLandingweight;
    unchangedACWeight = receivedACweight ;
    
    //NSLog(@"receivedSelectedUnitsForItems %@", receivedSelectedUnitsForItems);
    
   
    //NSLog(@"1 acLandingWeight %.0f", acLandingWeight);
    //NSLog(@"1 ACweightUnitsUsed %@", ACweightUnitsUsed);
    //NSLog(@"1 MTOWfromEnvelope %.0f", MTOWfromEnvelope);
    
        
    
    if (lockACweightOverrideTO == 1) {
        _sliderAircraftWeightOverrideTO.maximumValue = MTOWfromEnvelope;
        _sliderAircraftWeightOverrideTO.minimumValue = 0;
        _sliderAircraftWeightOverrideTO.value = acWeight;
        
        if ([ACweightUnitsUsed isEqualToString:@"lbs"] && [selectedUnitsForItems isEqualToString:@"kg"] ) {
            _sliderAircraftWeightOverrideTO.maximumValue = MTOWfromEnvelope  / 2.2046;
            _sliderAircraftWeightOverrideTO.minimumValue = 0;
            _sliderAircraftWeightOverrideTO.value = acWeight  / 2.2046;
        }
        
    }
    
    
    if (lockACweightOverrideLD == 1) {
        
        _sliderAircraftWeightOverrideLD.maximumValue = MTOWfromEnvelope;
        _sliderAircraftWeightOverrideLD.minimumValue = 0;
        _sliderAircraftWeightOverrideLD.value = acLandingWeight;
        
        if ([ACweightUnitsUsed isEqualToString:@"lbs"] && [selectedUnitsForItems isEqualToString:@"kg"] ) {
            _sliderAircraftWeightOverrideLD.maximumValue = MTOWfromEnvelope  / 2.2046;
            _sliderAircraftWeightOverrideLD.minimumValue = 0;
            _sliderAircraftWeightOverrideLD.value = acLandingWeight  / 2.2046;
        }
        
    }
    
     if (lockACweightOverrideTO == 0) {
         acWeight = _sliderAircraftWeightOverrideTO.value;
         unchangedACWeight = acWeight;
         //NSLog(@"1override %.0f", acWeight);
     }
    
    if (lockACweightOverrideLD == 0) {
        acLandingWeight = _sliderAircraftWeightOverrideLD.value;
         //NSLog(@"2override %.0f", acLandingWeight);
    }
    
    
   
    
    
    DensityAlt = receivedDA;
    penaltyFtMin = receivedPenaltyFtMin;
    penaltyWeight = receivedPenaltyWeight;
    headWindKTS = receivedHeadWindKts;
    //NSLog(@"headWindKTS %.0f", headWindKTS);
    OAT = receivedOAT;
    Hp = receivedPA;
    //NSLog(@"receivedPA  %.2f", receivedPA);
    //NSLog(@"receivedAltimeterUSA  %.2f", receivedAltimeterUSA);
    
    selectedChartButton = receivedSelectedChartButton;
    ISADiff = receivedISADiff;
    ISAdiffExtern = receivedISADiff;
    
    altimeterInches = receivedAltimeterInches;
    
    //NSLog(@"receivedAltimeterInches %.1f ", receivedAltimeterInches );
    
    [self calcPerformance];
    
    //[self makeOverviewPages];
    
}




- (void)drawRect:(CGRect)rect {
    /* Set UIView Border */
    /*
     // Get the contextRef
     CGContextRef contextRef = UIGraphicsGetCurrentContext();
     
     // Set the border width
     CGContextSetLineWidth(contextRef, 5.0);
     
     // Set the border color to RED
     CGContextSetRGBStrokeColor(contextRef, 255.0, 0.0, 0.0, 1.0);
     
     // Draw the border along the view edge
     CGContextStrokeRect(contextRef, rect);
     */
    
    /* Draw a circle */
    // Get the contextRef
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    // Set the border width
    CGContextSetLineWidth(contextRef, 1.0);
    
    // Set the circle fill color to GREEN
    CGContextSetRGBFillColor(contextRef, 0.0, 255.0, 0.0, 1.0);
    
    // Set the cicle border color to BLUE
    CGContextSetRGBStrokeColor(contextRef, 0.0, 0.0, 255.0, 1.0);
    
    // Fill the circle with the fill color
    CGContextFillEllipseInRect(contextRef, rect);
    
    // Draw the circle border
    CGContextStrokeEllipseInRect(contextRef, rect);
}


- (void) hideAllViews {
    
    _viewPC2OverviewAS365.hidden = YES;
    _viewCATAOverview1.hidden = YES;
    _viewCATAOverview2.hidden = YES;
    _viewCATAOverview3.hidden = YES;  
    _viewPowerCheck.hidden = YES;
    _viewPowerCheck2.hidden = YES;
    _viewTakeoff.hidden = YES;
    _viewClimb.hidden = YES;
    _viewCruise.hidden = YES;
    _viewLanding.hidden = YES;
    _viewSummary.hidden = YES;
    _viewR44Manifold.hidden = YES;
    _viewR44VNE.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_sliderEngineTorque1 setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderITT1 setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderITT2 setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderEngineTorque2 setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderRundwayHeadingTO setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderRunwayLength setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderRunwayLengthLD setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderAircraftWeightOverrideTO setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderRunwayConditionsTO setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderSlopeTO setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderAircraftWeightOverrideLD setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderClimbEnd setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderRundwayHeadingLD setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderRunwayConditionsLD setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderSlopeLD setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderEngineRPMcruise setMaximumTrackTintColor:[UIColor darkGrayColor]];
    [_sliderTripDistanceNM setMaximumTrackTintColor:[UIColor darkGrayColor]];
   
   
    
    
    //calcPerfC172 *_calcPerfC172= [[calcPerfC172 alloc]init];
    //[_calcPerfC172 takeoff_DA40180];
    //[_calcPerfC172 landing_DA40180];
    
    // Do any additional setup after loading the view from its nib.
    
    _viewR44ManifoldChart.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.7, 0.7);
    
    _viewTORunway.frame = CGRectMake(-220, 55, 570, 172);
    _sliderAircraftWeightOverrideTO.enabled = NO;
    
    _viewLDRunway.frame = CGRectMake(-220, 55, 570, 172);
    _sliderAircraftWeightOverrideLD.enabled = NO;
    
    frwyIncrement =  100;
    
    float scale = 1.0 ;
    unitResult = @"-";
    
    conversionFeetToMeter = 1;
    incrementRunwayLength = 100;
    initialRunwayFrameWidth = _symRunway.frame.size.width;
    
    
    CGAffineTransform scaleValue  = CGAffineTransformMakeScale(1, scale);
    CGAffineTransform rotateValue = CGAffineTransformMakeRotation(-12 * M_PI / 180.0);
    
    
    rotateValue = CGAffineTransformMakeRotation(-7 * M_PI / 180.0);
    _symAC1.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // ac in center = the taking off from runway
    
    rotateValue = CGAffineTransformMakeRotation(-14 * M_PI / 180.0);
    _symAC2.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // ac in center = the taking off from runway
    
    rotateValue = CGAffineTransformMakeRotation(5 * M_PI / 180.0);
    _symAC0LD.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // scale and rotate
    
    rotateValue = CGAffineTransformMakeRotation(-3 * M_PI / 180.0);
    _symAC1LD.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // scale and rotate
    
    rotateValue = CGAffineTransformMakeRotation(-7 * M_PI / 180.0);
    _symACClimb1.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // climbing
    
    rotateValue = CGAffineTransformMakeRotation(-7 * M_PI / 180.0);
    _symACClimb2.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // climbing
    
    
    scaleValue  = CGAffineTransformMakeScale(1, 0.5);
    rotateValue = CGAffineTransformMakeRotation(0* M_PI / 180.0);
    
    _viewWindCircle.layer.anchorPoint = CGPointMake(0.5, 0.5);
    _viewWindCircle.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // scale and rotate
    _viewWindCircleLD.layer.anchorPoint = CGPointMake(0.5, 0.5);
    _viewWindCircleLD.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // scale and rotate
    
    
    scaleValue  = CGAffineTransformMakeScale(1, 1);
    rotateValue = CGAffineTransformMakeRotation(0* M_PI / 180.0);
    
    //_symWindCircle.layer.anchorPoint = CGPointMake(0.5, 0.5);
    //_symWindCircle.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // scale and rotate
    
    _symWindCircleLD.layer.anchorPoint = CGPointMake(0.5, 0.5);
    _symWindCircleLD.transform = CGAffineTransformConcat(scaleValue, rotateValue);  // scale and rotate
    
    
    
     [self hideAllViews];
    
   
    
    float crossSize = 50;
    float dotSize = 40;
    
    float dotLineWidth = 3.0;
    
    _viewVTOL.hidden = YES; _viewCATACH.hidden = NO;
    
    // make cross views
    
    
    viewCross1 = [[UIView alloc] initWithFrame: CGRectMake ( 300, 50, crossSize, crossSize)];
    [_viewChartsUniversal addSubview:viewCross1];
    //viewCross1.backgroundColor =[UIColor yellowColor];
    
    viewCross2 = [[UIView alloc] initWithFrame: CGRectMake ( 300, 150, crossSize, crossSize)];
    [_viewChartsUniversal addSubview:viewCross2];
    //viewCross2.backgroundColor = [UIColor yellowColor];
    
    viewCross3 = [[UIView alloc] initWithFrame: CGRectMake ( 300, 250, crossSize, crossSize)];
    [_viewChartsUniversal addSubview:viewCross3];
    //viewCross3.backgroundColor = [UIColor yellowColor];
    
    viewCross4 = [[UIView alloc] initWithFrame: CGRectMake ( 300, 350, crossSize, crossSize)];
    [_viewChartsUniversal addSubview:viewCross4];
    
    viewCross5 = [[UIView alloc] initWithFrame: CGRectMake ( 300, 350, crossSize, crossSize)];
    [_viewChartsUniversal addSubview:viewCross5];
    
  
    
    
    circleLayer = [CAShapeLayer layer];
    [circleLayer setBounds:CGRectMake(0.0f, 0.0f, crossSize , crossSize )];
    [circleLayer setPosition:CGPointMake( crossSize/2, crossSize/2)];
    
    // Create a circle path.
    pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake((crossSize/2) - (dotSize/2), (crossSize/2) - (dotSize/2), dotSize, dotSize)]; // xPos,yPos width, height
    [circleLayer setPath:[pathC CGPath]];
    [circleLayer setStrokeColor:[ colorSet CGColor]  ];
    [circleLayer setFillColor:[[UIColor clearColor] CGColor]];
    [circleLayer setLineWidth:dotLineWidth];
    [viewCross1.layer addSublayer:circleLayer];
    
 
    CAShapeLayer *circleLayer2 = [CAShapeLayer layer];
    [circleLayer2 setBounds:CGRectMake(0.0f, 0.0f, crossSize , crossSize )];
    [circleLayer2 setPosition:CGPointMake( crossSize/2, crossSize/2)];
    pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake((crossSize/2) - (dotSize/2), (crossSize/2) - (dotSize/2), dotSize, dotSize)]; // xPos,yPos width, height
    [circleLayer2 setPath:[pathC CGPath]];
    [circleLayer2 setStrokeColor:[ colorSet CGColor]  ];
    [circleLayer2 setFillColor:[[UIColor clearColor] CGColor]];
    [circleLayer2 setLineWidth:dotLineWidth];
    [viewCross2.layer addSublayer:circleLayer2];
 
   
    
    CAShapeLayer *circleLayer3 = [CAShapeLayer layer];
    [circleLayer3 setBounds:CGRectMake(0.0f, 0.0f, crossSize , crossSize )];
    [circleLayer3 setPosition:CGPointMake( crossSize/2, crossSize/2)];
    pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake((crossSize/2) - (dotSize/2), (crossSize/2) - (dotSize/2), dotSize, dotSize)]; // xPos,yPos width, height
    [circleLayer3 setPath:[pathC CGPath]];
    [circleLayer3 setStrokeColor:[ colorSet CGColor]  ];
    [circleLayer3 setFillColor:[[UIColor clearColor] CGColor]];
    [circleLayer3 setLineWidth:dotLineWidth];
    [viewCross3.layer addSublayer:circleLayer3];
    
    
    
    CAShapeLayer *circleLayer4 = [CAShapeLayer layer];
    [circleLayer4 setBounds:CGRectMake(0.0f, 0.0f, crossSize , crossSize )];
    [circleLayer4 setPosition:CGPointMake( crossSize/2, crossSize/2)];
    pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake((crossSize/2) - (dotSize/2), (crossSize/2) - (dotSize/2), dotSize, dotSize)]; // xPos,yPos width, height
    [circleLayer4 setPath:[pathC CGPath]];
    [circleLayer4 setStrokeColor:[ colorSet CGColor]  ];
    [circleLayer4 setFillColor:[[UIColor clearColor] CGColor]];
    [circleLayer4 setLineWidth:dotLineWidth];
    [viewCross4.layer addSublayer:circleLayer4];
    
    CAShapeLayer *circleLayer5 = [CAShapeLayer layer];
    [circleLayer5 setBounds:CGRectMake(0.0f, 0.0f, crossSize , crossSize )];
    [circleLayer5 setPosition:CGPointMake( crossSize/2, crossSize/2)];
    pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake((crossSize/2) - (dotSize/2), (crossSize/2) - (dotSize/2), dotSize, dotSize)]; // xPos,yPos width, height
    [circleLayer5 setPath:[pathC CGPath]];
    [circleLayer5 setStrokeColor:[ colorSet CGColor]  ];
    [circleLayer5 setFillColor:[[UIColor clearColor] CGColor]];
    [circleLayer5 setLineWidth:dotLineWidth];
    [viewCross5.layer addSublayer:circleLayer5];
    
    
    
   
    
    UIPinchGestureRecognizer *twoFingerPinch = [[UIPinchGestureRecognizer alloc]
                                                initWithTarget:self
                                                action:@selector(twoFingerPinch:)]
    ;
    
    [[self masterViewCharts] addGestureRecognizer:twoFingerPinch];
    
    
    
    
    
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc]
                                             initWithTarget:self
                                             action:@selector(panRecognizer:)]
    ;
    
    [[self viewChartContainer] addGestureRecognizer:panRecognizer];
    
    
    
    UITapGestureRecognizer *singleTapRecognizer = [[UITapGestureRecognizer alloc]
                                                   initWithTarget: self
                                                   action:@selector(handleSingleTapOnView:)];
    
    [singleTapRecognizer setNumberOfTouchesRequired:1];
    [[self masterViewCharts] addGestureRecognizer: singleTapRecognizer];
  

    
    
    //NSLog(@"viewDidLoad calcPerfClass");
    
    moveupDown = 0, moveLeftRight = 0, pinchScale = 1, pinchScaleEnded = 1;
    fullScreenPerfCharts = 0;
    
    transferValueDictionary = [[NSMutableDictionary alloc] init];
  
    resultsAllChartNames = [[NSMutableArray alloc] init];
    resultsAllChartUserNames= [[NSMutableArray alloc] init];
    resultsAllChartValues = [[NSMutableArray alloc] init];
    resultsAllUnits = [[NSMutableArray alloc] init];
    resultsAllDataOutOfRange = [[NSMutableArray alloc] init];
    resultsAllPrintOnManifest = [[NSMutableArray alloc] init];
    resultsAllEnviSettings = [[NSMutableArray alloc] init];
    
    
    // load basics
    
    serverUrl  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"serverUrl"];
    ACCategory  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"ACCategory"];
    ACmanufacturer  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"ACmanufacturer"];
    AC_Type  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"AC_Type"];
    ACVariant  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"ACVariant"];

    chartImagesDictionary = [[NSMutableDictionary alloc] init];
    
    [self calcPerformance];    
    
    acWeight = 2500;    
    headWindKTS = 0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)closeKeyboardPowerCheck:(id)sender {
    
    
    [self.view endEditing:TRUE];
    
    _sliderITT1.value = [_inputITT1.text floatValue];
    _sliderITT2.value = [_inputITT2.text floatValue];
    
    _sliderEngineTorque1.value = [_inputEngineTorque1.text floatValue];
    _sliderEngineTorque2.value = [_inputEngineTorque2.text floatValue];
    
    [self calcPerformance];
}

- (IBAction)closeKeyboardCruise:(id)sender {
    
    
    [self.view endEditing:TRUE];
    
    [self calcPerformance];
    [self calcPerformance];
}



- (void) computeTakeoff_UniversalWithFixedData {
    
    // wind rule: decrease distances 10% for each 9 knot headwind
    // tailwind up to 10 kts: increase distances by 10% for each 2 knots
    
   
    windDirectionTO = IAS;
    
    unitDistance = @"ft";
    if (_segmentMeterFeet.selectedSegmentIndex == 0) {
        conversionFeetToMeter = 1;
    }else{
        conversionFeetToMeter = 0.3048;
        unitDistance = @"m";
    }
    
    
    //**************************************************
    //Ground Roll
    //**************************************************
    
    headwindcomponentTO = headWindKTS * cos (  ( windDirectionTO -  _sliderRundwayHeadingTO.value) * 0.01745);
    windSpeedTO = headWindKTS;
    
    originalGroundRoll = 0;
    penaltyWindGR = 0;
    penaltyRunwayConditionsGR = 0;
    penaltySlopeGR = 0;
    totalGroundRoll = 0;
    
    originalGroundRoll = resultGroundRoll;
    float factorRWYconditions = 1 + (_sliderRunwayConditionsTO.value/100);
    penaltyRunwayConditionsGR = (resultGroundRoll * factorRWYconditions) - resultGroundRoll;
    
    //NSLog(@"resultGroundRoll %.0f", resultGroundRoll);
    //NSLog(@"factorRWYconditions %.0f", factorRWYconditions);
    //NSLog(@"penaltyRunwayConditionsGR %.0f", penaltyRunwayConditionsGR);
    //NSLog(@"originalGroundRoll %.0f", originalGroundRoll);
    
    penaltyWindGR = -1 * ((headwindcomponentTO / 9) * (originalGroundRoll*0.1));
    if ([compString rangeOfString:@"PA28"].location != NSNotFound || [compString rangeOfString:@"DA40-180"].location != NSNotFound  ) {        
        penaltyWindGR = resultWindDifferenceGR_TO;
    }
    
    penaltySlopeGR = originalGroundRoll *  (_sliderSlopeTO.value /100);
    totalGroundRoll = originalGroundRoll + penaltyWindGR + penaltyRunwayConditionsGR + penaltySlopeGR;
    
   
    
    //**************************************************
    //Distance over 50ft
    //**************************************************
    
    originalDistance50ft = 0;
    penaltyWind50ft = 0;
    penaltyRunwayConditions50ft = 0;
    penaltySlope50ft = 0;
    totalDistance50ft = 0;
    
    originalDistance50ft = resultDistanceOverObstacle;
    penaltyRunwayConditions50ft = penaltyRunwayConditionsGR;
    
    penaltyWind50ft = -1 * ((headwindcomponentTO / 9) * (originalDistance50ft*0.1));
    if ([compString rangeOfString:@"PA28"].location != NSNotFound  || [compString rangeOfString:@"DA40-180"].location != NSNotFound  ) {        
        penaltyWind50ft = resultWindDifference50ft_TO;
    }
    penaltySlope50ft = originalDistance50ft *  (_sliderSlopeTO.value /100);
    totalDistance50ft = originalDistance50ft + penaltyWind50ft + penaltyRunwayConditions50ft + penaltySlope50ft;
    
   
    
}


- (void) createGraphicsClimb {
    
    
    _viewForClimbAnimations.frame = CGRectMake(_viewForClimbGrid.frame.origin.x, _viewForClimbGrid.frame.origin.y, _viewForClimbGrid.frame.size.width, _viewForClimbGrid.frame.size.height);
    
    //NSLog(@"createGraphicsClimb");
    int maxElevation = maxPAforThisComputation + 2000;
    climbYaxisEnd = maxElevation;
    int stepPA = 1000;
    if (maxPAforThisComputation >= 12000) {
        stepPA = 2000;
    }    
    int ySteps = climbYaxisEnd / stepPA;
    
   
    float yPixelDiff =  ( _viewForClimbGrid.frame.size.height / climbYaxisEnd) * (climbYaxisEnd /ySteps);    
    [_viewForClimbGrid.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    
    
    // frame
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake( 0, 0 )];
    [path addLineToPoint:CGPointMake( _viewForClimbGrid.frame.size.width, 0 )  ];
    [path addLineToPoint:CGPointMake( _viewForClimbGrid.frame.size.width, _viewForClimbGrid.frame.size.height)];
    [path addLineToPoint:CGPointMake( 0, _viewForClimbGrid.frame.size.height)  ];
    [path addLineToPoint:CGPointMake( 0, 0)  ];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];
    shapeLayer.lineWidth = 3.0;
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    [_viewForClimbGrid.layer addSublayer:shapeLayer];
    
    // y lines
    for (int i = 0; i < ySteps+1 ; i++) {        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( 0, 0 + (i * yPixelDiff) )];
        [path addLineToPoint:CGPointMake( _viewForClimbGrid.frame.size.width, (i * yPixelDiff) )];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];
        shapeLayer.lineWidth = 1.0;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [_viewForClimbGrid.layer addSublayer:shapeLayer]; 
        
        if (i == 0) {
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake( -86, (i * yPixelDiff) - 5 , 80, 20)];
            label.textAlignment = NSTextAlignmentRight;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText =  @"feet PA";
            if (_segmentMeterFeetClimb.selectedSegmentIndex == 1) {
                labelText =  @"meter PA"; 
            }
            
            [label  setText: labelText  ];
            [_viewForClimbGrid addSubview: label];
        }else{
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake( -86, (i * yPixelDiff) -10, 80, 20)];
            label.textAlignment = NSTextAlignmentRight;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText;
            if (((maxElevation/1000) - i) < 1) {
                labelText =  @"0";
            }else{
                labelText =  [[NSString alloc] initWithFormat:@"%d,000", (maxElevation/1000) - (i*stepPA/1000) ]; 
                if (_segmentMeterFeetClimb.selectedSegmentIndex == 1) {
                    labelText =  [[NSString alloc] initWithFormat:@"%.0f", ((maxElevation/1000) - i) * 0.3048  * 1000]; 
                }
            }           
            [label  setText: labelText  ];
            [_viewForClimbGrid addSubview: label];
            
        }
        
        
        
    }
    
    // x lines
    int xSteps = maxClimbDistanceForGraph / maxClimbDistanceSteps;
    climbXaxisEnd = maxClimbDistanceForGraph;
    if (isnan(xSteps)) {
        xSteps = 1;
    }
    if (isnan(maxClimbDistanceForGraph)) {
        maxClimbDistanceForGraph = 1;
    }
    
    //NSLog(@"maxClimbDistanceForGraph %.0f", maxClimbDistanceForGraph);
    
    //NSLog(@"xSteps %d", xSteps);
    
    float xPixelDiff =  ( _viewForClimbGrid.frame.size.width / climbXaxisEnd) * (climbXaxisEnd /xSteps);
    
    for (int i = 0; i < xSteps+1 ; i++) {        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(  (i * xPixelDiff), 0 )];
        [path addLineToPoint:CGPointMake(  (i * xPixelDiff), _viewForClimbGrid.frame.size.height ) ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];
        shapeLayer.lineWidth = 1.0;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [_viewForClimbGrid.layer addSublayer:shapeLayer];
        
        if (i == 0) {
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(  (i * xPixelDiff) , _viewForClimbGrid.frame.size.height +1  , 80, 20)];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText =  @"NM";
            if (_segmentMeterFeetClimb.selectedSegmentIndex == 1) {
                labelText =  @"km";
            }
            [label  setText: labelText  ];
            [_viewForClimbGrid addSubview: label];
        }else{
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(  (i * xPixelDiff) - 40 , _viewForClimbGrid.frame.size.height +1  , 80, 20)];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText;
            if (((maxElevation/1000) - i) < 1) {
                labelText =  @"0";
            }else{
                labelText =  [[NSString alloc] initWithFormat:@"%.0f", i*maxClimbDistanceSteps ]; 
                if (_segmentMeterFeetClimb.selectedSegmentIndex == 1) {
                    labelText =  [[NSString alloc] initWithFormat:@"%.1f", i*maxClimbDistanceSteps * 1.852]; 
                }
            }           
            [label  setText: labelText  ];
            [_viewForClimbGrid addSubview: label];            
        }
    }
   
    
   
    
    
}



- (void) computeCruiseUniversal  {
    
    //NSLog(@"computeCruiseUniversal Hp = %.0f", Hp);
     
    //NSLog(@"--------------"); 
    //NSLog(@"computeCruiseUniversal AC_Type %@", AC_Type);
        
    ViewController *parent = (ViewController *)self.parentViewController;
      if (parent.arrayName21.count < 2) {
          return;     
      }    
    
    _viewCruiseOverride.hidden = YES;
    
   if (![calcMode isEqualToString:@"plan"]) {        
       _viewCruiseDescentInfo.hidden = YES;       
       _viewCruiseTripInfo.hidden = YES;
   }else{
       _viewCruiseDescentInfo.hidden = NO;       
       _viewCruiseTripInfo.hidden = NO;
       
   }
    
    minPAforThisComputation = 0;    
    if (_viewCruiseGrid.layer.sublayers.count < 1) {
         cruiseRangeWindowNM = CruiseMaxDistance;
        [self createGraphicsCruise];
    }
    
     previousCruiseRangeWindowNM = cruiseRangeWindowNM;
    
    _sliderTripDistanceNM.minimumValue = 0;
    _sliderTripDistanceNM.maximumValue = 1000;
    _labelTripDistanceNM.text =  [[NSString alloc] initWithFormat:@"%.0f NM", _sliderTripDistanceNM.value ]; 
    
    flagClimbEndMustBeHigherThanElevation = 0; 
    
  
    calcPerfC172 *_calcPerfC172= [[calcPerfC172 alloc]init];
        
    
    NSString *originalFuelUnits =  [parent.arrayName21 objectAtIndex:15];
    //NSLog(@"originalFuelUnits %@", originalFuelUnits);   
    
    
    
    float windComponentCruise = headWindKTS ;
    _viewSliderEngineRPM.hidden = YES; 
    _viewCruisePowerSegment.hidden = YES;
    
    if (windComponentCruise >1) {
        _labelWindComponentCruise.text = @"Headwind";
        _labelWindSpeedCruise.text =  [[NSString alloc] initWithFormat:@"%.0f KTS", windComponentCruise ]; 
    }else if (windComponentCruise <-11) {
        _labelWindComponentCruise.text = @"Tailwind";
        _labelWindSpeedCruise.text =  [[NSString alloc] initWithFormat:@"%.0f KTS", windComponentCruise * -1 ]; 
    }else{
         _labelWindComponentCruise.text = @"Wind";
        _labelWindSpeedCruise.text = @"0 KTS";
    }

    flagGettingFuelFromInputField = 1;
    
    _viewCruiseOverride.hidden = YES;
    
    
    if (arrayFixedWingSetup.count > 2) {
        
        _viewCruiseOverride.hidden = NO;
        _viewSliderEngineRPM.hidden = YES; 
        _viewCruisePowerSegment.hidden = YES;
         resultCruiseKTAS = [_cruiseInputTAS.text floatValue];        
         resultCruiseFuelBurn = [_cruiseInputFuelFlow.text floatValue];        
        _switchOverrideCruiseInput.on = YES;
        _switchOverrideCruiseInput.enabled = NO;   
        
        if ([[arrayFixedWingSetup objectAtIndex:8] isEqualToString:@"yes"]) {
            [self computeCruiseTableSR22];
            _switchOverrideCruiseInput.enabled = YES;
        }
        
    }else{
        if ([ AC_Type  rangeOfString:@"DA42"].location != NSNotFound     ) {
            _viewCruiseOverride.hidden = NO;
            _viewSliderEngineRPM.hidden = YES; 
            _viewCruisePowerSegment.hidden = YES;
            resultCruiseKTAS = [_cruiseInputTAS.text floatValue];        
            resultCruiseFuelBurn = [_cruiseInputFuelFlow.text floatValue];        
          _switchOverrideCruiseInput.on = YES;
          _switchOverrideCruiseInput.enabled = NO;        
            
        } else if ([ AC_Type  rangeOfString:@"SR22"].location != NSNotFound      ) {
            
            if ([ AC_Type  rangeOfString:@"SR22TG6"].location != NSNotFound      ) {           
                [self computeCruiseTableSR22];
                _switchOverrideCruiseInput.enabled = YES;                   
            }else{
                _switchOverrideCruiseInput.on = YES;
                _switchOverrideCruiseInput.enabled = NO;            
            }
            _viewCruiseOverride.hidden = NO;
            _viewSliderEngineRPM.hidden = YES;
            _viewCruisePowerSegment.hidden = NO; [_viewCruise bringSubviewToFront:_viewCruisePowerSegment];
            
            
            
            resultCruiseKTAS = [_cruiseInputTAS.text floatValue];        
            resultCruiseFuelBurn = [_cruiseInputFuelFlow.text floatValue];
            
        }else if ([ AC_Type  rangeOfString:@"P2010"].location != NSNotFound   || [ AC_Type  rangeOfString:@"P2008"].location != NSNotFound  || [ AC_Type  rangeOfString:@"P2006"].location != NSNotFound    ) {
            
            _viewCruiseOverride.hidden = NO;
            _viewSliderEngineRPM.hidden = YES; 
            _viewCruisePowerSegment.hidden = YES;
            resultCruiseKTAS = [_cruiseInputTAS.text floatValue];        
            resultCruiseFuelBurn = [_cruiseInputFuelFlow.text floatValue];
            _switchOverrideCruiseInput.on = YES;
            _switchOverrideCruiseInput.enabled = NO;
            //adjust
            
        }else{  
            
            flagGettingFuelFromInputField = 0;        
            _viewSliderEngineRPM.hidden = NO; 
            engineRPMcruise = _sliderEngineRPMcruise.value;
            [_calcPerfC172 fwValueTransfer:OAT sendPA:Hp  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:0 sendACType:AC_Type sendComputation:compString];    
            _labelCruiseRPMmin.text =  [[NSString alloc] initWithFormat:@"min: %.0f", resultRPMmin ];
            _labelCruiseRPMmax.text =  [[NSString alloc] initWithFormat:@"max: %.0f", resultRPMmax ];
            _sliderEngineRPMcruise.minimumValue = resultRPMmin;
            _sliderEngineRPMcruise.maximumValue = resultRPMmax;
            // this is doppelt to set the slider RPMrange!!
            //NSLog(@"----");
            //NSLog(@"engineRPMcruise %.0f", engineRPMcruise);
            //NSLog(@"compString %@", compString);
            engineRPMcruise = _sliderEngineRPMcruise.value;    
            [_calcPerfC172 fwValueTransfer:OAT sendPA:Hp  sendISAdiff:ISADiff  sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:0 sendACType:AC_Type sendComputation:compString];        
            _labelEngineRPMcruise.text =  [[NSString alloc] initWithFormat:@"%.0f", _sliderEngineRPMcruise.value ];    
            _iCruiseSpeed.text =  [[NSString alloc] initWithFormat:@"%.0f kt", resultCruiseKTAS ];  
            _iCruiseBHP.text =  [[NSString alloc] initWithFormat:@"%.0f %%", resultCruiseBHP ];
            _iCruisePressureAlt.text =  [[NSString alloc] initWithFormat:@"%.0f'", Hp ];
                    
        }
        
    }
        
        
    
    
    
    
    
    
    
    
    
    if (_switchOverrideCruiseInput.on == YES) {
        //NSLog(@"_switchOverrideCruiseInput ON!!!!");
        _viewSliderEngineRPM.hidden = YES;
        _viewCruisePowerSegment.hidden = YES;
        
    }
    float usableFuelOnBoard = 0;
    
    //NSLog(@"-----");
    //NSLog(@"fuelOnBoardKg %.1f", fuelOnBoardKg);
    //NSLog(@"specificFuelDensityValue %.1f", specificFuelDensityValue);    
    //NSLog(@"fuelEnterMode %@", fuelEnterMode);    
    
    //NSLog(@"computed resultCruiseFuelBurn %.1f", resultCruiseFuelBurn);
    
    //NSLog(@"originalFuelUnits %@", originalFuelUnits);
    
    
    
    if ([ AC_Type  rangeOfString:@"DA40-180"].location != NSNotFound      ) {                
         resultCruiseFuelBurn = resultCruiseFuelBurn * 3.7854;                 
    }
    
     //NSLog(@"used resultCruiseFuelBurn %.1f", resultCruiseFuelBurn);
    
    NSString *fuelUnitText;
    
    if ([fuelEnterMode isEqualToString:@"volume"]) { 

        //NSLog(@"volume  selectedUnitForFuel %@", selectedUnitForFuel);
        
        //fuelOnBoardKg is mass, we need to convert to volume
        usableFuelOnBoard = fuelOnBoardKg / specificFuelDensityValue; // this smust match the desired unit          
        if ([selectedUnitForFuel isEqualToString:@"lbs"] ) {
            //NSLog(@"1 we want Gallons");
            // this is VOLUME in GALLONS
            _labelFuelFlowCruisePage.text = @"Fuel Flow [Gal/h]";  
            fuelUnitText = @"Gal";   
            if ([originalFuelUnits isEqualToString:@"kg"] ) {  
                //convert fuel on board from liter to gallons
                usableFuelOnBoard = usableFuelOnBoard / 3.785;
                if (flagGettingFuelFromInputField == 0) {
                   resultCruiseFuelBurn = resultCruiseFuelBurn / 3.785; 
                }
                
            }
        }
        
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
             //NSLog(@"2 we want liter");
            // this is VOLUME in LITER
           _labelFuelFlowCruisePage.text = @"Fuel Flow [ltr/h]";
            fuelUnitText = @"ltr"; 
            if ([originalFuelUnits isEqualToString:@"lbs"] ) {  
                //NSLog(@"but we need to convert gallons to liter");
                //convert fuel on board from Gallons to liter
                usableFuelOnBoard = usableFuelOnBoard * 3.785;
                 if (flagGettingFuelFromInputField == 0) {
                    resultCruiseFuelBurn = resultCruiseFuelBurn * 3.785; 
                 }
                
                
            }
           
        }    
        
        //NSLog(@"1 resultCruiseFuelBurn %.1f", resultCruiseFuelBurn);
        
    }else{  
        usableFuelOnBoard = fuelOnBoardKg ;
        //NSLog(@"mass  selectedUnitForFuel %@", selectedUnitForFuel);
        
        if ([selectedUnitForFuel isEqualToString:@"lbs"] ) {
             //NSLog(@"3 we want lbs");
            _labelFuelFlowCruisePage.text = @"Fuel Flow [lbs/h]";   
            fuelUnitText = @"lbs";
            if ([originalFuelUnits isEqualToString:@"kg"] ) {  
                //convert fuel on board from kg to lbs
                usableFuelOnBoard = usableFuelOnBoard * 2.2046;
                if (flagGettingFuelFromInputField == 0) {
                   resultCruiseFuelBurn = resultCruiseFuelBurn * 2.2046; 
                }
                
            }
            
            
        }
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
             //NSLog(@"4 we want kg");
            _labelFuelFlowCruisePage.text = @"Fuel Flow [kg/h]";  
            fuelUnitText = @"kg";  
            if ([originalFuelUnits isEqualToString:@"lbs"] ) {
                //NSLog(@"but we need to convert lbs to kilo");
                //convert fuel on board from lbs to kilo
                usableFuelOnBoard = usableFuelOnBoard / 2.2046;
                 if (flagGettingFuelFromInputField == 0) {
                      resultCruiseFuelBurn = resultCruiseFuelBurn / 2.2046;
                 }
               
            }
        } 
        
         //NSLog(@"22 resultCruiseFuelBurn %.1f  %@", resultCruiseFuelBurn , fuelUnitText);   
        if (flagGettingFuelFromInputField == 0) {
            //NSLog(@"!!!!!!!!!!!!!!!!!!!");   
            resultCruiseFuelBurn = resultCruiseFuelBurn * specificFuelDensityValue;
        }
    }
    
    //NSLog(@"flagGettingFuelFromInputField %d", flagGettingFuelFromInputField); 
   
    //NSLog(@"usableFuelOnBoard %.1f", usableFuelOnBoard);    
    
     
    //NSLog(@"33resultCruiseFuelBurn %.1f  %@", resultCruiseFuelBurn , fuelUnitText);    
    
    _iCruiseFuelBurn.text =  [[NSString alloc] initWithFormat:@"%.1f %@", resultCruiseFuelBurn, fuelUnitText ];    
    
   
    if (_switchOverrideCruiseInput.on == NO  ) {        
        
        _cruiseInputFuelFlow.text =  [[NSString alloc] initWithFormat:@"%.1f", resultCruiseFuelBurn ];    
        
        //NSLog(@"setting _cruiseInputFuelFlow.text   %@", _cruiseInputFuelFlow.text);   
    }
    
    
        
    [_viewCruiseAnimations.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    
  
    
    float paCalc = ((29.92 - LDG_ALTIM) *1000);
    if (paCalc < 0.001 & paCalc > -0.001) {
        paCalc = 0;
    }
    float landingPressureAlt = LDG_ELEV + paCalc;     
    float descentDistance = 0, totalCruiseRangeNM = 0, desiredCruiseDistanceOnly = 0, fuelForTripDistanceGallons = 0; 
   
    if (IAS < 1) {
        IAS = 1;
    }
    float rateOfDescentFeetMin = IAS;
    float fuelFlowDescentGalPerHour = resultCruiseFuelBurn;
    
        
    float cruiseGroundSpeed =  resultCruiseKTAS - windComponentCruise;
     _iCruiseGroundSpeed.text =  [[NSString alloc] initWithFormat:@"%.0f KTS", cruiseGroundSpeed ];  
    float descentGroundSpeed = cruiseGroundSpeed;
    
    
    
    
    
    //NSLog(@"rateOfDescentFeetMin %.0f", rateOfDescentFeetMin);
    
    float descentTimeHours = ((Hp - landingPressureAlt) / rateOfDescentFeetMin) / 60;
    float descentFuel = descentTimeHours * fuelFlowDescentGalPerHour;
    descentDistance = descentTimeHours * descentGroundSpeed;
    
    if (isnan(descentDistance)) {
        descentDistance = 0;
    }
       
    
    //NSLog(@"descentTimeHours %.1f", descentTimeHours);
    //NSLog(@"fuelFlowDescentGalPerHour %.1f", fuelFlowDescentGalPerHour);
    
    //NSLog(@"descentFuel %.1f", descentFuel);
    //NSLog(@"descentDistance %.1f", descentDistance);
    
    
    float desiredTripDistanceNM = _sliderTripDistanceNM.value;
    if ([calcMode isEqualToString:@"plan"]) {           
       desiredCruiseDistanceOnly = desiredTripDistanceNM - descentDistance - resultClimbDistanceTotal;
    }else{
         desiredCruiseDistanceOnly = desiredTripDistanceNM;
    }
    _iCruiseTripFuel.text = [[NSString alloc] initWithFormat:@"%.1f %@", (desiredCruiseDistanceOnly/cruiseGroundSpeed) * resultCruiseFuelBurn, fuelUnitText ]; 
    //NSLog(@"desiredCruiseDistanceOnly %.0f", desiredCruiseDistanceOnly);
    //NSLog(@"cruiseGroundSpeed %.0f", cruiseGroundSpeed);
    //NSLog(@"resultCruiseFuelBurn %.0f", resultCruiseFuelBurn);
   
   
    fuelForTripDistanceGallons = (desiredCruiseDistanceOnly / cruiseGroundSpeed) * resultCruiseFuelBurn;  
     

    if ([calcMode isEqualToString:@"plan"]) { 
        totalCruiseRangeNM = ((usableFuelOnBoard - Climb_FuelTotal) / resultCruiseFuelBurn) * cruiseGroundSpeed;              
    }else{
        totalCruiseRangeNM = ((usableFuelOnBoard) / resultCruiseFuelBurn) * cruiseGroundSpeed;
    }
    
    //NSLog(@"usableFuelOnBoard %.1f", usableFuelOnBoard);
    //NSLog(@"Climb_FuelTotal %.1f", Climb_FuelTotal);
    //NSLog(@"resultCruiseFuelBurn %.1f", resultCruiseFuelBurn);
    //NSLog(@"cruiseGroundSpeed %.1f", cruiseGroundSpeed);
    //NSLog(@"totalCruiseRangeNM %.1f", totalCruiseRangeNM);
    //NSLog(@"resultClimbDistanceTotal %.1f", resultClimbDistanceTotal);
    
    
    _iDescentRoD.text =  [[NSString alloc] initWithFormat:@"%.0f ft/min", rateOfDescentFeetMin  ]; 
    _iDescentTAS.text =  [[NSString alloc] initWithFormat:@"%.0f KTAS", resultCruiseKTAS  ]; 
    _iDescentGroundSpeed.text =  [[NSString alloc] initWithFormat:@"%.0f KTS", cruiseGroundSpeed  ]; 
    _iDescentFuelFlow.text =  [[NSString alloc] initWithFormat:@"%.0f %@", fuelFlowDescentGalPerHour, fuelUnitText   ]; 
    _iDescentTime.text =  [[NSString alloc] initWithFormat:@"%.1f min", (Hp - landingPressureAlt) / rateOfDescentFeetMin ]; 
   
    
    _iTripClimbFuel.text =  [[NSString alloc] initWithFormat:@"%.1f %@", Climb_FuelTotal , fuelUnitText   ]; 
    _iTripCruiseFuel.text =  [[NSString alloc] initWithFormat:@"%.1f %@", (desiredCruiseDistanceOnly/cruiseGroundSpeed) * resultCruiseFuelBurn, fuelUnitText   ];
    _iTripDescentFuel.text =  [[NSString alloc] initWithFormat:@"%.1f %@", descentFuel, fuelUnitText ];    
    
    float totalTripFuel = 0;
    if ([calcMode isEqualToString:@"plan"]) {    
         totalTripFuel = Climb_FuelTotal + descentFuel + ((desiredCruiseDistanceOnly/cruiseGroundSpeed) * resultCruiseFuelBurn);
    }else{
         totalTripFuel = (desiredCruiseDistanceOnly/cruiseGroundSpeed) * resultCruiseFuelBurn;
    }
   
    
    
    _iTripTotalFuel.text =  [[NSString alloc] initWithFormat:@"%.1f %@", totalTripFuel, fuelUnitText ];
    
    // time
    int minuteDifference = (desiredCruiseDistanceOnly / cruiseGroundSpeed) * 60;
    int hours = minuteDifference / 60;
    int minutes = minuteDifference - (hours * 60);
    NSString *flightTime=  [ [NSString alloc] initWithFormat:@"%.d", minuteDifference ];
    if (minutes >= 10)                  { flightTime =  [ [NSString alloc] initWithFormat:@"0%.dh:%.dmin", hours, minutes ];}
    if (minutes <= 9  & minutes > 0)    { flightTime =  [ [NSString alloc] initWithFormat:@"0%.dh:0%.dmin", hours, minutes ];}
    if (minutes <= 0)                   { flightTime =  [ [NSString alloc] initWithFormat:@"0%.dh:00min", hours ];}        
    _iCruiseTime.text =  flightTime;
    
    float reserveFuel = usableFuelOnBoard - totalTripFuel;
    float reserveTimeMinutes = reserveFuel / resultCruiseFuelBurn * 60;
    
   
    
    _labelReserveTimeOnCruise.text =  [[NSString alloc] initWithFormat:@"%.0f min", reserveTimeMinutes ];
    
    if ([fuelEnterMode isEqualToString:@"volume"]) {         
        //fuelOnBoardKg is mass, we need to convert to volume             
        if ([selectedUnitForFuel isEqualToString:@"lbs"] ) { 
             _labelUsableFuelOnBoard.text =  [[NSString alloc] initWithFormat:@"%.1f Gal", usableFuelOnBoard ]; 
            _labelLandingFuelOnCruise.text =  [[NSString alloc] initWithFormat:@"%.1f Gal", reserveFuel];
           
        }
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _labelUsableFuelOnBoard.text =  [[NSString alloc] initWithFormat:@"%.0f ltr", usableFuelOnBoard ];
            _labelLandingFuelOnCruise.text =  [[NSString alloc] initWithFormat:@"%.0f kg", reserveFuel ];
        }        
    }else{         
        if ([selectedUnitForFuel isEqualToString:@"lbs"] ) {  
            _labelUsableFuelOnBoard.text =  [[NSString alloc] initWithFormat:@"%.0f lbs", usableFuelOnBoard ];
            _labelLandingFuelOnCruise.text =  [[NSString alloc] initWithFormat:@"%.0f lbs", reserveFuel ];
        }
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) { 
             _labelUsableFuelOnBoard.text =  [[NSString alloc] initWithFormat:@"%.0f kg", usableFuelOnBoard ];
           _labelLandingFuelOnCruise.text =  [[NSString alloc] initWithFormat:@"%.0f kg", reserveFuel ];
        }            
    }
  
   
    
    
   
    
 
    
    _iCruiseDistance.text =  [[NSString alloc] initWithFormat:@"%.1f %@", desiredCruiseDistanceOnly * conversionNNMtoKM, unitDistanceNMkm ];      
    _iCruiseToD.text =  [[NSString alloc] initWithFormat:@"%.0f %@", resultClimbDistanceTotal + desiredCruiseDistanceOnly  * conversionNNMtoKM, unitDistanceNMkm];
    _iTripDescentDistance.text =  [[NSString alloc] initWithFormat:@"%.0f %@", descentDistance * conversionNNMtoKM, unitDistanceNMkm ];  
    _iTripClimbDistance.text = [[NSString alloc] initWithFormat:@"%.1f %@", (climbDistanceEnd- climbDistanceStart) * conversionNNMtoKM, unitDistanceNMkm];
    
    _iTripTotalDistance.text = [[NSString alloc] initWithFormat:@"%.1f %@", (desiredCruiseDistanceOnly + descentDistance + (climbDistanceEnd- climbDistanceStart) ) * conversionNNMtoKM, unitDistanceNMkm];
    
    cruiseXaxisEnd = cruiseRangeWindowNM;
   
    
    if ([calcMode isEqualToString:@"plan"]) {  
        
        float yPixelDiffClimbStart =  ( _viewCruiseGrid.frame.size.height - (_viewCruiseGrid.frame.size.height / cruiseYaxisEnd) * [_iClimbPAStart.text floatValue] );        
        float xPixelDiffCruiseStart =  ( (_viewCruiseGrid.frame.size.width) / cruiseXaxisEnd) * (resultClimbDistanceTotal) ;
        float yPixelDiffClimbEnd =  ( _viewCruiseGrid.frame.size.height - (_viewCruiseGrid.frame.size.height / cruiseYaxisEnd) * [_iClimbPAEnd.text floatValue] );        
        float totalCruissDistance = resultClimbDistanceTotal + desiredCruiseDistanceOnly + descentDistance;
        totalTripRange =  totalCruiseRangeNM;
        
       
        if (totalTripRange < _sliderTripDistanceNM.value) {
            triggerCruiseRangeWarning = 1;
            _labelWarningTripFuel.text = @"Not sufficient fuel for trip distance. Increase fuel on W&B page.";
            _warningTripFuel.backgroundColor = [UIColor redColor];
        }else if (reserveTimeMinutes < [parent.vReserveTimeField.text floatValue]) {
            triggerCruiseRangeWarning = 1;
            _labelWarningTripFuel.text = @"Reserve Time too low. Increase fuel on W&B page/check Flight Settings" ;
            _warningTripFuel.backgroundColor = [UIColor orangeColor];
            _labelReserveTimeOnCruise.textColor = [UIColor orangeColor];
        }else{
            triggerCruiseRangeWarning = 0;
            _labelReserveTimeOnCruise.textColor = [UIColor whiteColor];
        }
        
       
        // climb line
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( 0, yPixelDiffClimbStart )];
        [path addLineToPoint:CGPointMake( xPixelDiffCruiseStart, yPixelDiffClimbEnd ) ];  
        CAShapeLayer *shapeLayerRedLine = [CAShapeLayer layer];
        shapeLayerRedLine.path = [path CGPath];
        shapeLayerRedLine.strokeColor = [[UIColor orangeColor] CGColor];
        shapeLayerRedLine.lineWidth = 5.0;
        shapeLayerRedLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseAnimations.layer addSublayer:shapeLayerRedLine];  
        
        //total cruise line
        float xPixelDiffCruiseEnd =  ( (_viewCruiseGrid.frame.size.width) / cruiseXaxisEnd) * ( totalCruiseRangeNM);   
        if (isnan(xPixelDiffCruiseEnd)) {
            xPixelDiffCruiseEnd = 0;
        }
        
        float yPixelDiffCruise =  ( _viewCruiseGrid.frame.size.height - (_viewCruiseGrid.frame.size.height / cruiseYaxisEnd) * Hp );    
        UIBezierPath *path2 = [UIBezierPath bezierPath];
        [path2 moveToPoint:CGPointMake( xPixelDiffCruiseStart, yPixelDiffCruise )];
        [path2 addLineToPoint:CGPointMake( xPixelDiffCruiseEnd, yPixelDiffCruise ) ];  
        CAShapeLayer *shapeLayerCruiseLine = [CAShapeLayer layer];
        shapeLayerCruiseLine.path = [path2 CGPath];
        shapeLayerCruiseLine.strokeColor = [yellowSpecialColor  CGColor];
        shapeLayerCruiseLine.lineWidth = 5.0;
        shapeLayerCruiseLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseAnimations.layer addSublayer:shapeLayerCruiseLine];
       
        //desired cruise line only
        float xPixelDiffCruiseOnlyEnd =  ( (_viewCruiseGrid.frame.size.width) / cruiseXaxisEnd) * (resultClimbDistanceTotal + desiredCruiseDistanceOnly);
        path2 = [UIBezierPath bezierPath];
        [path2 moveToPoint:CGPointMake( xPixelDiffCruiseStart, yPixelDiffCruise )];
        [path2 addLineToPoint:CGPointMake( xPixelDiffCruiseOnlyEnd, yPixelDiffCruise ) ];  
        CAShapeLayer *shapeLayerCruiseOnlyLine = [CAShapeLayer layer];
        shapeLayerCruiseOnlyLine.path = [path2 CGPath];
     
        if (triggerCruiseRangeWarning == 1) {
            _warningTripFuel.hidden = NO;
            shapeLayerCruiseOnlyLine.strokeColor = [[UIColor redColor]  CGColor];
        }else{
            shapeLayerCruiseOnlyLine.strokeColor = [[UIColor greenColor]  CGColor];
            _warningTripFuel.hidden = YES;
        }
      
        shapeLayerCruiseOnlyLine.lineWidth = 7.0;
        shapeLayerCruiseOnlyLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseAnimations.layer addSublayer:shapeLayerCruiseOnlyLine];
        
        // dot TOC
        float dotSize = 12;
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( xPixelDiffCruiseStart, yPixelDiffClimbEnd)];
        UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)]; 
        [circleLayer setPath:[pathC CGPath]];  
        [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
        [circleLayer setLineWidth:2.0f];
        [_viewCruiseAnimations.layer addSublayer:circleLayer];
        
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake( xPixelDiffCruiseStart - 10, yPixelDiffClimbEnd - 27 , 35, 17)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:14];
        [label  setText: @"TOC"  ];
        [_viewCruiseAnimations addSubview: label];
        
        
        
        float xPixelDiffDescentEnd =  ( (_viewCruiseGrid.frame.size.width) / cruiseXaxisEnd) * totalCruissDistance; 
        
        float yPixelDiffLanding =  ( _viewCruiseGrid.frame.size.height - (_viewCruiseGrid.frame.size.height / cruiseYaxisEnd) * landingPressureAlt );    
        
        // descent line
        UIBezierPath *path3 = [UIBezierPath bezierPath];
        [path3 moveToPoint:CGPointMake( xPixelDiffCruiseOnlyEnd, yPixelDiffCruise )];
        [path3 addLineToPoint:CGPointMake( xPixelDiffDescentEnd, yPixelDiffLanding ) ];  
        CAShapeLayer *shapeLayerDescentLine = [CAShapeLayer layer];
        shapeLayerDescentLine.path = [path3 CGPath];
        shapeLayerDescentLine.strokeColor = [[UIColor orangeColor] CGColor];
        shapeLayerDescentLine.lineWidth = 5.0;
        shapeLayerDescentLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseAnimations.layer addSublayer:shapeLayerDescentLine]; 
        // dot TOD
        dotSize = 12;
        circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( xPixelDiffCruiseOnlyEnd, yPixelDiffCruise)];
        pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)]; 
        [circleLayer setPath:[pathC CGPath]];  
        [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
        [circleLayer setLineWidth:2.0f];
        [_viewCruiseAnimations.layer addSublayer:circleLayer];
      
        label= [[UILabel alloc] initWithFrame:CGRectMake( xPixelDiffCruiseOnlyEnd - 30, yPixelDiffCruise - 27 , 35, 17)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:14];
        [label  setText: @"TOD"  ];
        [_viewCruiseAnimations addSubview: label];
     
        
        float yPixelDiffTakeoffPA =  ( _viewCruiseGrid.frame.size.height - (_viewCruiseGrid.frame.size.height / cruiseYaxisEnd) * TO_PA );
        // takeoff dot
        dotSize = 12;
        circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( 0, yPixelDiffTakeoffPA)];
        pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)]; 
        [circleLayer setPath:[pathC CGPath]];  
        [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
        [circleLayer setLineWidth:2.0f];
        [_viewCruiseAnimations.layer addSublayer:circleLayer];
      
        
        // landing dot
        dotSize = 12;
        circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( xPixelDiffDescentEnd, yPixelDiffLanding)];
        pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)]; 
        [circleLayer setPath:[pathC CGPath]];  
        [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
        [circleLayer setLineWidth:2.0f];
        [_viewCruiseAnimations.layer addSublayer:circleLayer];
        
        // max cruise
        dotSize = 12;
        circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( xPixelDiffCruiseEnd, yPixelDiffCruise)];        
        pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)];        
        [circleLayer setPath:[pathC CGPath]];  
        [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
        [circleLayer setLineWidth:2.0f];    
        [_viewCruiseAnimations.layer addSublayer:circleLayer];
      
        label= [[UILabel alloc] initWithFrame:CGRectMake( xPixelDiffCruiseEnd - 20, yPixelDiffCruise - 27 , 60, 17)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:13];
        [label  setText:  [[NSString alloc] initWithFormat:@"%.0f NM", totalTripRange ]   ];
        [_viewCruiseAnimations addSubview: label];
      
        // position aircraft   
        _symACCruise.frame = CGRectMake( ((xPixelDiffCruiseOnlyEnd - xPixelDiffCruiseStart)/2 + xPixelDiffCruiseStart) , yPixelDiffCruise - _symACCruise.frame.size.height/2-18, _symACCruise.frame.size.width, _symACCruise.frame.size.height);
        
    
        
    }else{
        
        
        float xPixelDiffCruiseStart =  ( (_viewCruiseGrid.frame.size.width) / cruiseXaxisEnd) * (1) ;
       
        totalTripRange =  totalCruiseRangeNM;
        
        ViewController *parent = (ViewController *)self.parentViewController; 
        
        
        if (totalTripRange < _sliderTripDistanceNM.value) {
            triggerCruiseRangeWarning = 1;
            _labelWarningTripFuel.text = @"Not sufficient fuel for trip distance. Increase fuel on W&B page.";
            _warningTripFuel.backgroundColor = [UIColor redColor];
        }else if (reserveTimeMinutes < [parent.vReserveTimeField.text floatValue]) {
            triggerCruiseRangeWarning = 1;
            _labelWarningTripFuel.text = @"Reserve Time too low. Increase fuel on W&B page/check Flight Settings" ;
            _warningTripFuel.backgroundColor = [UIColor orangeColor];
            _labelReserveTimeOnCruise.textColor = [UIColor orangeColor];
        }else{
            triggerCruiseRangeWarning = 0;
            _labelReserveTimeOnCruise.textColor = [UIColor whiteColor];
        }
        
        //total cruise line
        float xPixelDiffCruiseEnd =  ( (_viewCruiseGrid.frame.size.width) / cruiseXaxisEnd) * (totalCruiseRangeNM);   
        float yPixelDiffCruise =  ( _viewCruiseGrid.frame.size.height - (_viewCruiseGrid.frame.size.height / cruiseYaxisEnd) * Hp );    
        UIBezierPath *path2 = [UIBezierPath bezierPath];
        [path2 moveToPoint:CGPointMake( xPixelDiffCruiseStart, yPixelDiffCruise )];
        [path2 addLineToPoint:CGPointMake( xPixelDiffCruiseEnd, yPixelDiffCruise ) ];  
        CAShapeLayer *shapeLayerCruiseLine = [CAShapeLayer layer];
        shapeLayerCruiseLine.path = [path2 CGPath];
        shapeLayerCruiseLine.strokeColor = [yellowSpecialColor  CGColor];
        shapeLayerCruiseLine.lineWidth = 5.0;
        shapeLayerCruiseLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseAnimations.layer addSublayer:shapeLayerCruiseLine];
        
        //desired cruise line only
        float xPixelDiffCruiseOnlyEnd =  ( (_viewCruiseGrid.frame.size.width) / cruiseXaxisEnd) * (desiredCruiseDistanceOnly);
        path2 = [UIBezierPath bezierPath];
        [path2 moveToPoint:CGPointMake( xPixelDiffCruiseStart, yPixelDiffCruise )];
        [path2 addLineToPoint:CGPointMake( xPixelDiffCruiseOnlyEnd, yPixelDiffCruise ) ];  
        CAShapeLayer *shapeLayerCruiseOnlyLine = [CAShapeLayer layer];
        shapeLayerCruiseOnlyLine.path = [path2 CGPath];
        
        if (triggerCruiseRangeWarning == 1) {
            _warningTripFuel.hidden = NO;
            shapeLayerCruiseOnlyLine.strokeColor = [[UIColor redColor]  CGColor];
        }else{
            shapeLayerCruiseOnlyLine.strokeColor = [[UIColor greenColor]  CGColor];
            _warningTripFuel.hidden = YES;
        }
        
        shapeLayerCruiseOnlyLine.lineWidth = 7.0;
        shapeLayerCruiseOnlyLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseAnimations.layer addSublayer:shapeLayerCruiseOnlyLine];
        
        
        
        
        // max cruise
        float dotSize = 12;
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        [circleLayer setBounds:CGRectMake(0.0f, 0.0f, dotSize ,dotSize)];
        [circleLayer setPosition:CGPointMake( xPixelDiffCruiseEnd, yPixelDiffCruise)];
        UIBezierPath *pathC = [UIBezierPath bezierPathWithOvalInRect:   CGRectMake(0.0f, 0.0f, dotSize, dotSize)]; 
        [circleLayer setPath:[pathC CGPath]];  
        [circleLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [circleLayer setFillColor:[[UIColor whiteColor] CGColor]];
        [circleLayer setLineWidth:2.0f];
        [_viewCruiseAnimations.layer addSublayer:circleLayer];
        
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake( xPixelDiffCruiseEnd - 20, yPixelDiffCruise - 27 , 60, 17)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:13];
        [label  setText:  [[NSString alloc] initWithFormat:@"%.0f NM", totalTripRange ]   ];
        [_viewCruiseAnimations addSubview: label];
        
        // position aircraft    
      
        _symACCruise.frame = CGRectMake( xPixelDiffCruiseOnlyEnd - 20 , yPixelDiffCruise - _symACCruise.frame.size.height/2-18, _symACCruise.frame.size.width, _symACCruise.frame.size.height);

        
    }
    
     
     
   
   
    
    
   
    
    
    
}


- (void) computeCruiseTableSR22 {
    
    //NSLog(@"computeCruiseTable " );
    //FixedWing_Cirrus_SR22TG6_NONE_CruiseComp_lbs_FXX   
    arrayKey = [ [NSString alloc] initWithFormat:@"%@", chartNameForThisInfoFile ];       
    //arrayKey = [ [NSString alloc] initWithFormat:@"%@_part1_infoFile", [infoArray objectAtIndex: 0] ];
    NSString *loadedperfString = [[NSUserDefaults standardUserDefaults] objectForKey:arrayKey];   
    loadedperfString  = [ loadedperfString stringByReplacingOccurrencesOfString:@"\n" withString:@""];  
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"*"]; 
    NSArray* components = [loadedperfString componentsSeparatedByCharactersInSet:charSet];     
    charSet = [NSCharacterSet characterSetWithCharactersInString:@"+"];
    NSArray *dataComponents = [ [components objectAtIndex:1] componentsSeparatedByCharactersInSet:charSet];
        
    
    //NSLog(@"dataComponents %@ ", dataComponents );
    
   
    //********************************
    float checkHP = Hp;   
    //********************************
    
    //NSLog(@"checkHP %.0f ", checkHP );
    
    int PAdatasetID = 0;
    
    // check for PA
    // check for PA
    for (int i = 0; i < dataComponents.count-2 ; i++) {
        charSet = [NSCharacterSet characterSetWithCharactersInString:@"_"];
        NSArray *dataComponentsPA = [[dataComponents objectAtIndex:i] componentsSeparatedByCharactersInSet:charSet]; 
        // look for HP
        float PAvalueLow = [[[dataComponentsPA objectAtIndex:0] stringByReplacingOccurrencesOfString:@"@" withString:@""] floatValue];       
        dataComponentsPA = [[dataComponents objectAtIndex:i+1] componentsSeparatedByCharactersInSet:charSet];  
        float PAvalueHigh = [[[dataComponentsPA objectAtIndex:0] stringByReplacingOccurrencesOfString:@"@" withString:@""] floatValue];            
        if (checkHP <= PAvalueLow) {           
            PAdatasetID = i;
            break;
        }        
        if (checkHP >= PAvalueLow & checkHP <= PAvalueHigh) { 
            PAdatasetID = i+1;          
            break;
        }
    }
    
    NSString *dataComponentsPA = [dataComponents objectAtIndex:PAdatasetID];    
    //NSLog(@"dataComponentsPA %@ ", dataComponentsPA);
  
    // welche power ist im Angebot?
    
    // get Spielraum fuer power
    charSet = [NSCharacterSet characterSetWithCharactersInString:@"@"];
    NSArray *dataComponentsPAselected = [dataComponentsPA componentsSeparatedByCharactersInSet:charSet];  
    //NSLog(@"dataComponentsPAselected %@ ", dataComponentsPAselected);
      
    arrayPowerSets = [[NSMutableArray alloc] init];
    NSArray *dataStringComponents;    
    
    for (int i = 1; i < dataComponentsPAselected.count ; i++) {  
                
        NSString *dataSetString = [dataComponentsPAselected objectAtIndex:i]; 
        charSet = [NSCharacterSet characterSetWithCharactersInString:@"_"];
        dataStringComponents = [dataSetString componentsSeparatedByCharactersInSet:charSet];
        //NSLog(@"dataStringComponents %@ ", dataStringComponents);
        [arrayPowerSets addObject:[dataStringComponents objectAtIndex:1]];
        
    }
    
     
    
    
  
    
    NSString *selectedPowerValue = [arrayPowerSets objectAtIndex:_segmentCruisePower.selectedSegmentIndex];  
    //NSLog(@"cruiseSegmentSelected %.0f ", cruiseSegmentSelected);
    //NSLog(@"selectedPowerValue %@ ", selectedPowerValue);
    
    
    NSUInteger i = [ arrayPowerSets indexOfObject: selectedPowerValue ];
    //NSLog(@"arrayPowerSets %@ ", arrayPowerSets);
    NSString *selectedDataString = [dataComponentsPAselected objectAtIndex:i+1]; 
    //NSLog(@"selectedDataString %@ ", selectedDataString);   
    charSet = [NSCharacterSet characterSetWithCharactersInString:@"_"];
    dataStringComponents = [selectedDataString componentsSeparatedByCharactersInSet:charSet];
       //NSLog(@"dataStringComponents %@ ", dataStringComponents);  
  
    float fuelFlow = [[dataStringComponents objectAtIndex:2]floatValue];
    
    //NSLog(@"1 fuelFlow %.1f ", fuelFlow);  
    
    float tasMinus30 = [[dataStringComponents objectAtIndex:3]floatValue];
    float tasISA = [[dataStringComponents objectAtIndex:5]floatValue];
    float tasPlus30 = [[dataStringComponents objectAtIndex:7]floatValue];
       
    //NSLog(@"tasMinus30 %.1f ", tasMinus30);
    //NSLog(@"tasISA %.1f ", tasISA);
    //NSLog(@"tasPlus30 %.1f ", tasPlus30);
    
    float ISAcheck = ISADiff;
    //NSLog(@"ISAcheck%.1f ", ISAcheck);
    
    float tasLow = 0, tasHigh = 0;
    float TASinKTS  = 0;
    
    if (ISAcheck < 0) {
        tasLow = tasISA;
        tasHigh = tasMinus30;
        TASinKTS = tasLow - (((tasHigh-tasLow)/30) * ISAcheck);
        
    }else{
        tasLow = tasISA;
        tasHigh = tasPlus30; 
        TASinKTS = tasLow + (((tasHigh-tasLow)/30) * ISAcheck);
    }
    
    //NSLog(@"computed Fuel Flow %.1f ", fuelFlow);   
    
    //interpolate TAS for ISA   
    if (_switchOverrideCruiseInput.on == NO) {
        
        _cruiseInputTAS.text = [[NSString alloc] initWithFormat:@"%.0f", TASinKTS];  
                
        // this table gives us gallons and we need to convert to desired unit
         
        
        
        if ([fuelEnterMode isEqualToString:@"volume"]) {
            if ([selectedUnitForFuel isEqualToString:@"lbs"] ) {
                // we need gallons no conversion 
                _cruiseInputFuelFlow.text = [[NSString alloc] initWithFormat:@"%.1f", fuelFlow];                 
            }
            if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
                // we need liter - convert gal to liter 
                _cruiseInputFuelFlow.text = [[NSString alloc] initWithFormat:@"%.1f", fuelFlow * 3.7854];                
            }
            
        }else{
            if ([selectedUnitForFuel isEqualToString:@"lbs"] ) {
                // we need to convert to lbs,
                _cruiseInputFuelFlow.text = [[NSString alloc] initWithFormat:@"%.1f", fuelFlow * specificFuelDensityValue]; 
               
            }
            if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
                // we need to convert to lbs, then to kg
                _cruiseInputFuelFlow.text = [[NSString alloc] initWithFormat:@"%.1f", fuelFlow * specificFuelDensityValue / 2.2046];                
            }            
        }
        
       
        
        
        _cruiseInputTAS.enabled = NO;
        _cruiseInputFuelFlow.enabled = NO;
        
        
        _cruiseInputTAS.textColor = [UIColor whiteColor];
        [_cruiseInputTAS setBorderStyle:UITextBorderStyleLine];
        _cruiseInputTAS.backgroundColor = [UIColor clearColor];
        
        _cruiseInputFuelFlow.textColor = [UIColor whiteColor];
        [_cruiseInputFuelFlow setBorderStyle:UITextBorderStyleLine];
        _cruiseInputFuelFlow.backgroundColor = [UIColor clearColor];
        
        
    }else{
        _cruiseInputTAS.enabled = YES;
        _cruiseInputFuelFlow.enabled = YES;
        
         
        _cruiseInputTAS.textColor = [UIColor blackColor];
        [_cruiseInputTAS setBorderStyle:UITextBorderStyleRoundedRect];
        _cruiseInputTAS.backgroundColor = [UIColor whiteColor];
        
        _cruiseInputFuelFlow.textColor = [UIColor blackColor];
        [_cruiseInputFuelFlow setBorderStyle:UITextBorderStyleRoundedRect];
        _cruiseInputFuelFlow.backgroundColor = [UIColor whiteColor];
    }
    
    
   
}



- (IBAction)actionSegmentCruisePower:(id)sender {  
   
   [self calcPerformance];
    
}



- (void) createCruisePowerSegment {
    
    //NSLog(@"createCruisePowerSegment ");
      
    
    [_viewCruisePowerSegment.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    triggerCruiseSegmentSet = 1;
   
    NSMutableArray *segmentNamesArray = [[NSMutableArray alloc] init];    
    for (int i = 0; i < arrayPowerSets.count ; i++) {
        //NSLog(@" [arrayPowerSets objectAtIndex:i] %@",  [arrayPowerSets objectAtIndex:i]);
        NSString *segmentString =   [[NSString alloc] initWithFormat:@"%@%%",  [arrayPowerSets objectAtIndex:i] ];         
        [segmentNamesArray addObject:segmentString];
    }
    
  
   
    // create segment    
     UISegmentedControl * segmentedControlCruise = [[UISegmentedControl alloc] initWithItems:segmentNamesArray]; //@[@"One",@"Two"]
    segmentedControlCruise.frame = CGRectMake(8,  10, 591, 28);
    [segmentedControlCruise addTarget:self action:@selector(segmentActionCruisePower:) forControlEvents: UIControlEventValueChanged];
    segmentedControlCruise.tag = 1;
    
    /*
    if (cruiseSegmentSelected == 99) {
         segmentedControlCruise.selectedSegmentIndex = 0;
        cruiseSegmentSelected = 0;
    }
   */
    segmentedControlCruise.selectedSegmentIndex = 1;
    cruiseSegmentSelected = 1;
    
     segmentedControlCruise.tintColor = [UIColor whiteColor];
    segmentedControlCruise.backgroundColor = [UIColor lightGrayColor]; 
    [_viewCruisePowerSegment addSubview:segmentedControlCruise];
    
}

- (void) createGraphicsCruise {
    
    //NSLog(@"createGraphicsCruise");
    
    _viewCruiseAnimations.frame = CGRectMake(_viewCruiseGrid.frame.origin.x, _viewCruiseGrid.frame.origin.y, _viewCruiseGrid.frame.size.width, _viewCruiseGrid.frame.size.height);
    
    //NSLog(@"1 createGraphicsCruise");
    int maxElevation = CruiseMaxElevation;
    int ySteps = maxElevation / CruiseElevationincrement; 
    cruiseYaxisEnd = maxElevation;
    float yPixelDiff =  ( _viewCruiseGrid.frame.size.height / cruiseYaxisEnd) * (cruiseYaxisEnd /ySteps);    
    //NSLog(@"2 createGraphicsCruise _viewCruiseGrid %lu", (unsigned long)_viewCruiseGrid.subviews.count);
    [_viewCruiseGrid.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
   
    
    // frame
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake( 0, 0 )];
    [path addLineToPoint:CGPointMake( _viewCruiseGrid.frame.size.width, 0 )  ];
    [path addLineToPoint:CGPointMake( _viewCruiseGrid.frame.size.width, _viewCruiseGrid.frame.size.height)];
    [path addLineToPoint:CGPointMake( 0, _viewCruiseGrid.frame.size.height)  ];
    [path addLineToPoint:CGPointMake( 0, 0)  ];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];
    shapeLayer.lineWidth = 3.0;
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    [_viewCruiseGrid.layer addSublayer:shapeLayer];
    
  
    // y lines
    for (int i = 0; i < ySteps+1 ; i++) {        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( 0, _viewCruiseGrid.frame.size.height - (i * yPixelDiff) )];
        [path addLineToPoint:CGPointMake( _viewCruiseGrid.frame.size.width, _viewCruiseGrid.frame.size.height - (i * yPixelDiff) )];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];
        shapeLayer.lineWidth = 1.0;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseGrid.layer addSublayer:shapeLayer]; 
        
        if (i == ySteps) {
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake( -86, _viewCruiseGrid.frame.size.height - (i * yPixelDiff) - 5 , 80, 20)];
            label.textAlignment = NSTextAlignmentRight;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText =  @"feet PA";
            if (_segmentMeterFeetCruise.selectedSegmentIndex == 1) {
                labelText =  @"meter PA"; 
            }            
            [label  setText: labelText  ];
            [_viewCruiseGrid addSubview: label];
        }else{
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake( -86, _viewCruiseGrid.frame.size.height - (i * yPixelDiff) -10, 80, 20)];
            label.textAlignment = NSTextAlignmentRight;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText;            
            labelText =  [[NSString alloc] initWithFormat:@"%d",  i * CruiseElevationincrement ]; 
           
            [label  setText: labelText  ];
            [_viewCruiseGrid addSubview: label];
            
        }
    }
    
    
 
    
    // x lines    
    cruiseXaxisEnd = cruiseRangeWindowNM;
    
    int stepNM = 50;
    if (cruiseRangeWindowNM >= 1000) {
        stepNM = 100;
    }
    
    int xSteps = cruiseXaxisEnd / stepNM;
    
    float xPixelDiff =  ( _viewCruiseGrid.frame.size.width / cruiseXaxisEnd) * (cruiseXaxisEnd /xSteps);
    
    for (int i = 0; i < xSteps+1 ; i++) {        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(  (i * xPixelDiff), 0 )];
        [path addLineToPoint:CGPointMake(  (i * xPixelDiff), _viewCruiseGrid.frame.size.height ) ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        shapeLayer.strokeColor = [[UIColor lightGrayColor] CGColor];
        shapeLayer.lineWidth = 1.0;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [_viewCruiseGrid.layer addSublayer:shapeLayer];
        
        if (i == 0) {
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(  (i * xPixelDiff) , _viewCruiseGrid.frame.size.height +1  , 80, 20)];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText =  @"NM";
            if (_segmentMeterFeetCruise.selectedSegmentIndex == 1) {
                labelText =  @"km";
            }
            [label  setText: labelText  ];
            [_viewCruiseGrid addSubview: label];
        }else{
            UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(  (i * xPixelDiff) - 40 , _viewCruiseGrid.frame.size.height +1  , 80, 20)];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:12];
            NSString *labelText;
            labelText =  [[NSString alloc] initWithFormat:@"%d", i * stepNM]; 
            if (_segmentMeterFeetCruise.selectedSegmentIndex == 1) {
                labelText =  [[NSString alloc] initWithFormat:@"%.0f", i* stepNM * 1.852]; 
            }          
            [label  setText: labelText  ];
            [_viewCruiseGrid addSubview: label];            
        }
    }
    
    
   
    
    
    
    
    
}

- (void) prepareChartComp {
    
    [resultsAllChartNames addObject: chartNameForThisInfoFile];
    [resultsAllChartUserNames addObject: chartUserName];
    [resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d", 0 ]];
    //[resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagInputDataOutOfRange]];
    [resultsAllChartValues addObject: [ [NSString alloc] initWithFormat:@"%.5f", resultComputation ]];
    [resultsAllUnits addObject:unitResult];    
    return;
}


- (void) computeClimbTimeFuelDistance {
    
    //NSLog(@"computeClimbTimeFuelDistance");    
    arrayKey = [ [NSString alloc] initWithFormat:@"%@", [infoArray objectAtIndex: 0] ];
    NSString *perfString = [[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] ;    
    //NSLog(@"perfString %@", perfString);
    
    // this is DA42 so we have three weights
    NSArray* componentItems  = [perfString componentsSeparatedByString:@"@"];
    
    //NSLog(@"componentItems %@", componentItems);  
    
    //NSLog(@"componentItems.count %.0lu", (unsigned long)componentItems.count); 
    
    if (componentItems.count < 3) {
        //we have only a single weight for climb (SR22T)
      
        NSArray* climbWeightDataLow  = [[componentItems objectAtIndex:1] componentsSeparatedByString:@"|"];        
        //NSLog(@"climbWeightData %@", climbWeightData );        
       
        //NSLog(@"climbACweightLow %.0f", climbACweightLow ); 
         NSArray* climbWeightDataUsedLow;
         climbWeightDataUsedLow = climbWeightDataLow;
        
        NSArray *PAdataComponents;
        int foundClimbData = 0;
        float lowPA;
        float highPA; 
        
        float interpolatedTAS= 0;
        float interpolatedRoC= 0;
        float interpolatedTime= 0;
        float interpolatedFuel= 0;
        float interpolatedDistance= 0;           
        
        for (int i = 1; i < climbWeightDataUsedLow.count ; i++) {       
            PAdataComponents = [[climbWeightDataUsedLow objectAtIndex:i] componentsSeparatedByString:@","]; 
            //NSLog(@"PAdataComponents %@", PAdataComponents );        
            lowPA = [[PAdataComponents objectAtIndex:0] floatValue];
            highPA = [[PAdataComponents objectAtIndex:1] floatValue];
            if (climbPressureAltUsed >=lowPA & climbPressureAltUsed < highPA) {
                //NSLog(@"found PA data %@", PAdataComponents ); 
                foundClimbData = 1;
                break;
            }       
        }
        
        if (foundClimbData == 0) {
            //NSLog(@"error no climb data!!"); 
        }else{
            
            float lowTAS =  [[PAdataComponents objectAtIndex:2] floatValue];
            float highTAS = [[PAdataComponents objectAtIndex:3] floatValue];        
            float lowRoC =  [[PAdataComponents objectAtIndex:4] floatValue];
            float highRoC = [[PAdataComponents objectAtIndex:5] floatValue];        
            float lowTime =  [[PAdataComponents objectAtIndex:6] floatValue];
            float highTime = [[PAdataComponents objectAtIndex:7] floatValue];        
            float lowFuel =  [[PAdataComponents objectAtIndex:8] floatValue];
            float highFuel = [[PAdataComponents objectAtIndex:9] floatValue];        
            float lowDistance =  [[PAdataComponents objectAtIndex:10] floatValue];
            float highDistance = [[PAdataComponents objectAtIndex:11] floatValue];       
            
            
            //NSLog(@"lowTime %.1f", lowTime);
            //NSLog(@"highTime %.1f", highTime);
            //NSLog(@"climbPressureAltUsed %.1f", climbPressureAltUsed);
            
            interpolatedTAS   = lowTAS  + ( (highTAS-lowTAS) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedRoC   = lowRoC  + ( (highRoC-lowRoC) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedTime  = lowTime  + ( (highTime-lowTime) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedFuel  = lowFuel  + ( (highFuel-lowFuel) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedDistance  = lowDistance  + ( (highDistance-lowDistance) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));                
            //NSLog(@"interpolatedTAS %.1f", interpolatedTAS); 
            //NSLog(@"interpolatedRoC %.1f", interpolatedRoC);
            //NSLog(@"1 interpolatedTime %.1f", interpolatedTime);
            //NSLog(@"interpolatedFuel %.1f", interpolatedFuel);
            //NSLog(@"interpolatedDistance %.1f", interpolatedDistance);
            
            resultClimbSpeed= interpolatedTAS;    
            resultClimbRoC = interpolatedRoC;
            resultClimbTime = interpolatedTime;
            resultClimbFuel = interpolatedFuel;
            resultClimbDistance = interpolatedDistance;
            
            if (isnan(resultClimbTime)) {
                resultClimbTime = 0;
            }
            
            if (isnan(resultClimbFuel)) {
                resultClimbFuel = 0;
            }
            
            if (isnan(resultClimbDistance)) {
                resultClimbDistance = 0;
            }
            
            //NSLog(@"resultClimbTime %.0f", resultClimbTime);
            //NSLog(@"resultClimbFuel %.0f", resultClimbFuel);
            //NSLog(@"resultClimbDistance %.0f", resultClimbDistance);
            
        }
        
        
    }else{
        
        //ACweightClimb      
        //NSLog(@"acWeight %.0f", acWeight ); 
        
        float climbACWeightUsedLow, climbACWeightUsedHigh;
        
        NSArray* climbWeightDataLow  = [[componentItems objectAtIndex:1] componentsSeparatedByString:@"|"];        
        //NSLog(@"climbWeightData %@", climbWeightData );         
        float climbACweightLow = [[climbWeightDataLow objectAtIndex:0] floatValue];
        //NSLog(@"climbACweightLow %.0f", climbACweightLow ); 
        
        NSArray* climbWeightDataMed  = [[componentItems objectAtIndex:2] componentsSeparatedByString:@"|"];        
        //NSLog(@"climbWeightData %@", climbWeightData );         
        float climbACweightMed = [[climbWeightDataMed objectAtIndex:0] floatValue];
        //NSLog(@"climbACweightMed %.0f", climbACweightMed ); 
        
        NSArray* climbWeightDataHigh  = [[componentItems objectAtIndex:3] componentsSeparatedByString:@"|"];        
        //NSLog(@"climbWeightData %@", climbWeightData );         
        float climbACweightHigh = [[climbWeightDataHigh objectAtIndex:0] floatValue];
        //NSLog(@"climbACweightHigh %.0f", climbACweightHigh ); 
        
        NSArray* climbWeightDataUsedLow;
        NSArray* climbWeightDataUsedHigh;
        
        
        //NSLog(@"acWeight %.0f", acWeight);
        //NSLog(@"climbACweightMed %.0f", climbACweightMed);
        
        if (acWeight < climbACweightMed) {
            //NSLog(@"case 1");
            climbWeightDataUsedLow = climbWeightDataLow;
            climbWeightDataUsedHigh = climbWeightDataMed;
            climbACWeightUsedLow = climbACweightLow;
            climbACWeightUsedHigh = climbACweightMed;
        }else{
            //NSLog(@"case 2");
            climbWeightDataUsedLow = climbWeightDataMed;
            climbWeightDataUsedHigh = climbWeightDataHigh;
            climbACWeightUsedLow = climbACweightMed;
            climbACWeightUsedHigh = climbACweightHigh;
        }
        
        
        
        // get the lower values
        
        //NSLog(@"climbWeightDataUsedLow %@", climbWeightDataUsedLow );     
        //NSLog(@"climbWeightDataUsedHigh %@", climbWeightDataUsedHigh ); 
        //NSLog(@"climbACWeightUsedLow %.0f", climbACWeightUsedLow ); 
        //NSLog(@"climbACWeightUsedHigh %.0f", climbACWeightUsedHigh ); 
        
        // look for correct PA 
        NSArray *PAdataComponents;
        int foundClimbData = 0;
        float lowPA;
        float highPA; 
        
        float interpolatedTAS= 0, interpolatedTAS2 = 0;
        float interpolatedRoC= 0, interpolatedRoC2= 0;
        float interpolatedTime= 0, interpolatedTime2= 0;
        float interpolatedFuel= 0, interpolatedFuel2= 0;
        float interpolatedDistance= 0, interpolatedDistance2= 0;           
        
        for (int i = 1; i < climbWeightDataUsedLow.count ; i++) {       
            PAdataComponents = [[climbWeightDataUsedLow objectAtIndex:i] componentsSeparatedByString:@","]; 
            //NSLog(@"PAdataComponents %@", PAdataComponents );        
            lowPA = [[PAdataComponents objectAtIndex:0] floatValue];
            highPA = [[PAdataComponents objectAtIndex:1] floatValue];
            if (climbPressureAltUsed >=lowPA & climbPressureAltUsed < highPA) {
                //NSLog(@"found PA data %@", PAdataComponents ); 
                foundClimbData = 1;
                break;
            }       
        }
        
        //NSLog(@"foundClimbData %d", foundClimbData);
        
        
        if (foundClimbData == 0) {
            //NSLog(@"error no climb data!!"); 
        }else{
            
            float lowTAS =  [[PAdataComponents objectAtIndex:2] floatValue];
            float highTAS = [[PAdataComponents objectAtIndex:3] floatValue];        
            float lowRoC =  [[PAdataComponents objectAtIndex:4] floatValue];
            float highRoC = [[PAdataComponents objectAtIndex:5] floatValue];        
            float lowTime =  [[PAdataComponents objectAtIndex:6] floatValue];
            float highTime = [[PAdataComponents objectAtIndex:7] floatValue];        
            float lowFuel =  [[PAdataComponents objectAtIndex:8] floatValue];
            float highFuel = [[PAdataComponents objectAtIndex:9] floatValue];        
            float lowDistance =  [[PAdataComponents objectAtIndex:10] floatValue];
            float highDistance = [[PAdataComponents objectAtIndex:11] floatValue];       
            
            
            //NSLog(@"lowTime %.1f", lowTime);
            //NSLog(@"highTime %.1f", highTime);
            //NSLog(@"climbPressureAltUsed %.1f", climbPressureAltUsed);
            
            interpolatedTAS   = lowTAS  + ( (highTAS-lowTAS) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedRoC   = lowRoC  + ( (highRoC-lowRoC) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedTime  = lowTime  + ( (highTime-lowTime) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedFuel  = lowFuel  + ( (highFuel-lowFuel) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedDistance  = lowDistance  + ( (highDistance-lowDistance) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));                
            //NSLog(@"interpolatedTAS %.1f", interpolatedTAS); 
            //NSLog(@"interpolatedRoC %.1f", interpolatedRoC);
            //NSLog(@"1 interpolatedTime %.1f", interpolatedTime);
            //NSLog(@"interpolatedFuel %.1f", interpolatedFuel);
            //NSLog(@"interpolatedDistance %.1f", interpolatedDistance);
            
            
            
            
            
        }
        
        
        
        // do hight AC weight
        
        for (int i = 1; i < climbWeightDataUsedHigh.count ; i++) {       
            PAdataComponents = [[climbWeightDataUsedHigh objectAtIndex:i] componentsSeparatedByString:@","]; 
            //NSLog(@"PAdataComponents %@", PAdataComponents );        
            lowPA = [[PAdataComponents objectAtIndex:0] floatValue];
            highPA = [[PAdataComponents objectAtIndex:1] floatValue];
            if (climbPressureAltUsed >=lowPA & climbPressureAltUsed < highPA) {
                //NSLog(@"found PA data %@", PAdataComponents ); 
                foundClimbData = 1;
                break;
            }       
        }
        
        if (foundClimbData == 0) {
            //NSLog(@"error no climb data!!"); 
        }else{
            
            float lowTAS =  [[PAdataComponents objectAtIndex:2] floatValue];
            float highTAS = [[PAdataComponents objectAtIndex:3] floatValue];        
            float lowRoC =  [[PAdataComponents objectAtIndex:4] floatValue];
            float highRoC = [[PAdataComponents objectAtIndex:5] floatValue];        
            float lowTime =  [[PAdataComponents objectAtIndex:6] floatValue];
            float highTime = [[PAdataComponents objectAtIndex:7] floatValue];        
            float lowFuel =  [[PAdataComponents objectAtIndex:8] floatValue];
            float highFuel = [[PAdataComponents objectAtIndex:9] floatValue];        
            float lowDistance =  [[PAdataComponents objectAtIndex:10] floatValue];
            float highDistance = [[PAdataComponents objectAtIndex:11] floatValue];       
            
            interpolatedTAS2  = lowTAS  + ( (highTAS-lowTAS) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedRoC2  = lowRoC  + ( (highRoC-lowRoC) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedTime2  = lowTime  + ( (highTime-lowTime) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedFuel2  = lowFuel  + ( (highFuel-lowFuel) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));
            interpolatedDistance2  = lowDistance  + ( (highDistance-lowDistance) / (highPA - lowPA) * (climbPressureAltUsed - lowPA));                
            //NSLog(@"interpolatedTAS %.1f", interpolatedTAS2); 
            //NSLog(@"interpolatedRoC2 %.1f", interpolatedRoC2);
            //NSLog(@"interpolatedTime %.1f", interpolatedTime2);
            //NSLog(@"interpolatedFuel %.1f", interpolatedFuel2);
            //NSLog(@"interpolatedDistance %.1f", interpolatedDistance2);
            
        }
        
        
        // interpolate for AC weight
        
        float acWeightForInterpolation = acWeight;
        
        if (acWeightForInterpolation < climbACweightLow) {
            acWeightForInterpolation =  climbACweightLow;
        }
        
        
        
        resultClimbSpeed= interpolatedTAS2  + ( (interpolatedTAS2-interpolatedTAS) / (climbACWeightUsedLow - climbACWeightUsedHigh) * (acWeightForInterpolation - climbACWeightUsedLow));    
        resultClimbRoC = interpolatedRoC2  + ( (interpolatedRoC2-interpolatedRoC) / (climbACWeightUsedLow - climbACWeightUsedHigh) * (acWeightForInterpolation - climbACWeightUsedLow));
        resultClimbTime = interpolatedTime2  + ( (interpolatedTime2-interpolatedTime) / (climbACWeightUsedLow - climbACWeightUsedHigh) * (acWeightForInterpolation - climbACWeightUsedLow));
        resultClimbFuel = interpolatedFuel2 + ( (interpolatedFuel2-interpolatedFuel) / (climbACWeightUsedLow - climbACWeightUsedHigh) * (acWeightForInterpolation - climbACWeightUsedLow));
        resultClimbDistance = interpolatedDistance2 + ( (interpolatedDistance2-interpolatedDistance) / (climbACWeightUsedLow - climbACWeightUsedHigh) * (acWeightForInterpolation - climbACWeightUsedLow));
        
        //NSLog(@"resultClimbRoC %.1f", resultClimbRoC);
        //NSLog(@"resultClimbDistance %.1f", resultClimbDistance);
        
        if (isnan(resultClimbTime)) {
            resultClimbTime = 0;
        }
        
        if (isnan(resultClimbFuel)) {
            resultClimbFuel = 0;
        }
        
        if (isnan(resultClimbDistance)) {
            resultClimbDistance = 0;
        }
        
        //NSLog(@"resultClimbTime %.0f", resultClimbTime);
        //NSLog(@"resultClimbFuel %.0f", resultClimbFuel);
        //NSLog(@"resultClimbDistance %.0f", resultClimbDistance);
        
    }
    
    
    

    
}

- (void) computeClimbIfRocDataOnly : (NSString*)climbACmodel {
    
    //NSLog(@"computeClimbIfRocDataOnly %@",climbACmodel );
    
    
    minPAforThisComputation = 0;
    
    if (_viewForClimbGrid.layer.sublayers.count < 1 || previousmMaxPAforThisComputation != maxPAforThisComputation) {
        [self createGraphicsClimb];
    }
    
    float climbStartPressureAlt = Hp;
    if (climbStartPressureAlt > maxPAforThisComputation) {
        climbStartPressureAlt = maxPAforThisComputation;
    }
    if (climbStartPressureAlt < minPAforThisComputation) {
        climbStartPressureAlt = minPAforThisComputation;
    }
    
    
    //NSLog(@"computeClimbUniversal");
    
    //NSLog(@"headWindKTS %f", headWindKTS); // climb End
    //NSLog(@"IAS %f", IAS); // Wind Component Head/Tail
    //NSLog(@"RATINGINDEX %f", RATINGINDEX); // Wind Component Head/Tail
    //NSLog(@"PROPRPM %f", PROPRPM); // not used
    
    
    
    float windComponentClimb = headWindKTS;
    if (windComponentClimb < 0) {
        _labelHeadWindClimb.text = [[NSString alloc] initWithFormat:@"%.0f kts", windComponentClimb * -1 ];
    }else{
        _labelHeadWindClimb.text = [[NSString alloc] initWithFormat:@"%.0f kts", windComponentClimb ];
    }
    
    if (windComponentClimb >= 1) {
        _labelWindTypeClimb.text = @"Headwind Component";
        _labelWindTypeClimb.textColor = yellowSpecialColor;
        _labelHeadWindClimb.textColor = yellowSpecialColor;
    }
    if (windComponentClimb <= -1) {
        _labelWindTypeClimb.text = @"Tailwind Component !!";
        _labelWindTypeClimb.textColor =yellowSpecialColor;
        _labelHeadWindClimb.textColor = yellowSpecialColor;
    }
    if (windComponentClimb > -1 & windComponentClimb < 1) {
        _labelHeadWindClimb.hidden = YES;
        _labelWindTypeClimb.text = @"No Wind";
        _labelWindTypeClimb.textColor = [UIColor whiteColor];
        _labelHeadWindClimb.textColor = [UIColor whiteColor];
    }else{
        _labelHeadWindClimb.hidden = NO;
    }
    
    //NSLog(@"infoArray %@", infoArray);
    
    NSString *compString = @"";
    calcPerfC172 *_calcPerfC172= [[calcPerfC172 alloc]init];
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location == NSNotFound  ) { 
        // only for Cessna and piper stored computations        
        compString = [infoArray objectAtIndex:6];         
    }
    
    
    
    // send data for climb end 
    float climbEndElevationMSL = IAS;
    
    
    
    
    float MSL = climbEndElevationMSL;    
    float paCalc = ((29.92 - altimeterInches) *1000);
    if (paCalc < 0.001 & paCalc > -0.001) {
        paCalc = 0;
    }
    
    float climbEndPressureAlt = MSL + paCalc;
    
    if (climbEndPressureAlt > maxPAforThisComputation) {
        climbEndPressureAlt = maxPAforThisComputation;
    }
    if (climbEndPressureAlt < minPAforThisComputation) {
        climbEndPressureAlt = minPAforThisComputation;
    }
    
    // send data for climb start  
    
    //NSLog(@"climb start +++++++++++++++");
    
    float OATClimbStart = OAT; 
    
    float ISAatClimbStart   = 15 - (1.98 * (climbStartPressureAlt/1000)); 
    OATClimbStart = ISAatClimbStart + ISADiff;             
    //NSLog(@"climbStartPressureAlt %.0f", climbStartPressureAlt);             
    //NSLog(@"OATClimbStart %.0f", OATClimbStart);
    
    // animateClimb    
    [_viewForClimbAnimations.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    float climbStep = climbEndPressureAlt - climbStartPressureAlt / 4;
    
    float totalClimbTime = 0;
    float totalDistanceClimbed = 0;
    float totalFuelClimbed = 0;
    
    climbStep = (climbEndPressureAlt - Hp) / 4;      
    for (int i = 0; i < 4 ; i++) {
        
        float climbPortionStart = climbStartPressureAlt + (i*climbStep);
        //NSLog(@"climbPortionStart %.0f", climbPortionStart);
        
        float climbPortionEnd = climbStartPressureAlt + ((i+1)*climbStep);
        //NSLog(@"climbPortionEnd %.0f", climbPortionEnd);
        
        float ISAatClimbEnd   = 15 - (1.98 * (climbPortionEnd/1000)); 
        float OATClimbEndPortion = ISAatClimbEnd + ISADiff;
        
         [_calcPerfC172 fwValueTransfer:OATClimbEndPortion sendPA:climbPortionEnd  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:acWeight sendACType:AC_Type sendComputation:compString];  
        
       
        
        float resultClimbRoCStart = resultClimbRoC;
        float resultClimbTimePortion = (climbPortionEnd -climbPortionStart) / resultClimbRoC; 
        float resultClimbFuelPortion = 10.0 * (resultClimbTimePortion/60);
        float resultClimbDistancePortion = (resultClimbTimePortion/60) * (80-headWindKTS);
        float resultClimbSpeedPortion = 80;
        
        totalFuelClimbed = totalFuelClimbed + resultClimbFuelPortion;
     
        //NSLog(@"resultClimbRoCStart %.1f", resultClimbRoCStart);
        //NSLog(@"resultClimbTimePortion %.1f", resultClimbTimePortion);
        //NSLog(@"resultClimbFuelPortion %.1f", resultClimbFuelPortion);
        //NSLog(@"resultClimbDistancePortion %.1f", resultClimbDistancePortion);
        //NSLog(@"resultClimbSpeedPortion %.1f", resultClimbSpeedPortion);
             
        totalClimbTime = totalClimbTime + resultClimbTimePortion;
        
        float xPixelDiffClimbStart =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * (totalDistanceClimbed  ) ;
        float yPixelDiffClimbStart =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * climbPortionStart );     
        float xPixelDiffClimbEnd =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * (totalDistanceClimbed + resultClimbDistancePortion  ) ;
        float yPixelDiffClimbEnd =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * climbPortionEnd );
        
        //NSLog(@"totalDistanceClimbed %.1f", totalDistanceClimbed);
        //NSLog(@"xPixelDiffClimbStart %.1f", xPixelDiffClimbStart);
        
        
        // climb line climb portion only
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( 5 + xPixelDiffClimbStart, yPixelDiffClimbStart )];
        [path addLineToPoint:CGPointMake( 5 + xPixelDiffClimbEnd, yPixelDiffClimbEnd ) ];
        
        CAShapeLayer *shapeLayerRedLine = [CAShapeLayer layer];
        shapeLayerRedLine.path = [path CGPath];
        shapeLayerRedLine.strokeColor = [[UIColor redColor] CGColor];
        shapeLayerRedLine.lineWidth = 8.0;
        shapeLayerRedLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewForClimbAnimations.layer addSublayer:shapeLayerRedLine];   
        
        
        totalDistanceClimbed = totalDistanceClimbed + resultClimbDistancePortion;
       
    }   
    
    
    
    
    [_calcPerfC172 fwValueTransfer:OATClimbStart sendPA:climbStartPressureAlt  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:acWeight sendACType:AC_Type sendComputation:compString];   
    
    
    float ACmassForClimbSpeed =  acWeight * 2.2046;   
    float climbAirspeed =0;
    if (ACmassForClimbSpeed <= 1874) {
        climbAirspeed = 60;
    }        
    if (ACmassForClimbSpeed > 1874 & ACmassForClimbSpeed <= 2205) {
        climbAirspeed = 68;
    }        
    if (ACmassForClimbSpeed > 2205 & ACmassForClimbSpeed <= 2535) {
        climbAirspeed = 73;
    }        
    if (ACmassForClimbSpeed > 2535 ) {
        climbAirspeed = 76;
    }
    
    float yIn = climbAirspeed;            
    float climbCAS = (-9.52292899408279E-06 * powf(yIn, 3) )  +  (0.00320987426035501 * powf(yIn, 2) )   + ( 0.595170118343197  * yIn ) + 20.407174556213 ;            
    //NSLog (@"climbCAS %@ ", [ [NSString alloc] initWithFormat:@"%.1f", climbCAS]);            
    float KIASclimb = climbCAS / pow((1-6.8755856 * pow(10,-6) * climbStartPressureAlt),2.12794);  // should be density alt
    
    
    float resultClimbTimeStart = climbStartPressureAlt / resultClimbRoC; 
    float resultClimbFuelStart = 10.0 * (resultClimbTimeStart/60);
    float resultClimbDistanceStart = (resultClimbTime/60) * KIASclimb;
    float resultClimbSpeedStart = resultClimbDistanceStart / (resultClimbTimeStart/60); 
    if (isnan(resultClimbSpeedStart)) {
        resultClimbSpeedStart = climbAirspeed;
    }
    
    float resultClimbRoCStart = resultClimbRoC;
    
    
    float OATClimbEnd = OAT;        
    float ISAatClimbEnd   = 15 - (1.98 * (climbEndPressureAlt/1000)); 
    OATClimbEnd = ISAatClimbEnd + ISADiff;             
    
    [_calcPerfC172 fwValueTransfer:OATClimbEnd sendPA:climbEndPressureAlt  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:acWeight sendACType:AC_Type sendComputation:compString];  
    
    
    
    ACmassForClimbSpeed =  acWeight * 2.2046;   
    climbAirspeed =0;
    if (ACmassForClimbSpeed <= 1874) {
        climbAirspeed = 60;
    }        
    if (ACmassForClimbSpeed > 1874 & ACmassForClimbSpeed <= 2205) {
        climbAirspeed = 68;
    }        
    if (ACmassForClimbSpeed > 2205 & ACmassForClimbSpeed <= 2535) {
        climbAirspeed = 73;
    }        
    if (ACmassForClimbSpeed > 2535 ) {
        climbAirspeed = 76;
    }
    
     yIn = climbAirspeed;            
     climbCAS = (-9.52292899408279E-06 * powf(yIn, 3) )  +  (0.00320987426035501 * powf(yIn, 2) )   + ( 0.595170118343197  * yIn ) + 20.407174556213 ;            
    //NSLog (@"climbCAS %@ ", [ [NSString alloc] initWithFormat:@"%.1f", climbCAS]);            
     KIASclimb = climbCAS / pow((1-6.8755856 * pow(10,-6) * climbEndPressureAlt),2.12794);  // should be density alt
    
    float resultClimbRoCEnd = resultClimbRoC;
    float resultClimbTimeEnd = totalClimbTime; 
    float resultClimbFuelEnd = totalFuelClimbed;
    float resultClimbDistanceEnd = totalDistanceClimbed;
    float resultClimbSpeedEnd = KIASclimb; 
    
   
    
    
    //NSLog(@"OATpercent %f", OATpercent);
    
    

    float windDistanceSubtract = ((resultClimbTimeEnd )/60) * windComponentClimb; // affects only the DISTANCE!
    
    _iClimbTimeEnd.text = [[NSString alloc] initWithFormat:@"%.1f min", resultClimbTimeEnd ];
    if ([fuelEnterMode isEqualToString:@"volume"]) {
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f ltr", (resultClimbFuelEnd ) * 3.7854];
        }else{
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f gal", resultClimbFuelEnd ];
        }
    }
    if ([fuelEnterMode isEqualToString:@"mass"]) {        
        float lbsFromGallons =  (resultClimbFuelEnd ) * 6.0;        
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f kg", lbsFromGallons / 2.2046];
        }else{
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f lbs", lbsFromGallons];
        }
    }
    
    _iClimbDistanceEnd.text = [[NSString alloc] initWithFormat:@"%.1f %@", (resultClimbDistanceEnd  - windDistanceSubtract) * conversionNNMtoKM, unitDistanceNMkm];    
    _iClimbPAEnd.text = [[NSString alloc] initWithFormat:@"%.0f'", climbEndPressureAlt];
    _iClimbSpeedEnd.text = [[NSString alloc] initWithFormat:@"%.1f KIAS", resultClimbSpeedEnd];
    _iClimbRoCdEnd.text = [[NSString alloc] initWithFormat:@"%.0f ft/min", resultClimbRoCEnd];
    
    
    
    float climbTimeEnd = resultClimbTimeEnd ;
    float climbFuelEnd = resultClimbFuelEnd ;
    climbDistanceEnd = resultClimbDistanceEnd  - windDistanceSubtract;
    
   
    
    
    
    
    
    
    
    windDistanceSubtract = ((resultClimbTime )/60) * windComponentClimb; // affects only the DISTANCE!
    
    _iClimbTimeStart.text = [[NSString alloc] initWithFormat:@"%.1f min", resultClimbTimeStart];    
    if ([fuelEnterMode isEqualToString:@"volume"]) {
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f ltr", (resultClimbFuel) * 3.7854];
        }else{
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f gal", resultClimbFuel ];
        }
    }
    if ([fuelEnterMode isEqualToString:@"mass"]) {        
        float lbsFromGallons =  (resultClimbFuel ) * 6.0;        
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f kg", lbsFromGallons / 2.2046];
        }else{
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f lbs", lbsFromGallons];
        }
    }
    
    
    _iClimbDistanceStart.text = [[NSString alloc] initWithFormat:@"%.1f %@", (resultClimbDistanceStart  - windDistanceSubtract) * conversionNNMtoKM, unitDistanceNMkm];
    _iClimbPAStart.text = [[NSString alloc] initWithFormat:@"%.0f'", Hp];
    _iClimbSpeedStart.text = [[NSString alloc] initWithFormat:@"%.1f KIAS", resultClimbSpeedStart];
    _iClimbRoCdStart.text = [[NSString alloc] initWithFormat:@"%.0f ft/min", resultClimbRoCStart];
    
    
    
    float climbTimeStart = resultClimbTimeStart ;
    float climbFuelStart = resultClimbFuelStart ;
    climbDistanceStart = resultClimbDistanceStart  - windDistanceSubtract ;
    
   
    _iClimbTimeTotal.text = [[NSString alloc] initWithFormat:@"%.1f min", climbTimeEnd- climbTimeStart];      
    _iClimbDistanceTotal.text = [[NSString alloc] initWithFormat:@"%.1f %@", (climbDistanceEnd- climbDistanceStart) * conversionNNMtoKM, unitDistanceNMkm];
    resultClimbDistanceTotal = (climbDistanceEnd- climbDistanceStart);
    
    
    
    if ([fuelEnterMode isEqualToString:@"volume"]) {
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f ltr", (climbFuelEnd- climbFuelStart) * 3.7854];
        }else{
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f gal", (climbFuelEnd- climbFuelStart) ];
        }
    }
    if ([fuelEnterMode isEqualToString:@"mass"]) {        
        float lbsFromGallons =  (climbFuelEnd- climbFuelStart) * 6.0;        
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f kg", lbsFromGallons / 2.2046];
        }else{
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f lbs", lbsFromGallons];
        }
    }
    
    Climb_FuelTotal = [_iClimbFuelTotal.text floatValue] ;
    
    // position aircraft    
    float xPixelDiffClimb =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * climbDistanceStart ;
    float yPixelDiffClimb =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * climbStartPressureAlt );    
    
    if (isnan(xPixelDiffClimb)) {
        xPixelDiffClimb = 1;
    }
    if (isnan(yPixelDiffClimb)) {
        yPixelDiffClimb = 1;
    }
    
    
    _symACClimb1.center = CGPointMake( xPixelDiffClimb+80, yPixelDiffClimb + 10);
    
    
    
    xPixelDiffClimb =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * climbDistanceEnd ;
    yPixelDiffClimb =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * climbEndPressureAlt ); 
    
    if (isnan(xPixelDiffClimb)) {
        xPixelDiffClimb = 1;
    }
    if (isnan(yPixelDiffClimb)) {
        yPixelDiffClimb = 1;
    }
    
    
    _symACClimb2.center = CGPointMake( xPixelDiffClimb + 80, yPixelDiffClimb + 10);
    
    
    
    _iCessna172ISATempCorrection.text = [[NSString alloc] initWithFormat:@"ISA Temp Correction* = %.0f ºC", (ISADiff)];
    _iCessna172ISATempCorrection.textColor = [UIColor whiteColor];
    _labelClimbTempCorrectionInfo.text = @"";
        
    
    
    
    
}

- (void) computeClimbUniversal : (NSString*)climbACmodel {
    
    
    
    //NSLog(@"computeClimbUniversal %@",climbACmodel );
    
     if ([[infoArray objectAtIndex: 0] rangeOfString:@"FXX"].location == NSNotFound  ) { 
         
         if (displayWindow - 100 == actualButtonNumber) {
             // do this only if climb chart is open
             ViewController *parent = (ViewController *)self.parentViewController;    
             if (parent.sliderMSL.value > parent.sliderIAS.value  ) {
                 if (flagClimbEndMustBeHigherThanElevation == 1) {
                     flagClimbEndMustBeHigherThanElevation = 0;            
                     parent.sliderMSL.value = parent.sliderIAS.value - 200;
                 }else{
                     parent.sliderIAS.value = parent.sliderMSL.value + 200;
                 }            
             } 
         }  
         
     }
    
         
   
    minPAforThisComputation = 0;
    
    if (_viewForClimbGrid.layer.sublayers.count < 1 || previousmMaxPAforThisComputation != maxPAforThisComputation) {
         [self createGraphicsClimb];
    }
    
 
    //NSLog(@"computeClimbUniversal");
    
    //NSLog(@"headWindKTS %f", headWindKTS); // climb End
    //NSLog(@"IAS %f", IAS); // Wind Component Head/Tail
    //NSLog(@"RATINGINDEX %f", RATINGINDEX); // Wind Component Head/Tail
    //NSLog(@"PROPRPM %f", PROPRPM); // not used
    
   
    
    float windComponentClimb = headWindKTS;
    if (windComponentClimb < 0) {
          _labelHeadWindClimb.text = [[NSString alloc] initWithFormat:@"%.0f kts", windComponentClimb * -1 ];
    }else{
          _labelHeadWindClimb.text = [[NSString alloc] initWithFormat:@"%.0f kts", windComponentClimb ];
    }
    
    if (windComponentClimb >= 1) {
        _labelWindTypeClimb.text = @"Headwind Component";
        _labelWindTypeClimb.textColor = yellowSpecialColor;
        _labelHeadWindClimb.textColor = yellowSpecialColor;
    }
    if (windComponentClimb <= -1) {
        _labelWindTypeClimb.text = @"Tailwind Component !!";
        _labelWindTypeClimb.textColor =yellowSpecialColor;
        _labelHeadWindClimb.textColor = yellowSpecialColor;
    }
    if (windComponentClimb > -1 & windComponentClimb < 1) {
        _labelHeadWindClimb.hidden = YES;
        _labelWindTypeClimb.text = @"No Wind";
        _labelWindTypeClimb.textColor = [UIColor whiteColor];
        _labelHeadWindClimb.textColor = [UIColor whiteColor];
    }else{
        _labelHeadWindClimb.hidden = NO;
    }
    
    //NSLog(@"infoArray %@", infoArray);
     
    NSString *compString = @"";
    calcPerfC172 *_calcPerfC172= [[calcPerfC172 alloc]init];
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location == NSNotFound  ) { 
        // only for Cessna and piper stored computations        
        compString = [infoArray objectAtIndex:6];         
    }
    
    
       
      // send data for climb end 
    float climbEndElevationMSL = IAS;
   
   
    
    
    float MSL = climbEndElevationMSL;    
    float paCalc = ((29.92 - altimeterInches) *1000);
    if (paCalc < 0.001 & paCalc > -0.001) {
        paCalc = 0;
    }
    
    float climbEndPressureAlt = MSL + paCalc;
    
    if (climbEndPressureAlt > maxPAforThisComputation) {
        climbEndPressureAlt = maxPAforThisComputation;
    }
    if (climbEndPressureAlt < minPAforThisComputation) {
        climbEndPressureAlt = minPAforThisComputation;
    }
    
   
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  ) { 
        
        // if this is a diamond etc...
        
        climbPressureAltUsed = climbEndPressureAlt;
        
        [self computeClimbTimeFuelDistance];
        
           
    }else{
       //old custom fixed wing 
        
        //NSLog(@"climb end +++++++++++++++");
 
        
       [_calcPerfC172 fwValueTransfer:OAT sendPA:climbEndPressureAlt  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:acWeight sendACType:AC_Type sendComputation:compString];  
                 
     }
    
   
    
   
    
    //NSLog(@"OATpercent %f", OATpercent);
    
    int flagDoNotAddOATPercent = 0;
    //add ISA correction
     if (arrayFixedWingSetup.count > 2) {
      
         if ([[arrayFixedWingSetup objectAtIndex:8] isEqualToString:@"no"]) {
             //no ISA correction
             _iCessna172ISATempCorrection.text = @"All values for ISA temp.";
             _iCessna172ISATempCorrection.textColor = [UIColor whiteColor];
             _labelClimbTempCorrectionInfo.text = @"";
         }else{
             _iCessna172ISATempCorrection.text = [[NSString alloc] initWithFormat:@"ISA Temp Correction* = %.0f %%", (ISADiff)];
                     if (ISADiff !=0.0) {
                         _iCessna172ISATempCorrection.textColor = yellowSpecialColor;
                     }else{
                         _iCessna172ISATempCorrection.textColor = [UIColor whiteColor];
                     }             
         }
         
     }else{
         if ([   AC_Type  rangeOfString:@"C172"].location != NSNotFound 
             || [AC_Type  rangeOfString:@"SR22"].location != NSNotFound   
             || [AC_Type  rangeOfString:@"DA42"].location != NSNotFound 
             || [AC_Type  rangeOfString:@"C152"].location != NSNotFound
             || [AC_Type  rangeOfString:@"C182"].location != NSNotFound
             
                                                                         ) {
             _iCessna172ISATempCorrection.text = [[NSString alloc] initWithFormat:@"ISA Temp Correction* = %.0f %%", (ISADiff)];
             if (ISADiff !=0.0) {
                 _iCessna172ISATempCorrection.textColor = yellowSpecialColor;
             }else{
                 _iCessna172ISATempCorrection.textColor = [UIColor whiteColor];
             }
         }else if ([AC_Type  rangeOfString:@"PA28"].location != NSNotFound  ){
             flagDoNotAddOATPercent = 1;
             _iCessna172ISATempCorrection.text = [[NSString alloc] initWithFormat:@"ISA Temp Correction* = %.0f ºC", (ISADiff)];
             _iCessna172ISATempCorrection.textColor = [UIColor whiteColor];
             _labelClimbTempCorrectionInfo.text = @"";
                   
            }else{
             //no ISA correction
             _iCessna172ISATempCorrection.text = @"All values for ISA temp.";
             _iCessna172ISATempCorrection.textColor = [UIColor whiteColor];
             _labelClimbTempCorrectionInfo.text = @"";
         }
         
     }
    
   
    float OATpercent = 1;
    if (flagDoNotAddOATPercent == 1) {
        //do not add 
    }else{
        OATpercent = 1;
        if (ISADiff <=0 ) {
            OATpercent =1;
        }else{
            OATpercent = 1+ ((ISADiff/10)/10);   
        }
        
    }
 
    float windDistanceSubtract = ((resultClimbTime * OATpercent)/60) * windComponentClimb; // affects only the DISTANCE!
    
    _iClimbTimeEnd.text = [[NSString alloc] initWithFormat:@"%.1f min", resultClimbTime * OATpercent ];
    if ([fuelEnterMode isEqualToString:@"volume"]) {
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f ltr", (resultClimbFuel * OATpercent) * 3.7854];
        }else{
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f gal", resultClimbFuel * OATpercent];
        }
    }
    if ([fuelEnterMode isEqualToString:@"mass"]) {        
        float lbsFromGallons =  (resultClimbFuel * OATpercent) * 6.0;        
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f kg", lbsFromGallons / 2.2046];
        }else{
            _iClimbFuelEndt.text = [[NSString alloc] initWithFormat:@"%.1f lbs", lbsFromGallons];
        }
    }
    
    _iClimbDistanceEnd.text = [[NSString alloc] initWithFormat:@"%.1f %@", (resultClimbDistance * OATpercent - windDistanceSubtract) * conversionNNMtoKM, unitDistanceNMkm];
    
    //NSLog(@"(resultClimbDistance * OATpercent - windDistanceSubtract) %.1f", (resultClimbDistance * OATpercent - windDistanceSubtract) * conversionNNMtoKM );

    
    _iClimbPAEnd.text = [[NSString alloc] initWithFormat:@"%.0f'", climbEndPressureAlt];
    _iClimbSpeedEnd.text = [[NSString alloc] initWithFormat:@"%.1f KIAS", resultClimbSpeed];
    _iClimbRoCdEnd.text = [[NSString alloc] initWithFormat:@"%.0f ft/min", resultClimbRoC];
    
    
    
    float climbTimeEnd = resultClimbTime * OATpercent;
    float climbFuelEnd = resultClimbFuel * OATpercent;
    climbDistanceEnd = resultClimbDistance * OATpercent - windDistanceSubtract;
    
    float climbStartPressureAlt = Hp;
    if (climbStartPressureAlt > maxPAforThisComputation) {
        climbStartPressureAlt = maxPAforThisComputation;
    }
    if (climbStartPressureAlt < minPAforThisComputation) {
        climbStartPressureAlt = minPAforThisComputation;
    }
    
   
    
    // send data for climb start  
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  ) { 
        
        // if this is a diamond etc...
        climbPressureAltUsed = climbStartPressureAlt;
        [self computeClimbTimeFuelDistance];        
         
    }else{
        
       [_calcPerfC172 fwValueTransfer:OAT sendPA:climbStartPressureAlt  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:acWeight sendACType:AC_Type sendComputation:compString];   
        
        
    }

 
    
    windDistanceSubtract = ((resultClimbTime * OATpercent)/60) * windComponentClimb; // affects only the DISTANCE!
    
    _iClimbTimeStart.text = [[NSString alloc] initWithFormat:@"%.1f min", resultClimbTime * OATpercent];    
    if ([fuelEnterMode isEqualToString:@"volume"]) {
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f ltr", (resultClimbFuel * OATpercent) * 3.7854];
        }else{
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f gal", resultClimbFuel * OATpercent];
        }
    }
    if ([fuelEnterMode isEqualToString:@"mass"]) {        
        float lbsFromGallons =  (resultClimbFuel * OATpercent) * 6.0;        
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f kg", lbsFromGallons / 2.2046];
        }else{
            _iClimbFuelStart.text = [[NSString alloc] initWithFormat:@"%.1f lbs", lbsFromGallons];
        }
    }    

    _iClimbDistanceStart.text = [[NSString alloc] initWithFormat:@"%.1f %@", (resultClimbDistance * OATpercent - windDistanceSubtract) * conversionNNMtoKM, unitDistanceNMkm];
    _iClimbPAStart.text = [[NSString alloc] initWithFormat:@"%.0f'", Hp];
    _iClimbSpeedStart.text = [[NSString alloc] initWithFormat:@"%.1f KIAS", resultClimbSpeed];
    _iClimbRoCdStart.text = [[NSString alloc] initWithFormat:@"%.0f ft/min", resultClimbRoC];
    
   
    
    float climbTimeStart = resultClimbTime * OATpercent;
    float climbFuelStart = resultClimbFuel * OATpercent;
    climbDistanceStart = resultClimbDistance * OATpercent - windDistanceSubtract ;
    
    _iClimbTimeTotal.text = [[NSString alloc] initWithFormat:@"%.1f min", climbTimeEnd- climbTimeStart];      
    _iClimbDistanceTotal.text = [[NSString alloc] initWithFormat:@"%.1f %@", (climbDistanceEnd- climbDistanceStart) * conversionNNMtoKM, unitDistanceNMkm];
    resultClimbDistanceTotal = (climbDistanceEnd- climbDistanceStart);
    
    
    if ([fuelEnterMode isEqualToString:@"volume"]) {
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f ltr", (climbFuelEnd- climbFuelStart) * 3.7854];
        }else{
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f gal", (climbFuelEnd- climbFuelStart) ];
        }
    }
    if ([fuelEnterMode isEqualToString:@"mass"]) {        
        float lbsFromGallons =  (climbFuelEnd- climbFuelStart) * 6.0;        
        if ([selectedUnitForFuel isEqualToString:@"kg"] ) {
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f kg", lbsFromGallons / 2.2046];
        }else{
            _iClimbFuelTotal.text = [[NSString alloc] initWithFormat:@"%.1f lbs", lbsFromGallons];
        }
    }
    
    Climb_FuelTotal = [_iClimbFuelTotal.text floatValue] ;
  
    // position aircraft    
    float xPixelDiffClimb =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * climbDistanceStart ;
    float yPixelDiffClimb =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * climbStartPressureAlt );    
    
    if (isnan(xPixelDiffClimb)) {
        xPixelDiffClimb = 1;
    }
    if (isnan(yPixelDiffClimb)) {
        yPixelDiffClimb = 1;
    }
    
    
    _symACClimb1.center = CGPointMake( xPixelDiffClimb+80, yPixelDiffClimb + 10);
   

    
    xPixelDiffClimb =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * climbDistanceEnd ;
    yPixelDiffClimb =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * climbEndPressureAlt ); 
    
    if (isnan(xPixelDiffClimb)) {
        xPixelDiffClimb = 1;
    }
    if (isnan(yPixelDiffClimb)) {
        yPixelDiffClimb = 1;
    }
    
    
    _symACClimb2.center = CGPointMake( xPixelDiffClimb + 80, yPixelDiffClimb + 10);
  
    
    // animateClimb    
    [_viewForClimbAnimations.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    float climbStep = maxPAforThisComputation / 30;
    
    //NSLog(@"maxPAforThisComputation %.0f", maxPAforThisComputation);

    for (int i = 0; i < 30 ; i++) {
       
        float loopClimbPA =  (i * climbStep); 

        if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location == NSNotFound  ) { 
             [_calcPerfC172 fwValueTransfer:OAT sendPA:loopClimbPA  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:0 sendACType:AC_Type sendComputation:compString];
        }else{
            // if this is a diamond etc...            
            climbPressureAltUsed = loopClimbPA;
            [self computeClimbTimeFuelDistance];
        }        
 
       //NSLog(@"climbPressureAltUsed %.0f", climbPressureAltUsed);
        
        float OATpercent = 1;
        if (ISADiff <=0 ) {
            OATpercent =1;
        }else{
            OATpercent = 1+ ((ISADiff/10)/10);   
        }
        float windDistanceSubtract = ((resultClimbTime * OATpercent)/60) * windComponentClimb; // affects only the DISTANCE!
     
        float xPixelDiffClimbStart =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * (resultClimbDistance * OATpercent - windDistanceSubtract) ;
        float yPixelDiffClimbStart =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * loopClimbPA );
        
        i = i +1;
        loopClimbPA =  (i * climbStep);
       
        [_calcPerfC172 fwValueTransfer:OAT sendPA:loopClimbPA  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:0 sendACType:AC_Type sendComputation:compString];
        
        if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location == NSNotFound  ) { 
           [_calcPerfC172 fwValueTransfer:OAT sendPA:loopClimbPA  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:0 sendACType:AC_Type sendComputation:compString];
        }else{
            // if this is a diamond etc...            
            climbPressureAltUsed = loopClimbPA;
            [self computeClimbTimeFuelDistance];
        }   
      
        
        OATpercent = 1;
        if (ISADiff <=0 ) {
            OATpercent =1;
        }else{
            OATpercent = 1+ ((ISADiff/10)/10);   
        }
        windDistanceSubtract = ((resultClimbTime * OATpercent)/60) * windComponentClimb; // affects only the DISTANCE!        
     
        float xPixelDiffClimbEnd =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * (resultClimbDistance * OATpercent - windDistanceSubtract) ;
        float yPixelDiffClimbEnd =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * loopClimbPA );
        
        //climb line blue part
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( 5 + xPixelDiffClimbStart, yPixelDiffClimbStart )];
        [path addLineToPoint:CGPointMake( 5 + xPixelDiffClimbEnd, yPixelDiffClimbEnd ) ];
        
      
        CAShapeLayer *shapeLayerRedLine = [CAShapeLayer layer];
        shapeLayerRedLine.path = [path CGPath];
        shapeLayerRedLine.strokeColor = [verylightBlueColor CGColor];
        shapeLayerRedLine.lineWidth = 4.0;
        shapeLayerRedLine.fillColor = [[UIColor clearColor] CGColor];
        [_viewForClimbAnimations.layer addSublayer:shapeLayerRedLine];   
        
        i = i -1;
    }
    
 
    
    climbStep = (climbEndPressureAlt - Hp) / 20;      
    for (int i = 1; i < 20 ; i++) {
         
         float loopClimbPA = Hp + (i * climbStep);         
        
         
        if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location == NSNotFound  ) { 
            [_calcPerfC172 fwValueTransfer:OAT sendPA:loopClimbPA  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:0 sendACType:AC_Type sendComputation:compString];
        }else{
            // if this is a diamond etc...            
            climbPressureAltUsed = loopClimbPA;
            [self computeClimbTimeFuelDistance];
        }  
        
        
         float OATpercent = 1;
         if (ISADiff <=0 ) {
             OATpercent =1;
         }else{
             OATpercent = 1+ ((ISADiff/10)/10);   
         }
         float windDistanceSubtract = ((resultClimbTime * OATpercent)/60) * windComponentClimb; // affects only the DISTANCE!         
       
        
         float xPixelDiffClimbStart =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * (resultClimbDistance * OATpercent - windDistanceSubtract) ;
         float yPixelDiffClimbStart =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * loopClimbPA );
        
        //NSLog(@"xPixelDiffClimbStart %.0f", xPixelDiffClimbStart);
        
         i = i +1;
         loopClimbPA = Hp + (i * climbStep);
        
        if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location == NSNotFound  ) { 
             [_calcPerfC172 fwValueTransfer:OAT sendPA:loopClimbPA  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headWindKTS  sendACweight:0 sendACType:AC_Type sendComputation:compString];
        }else{
            // if this is a diamond etc...            
            climbPressureAltUsed = loopClimbPA;
            [self computeClimbTimeFuelDistance];
        }  
        
        
        
          OATpercent = 1;
         if (ISADiff <=0 ) {
             OATpercent =1;
         }else{
             OATpercent = 1+ ((ISADiff/10)/10);   
         }
         windDistanceSubtract = ((resultClimbTime * OATpercent)/60) * windComponentClimb; // affects only the DISTANCE!
 
         float xPixelDiffClimbEnd =  ( (_viewForClimbGrid.frame.size.width) / climbXaxisEnd) * (resultClimbDistance * OATpercent - windDistanceSubtract) ;
         float yPixelDiffClimbEnd =  ( _viewForClimbGrid.frame.size.height - (_viewForClimbGrid.frame.size.height / climbYaxisEnd) * loopClimbPA );
         
         // climb line climb portion only
         UIBezierPath *path = [UIBezierPath bezierPath];
         [path moveToPoint:CGPointMake( 5 + xPixelDiffClimbStart, yPixelDiffClimbStart )];
         [path addLineToPoint:CGPointMake( 5 + xPixelDiffClimbEnd, yPixelDiffClimbEnd ) ];
                  
         CAShapeLayer *shapeLayerRedLine = [CAShapeLayer layer];
         shapeLayerRedLine.path = [path CGPath];
         shapeLayerRedLine.strokeColor = [[UIColor redColor] CGColor];
         shapeLayerRedLine.lineWidth = 8.0;
         shapeLayerRedLine.fillColor = [[UIColor clearColor] CGColor];
         [_viewForClimbAnimations.layer addSublayer:shapeLayerRedLine];   
         
         i = i -1;
     }   
 
  
    
}

- (void) computeLanding_CessnaC172 {
    
    // wind rule: decrease distances 10% for each 9 knot headwind
    // tailwind up to 10 kts: increase distances by 10% for each 2 knots
    
   
   
    windDirectionLD = IAS;
    
    unitDistance = @"ft";
    unitDistanceNMkm  = @"NM";    
    
    if (_segmentMeterFeetLD.selectedSegmentIndex == 0) {
        conversionFeetToMeter = 1;
        conversionNNMtoKM = 1;  
    }else{
        conversionFeetToMeter = 0.3048;
        unitDistance = @"m";
        unitDistanceNMkm  = @"km";
        conversionNNMtoKM = 1.852;
    }
    
    
    //**************************************************
    //Ground Roll
    //**************************************************
    
    headwindcomponentLD = headWindKTS * cos (  ( windDirectionLD -  _sliderRundwayHeadingLD.value) * 0.01745);
    windSpeedLD = headWindKTS;
    originalGroundRoll = 0;
    penaltyWindGR = 0;
    penaltyRunwayConditionsGR = 0;
    penaltySlopeGR = 0;
    totalGroundRoll = 0;
    
    originalGroundRoll = resultGroundRoll;
    float factorRWYconditions = 1 + (_sliderRunwayConditionsLD.value/100);
    penaltyRunwayConditionsGR = (resultGroundRoll * factorRWYconditions) - resultGroundRoll;
    
    penaltyWindGR = -1 * ((headwindcomponentLD / 9) * (originalGroundRoll *0.1));
    if ([compString rangeOfString:@"PA28"].location != NSNotFound  || [compString rangeOfString:@"DA40-180"].location != NSNotFound ) {        
        penaltyWindGR = resultWindDifferenceGR_LD;        
    }
    penaltySlopeGR = originalGroundRoll *  (_sliderSlopeLD.value /100);
    totalGroundRoll = originalGroundRoll + penaltyWindGR + penaltyRunwayConditionsGR + penaltySlopeGR;
    
    //**************************************************
    //Distance over 50ft
    //**************************************************
    
    originalDistance50ft = 0;
    penaltyWind50ft = 0;
    penaltyRunwayConditions50ft = 0;
    penaltySlope50ft = 0;
    totalDistance50ft = 0;
    
    originalDistance50ft = resultDistanceOverObstacle;
    penaltyRunwayConditions50ft = penaltyRunwayConditionsGR;
    
    penaltyWind50ft = -1 * ((headwindcomponentLD / 9) * (originalDistance50ft *0.1));
    if ([compString rangeOfString:@"PA28"].location != NSNotFound  || [compString rangeOfString:@"DA40-180"].location != NSNotFound) {        
        penaltyWind50ft = resultWindDifference50ft_LD;
    }
    penaltySlope50ft = originalDistance50ft *  (_sliderSlopeLD.value /100);
    totalDistance50ft = originalDistance50ft + penaltyWind50ft + penaltyRunwayConditions50ft + penaltySlope50ft;
    
   
    
}

- (void) computeTakeoff_UniversalFixedWing {
    
    //NSLog(@"computeTakeoff_UniversalFixedWing ");
    
    // wind rule: decrease by 10% for each 14 knots headwind
    // tailwind : increase by 10% for each 3 knots tailwind
    
    
   
  
    
    //NSLog(@"0resultGroundRoll %.0f", resultGroundRoll);
    //NSLog(@"diamond  unitDistance %@", unitDistance);
    //NSLog(@"diamond  conversionFeetToMeter %.3f", conversionFeetToMeter);
    
    //**************************************************
    //Ground Roll
    //**************************************************
   
    
    headwindcomponentTO = windSpeedTO * cos (  ( windDirectionTO -  _sliderRundwayHeadingTO.value) * 0.01745);
    
    originalGroundRoll = 0;
    penaltyWindGR = 0;
    penaltyRunwayConditionsGR = 0;
    penaltySlopeGR = 0;
    totalGroundRoll = 0;
    
    originalGroundRoll = resultTOGroundRoll;
    
    //NSLog(@"1resultGroundRoll %.0f", resultGroundRoll);
    
    float factorRWYconditions = 1 + (_sliderRunwayConditionsTO.value/100);
    penaltyRunwayConditionsGR = (originalGroundRoll * factorRWYconditions) - originalGroundRoll;
    //NSLog(@"_labelCo....");
    
    if (arrayFixedWingSetup.count > 2) {
        //if ([[arrayFixedWingSetup objectAtIndex:8] isEqualToString:@"no"]) {
        
        _labelConditionsTO.text = [arrayFixedWingSetup objectAtIndex:10];
        
        //NSLog(@"_labelConditionsTO.text %@", _labelConditionsTO.text);
        
        if (headwindcomponentTO >=0) {
                        penaltyWindGR = -1 * ((headwindcomponentTO / [[arrayFixedWingSetup objectAtIndex:11]floatValue] ) * (originalGroundRoll*0.1));
                    }else{
                        penaltyWindGR = -1 * ((headwindcomponentTO / [[arrayFixedWingSetup objectAtIndex:12]floatValue]) * (originalGroundRoll*0.1));
                    }
        
    }else{
        
        if ([ AC_Type  rangeOfString:@"DA42"].location != NSNotFound        ) {
             
              _labelConditionsTO.text = @"Conditions: Flaps UP, Power: MAX, Consult POH for Runway Conditions";
             
             // diamond rule:
             //headwind: Decrease by 10% for each 14 kt  
             //tailwind: Increase by 10% for each 3 kt         
             if (headwindcomponentTO >=0) {
                 penaltyWindGR = -1 * ((headwindcomponentTO / 14) * (originalGroundRoll*0.1));
             }else{
                 penaltyWindGR = -1 * ((headwindcomponentTO / 3) * (originalGroundRoll*0.1));
             }
         }
        
        if ([ AC_Type  rangeOfString:@"SR22"].location != NSNotFound      ) {
            
             _labelConditionsTO.text = @"Flaps 50%, Full Throttle, Mixture Set, Consult POH for Runway Conditions.";
            
            // Cirrus rule:
            //headwind: Subtract 10% for each 12 knots headwind.    
            //Add 10% for each 2 knots tailwind up to 10 knots. 
            
            if (headwindcomponentTO >=0) {
                penaltyWindGR = -1 * ((headwindcomponentTO / 12) * (originalGroundRoll*0.1));
            }else{
                penaltyWindGR = -1 * ((headwindcomponentTO / 10) * (originalGroundRoll*0.1));
            }
        }
        
        if ([ AC_Type  rangeOfString:@"P2010"].location != NSNotFound   || [ AC_Type  rangeOfString:@"P2008"].location != NSNotFound  || [ AC_Type  rangeOfString:@"P2006"].location != NSNotFound   ) {
            
            _labelConditionsTO.text = @"Refer to POH";
            
            // Cirrus rule:
            //headwind: Subtract 10% for each 12 knots headwind.    
            //Add 10% for each 2 knots tailwind up to 10 knots. 
            
            if (headwindcomponentTO >=0) {
                penaltyWindGR = -1 * ((headwindcomponentTO / 12) * (originalGroundRoll*0.1));
            }else{
                penaltyWindGR = -1 * ((headwindcomponentTO / 10) * (originalGroundRoll*0.1));
            }
        }
    }
         
            
                
                
                
    
     
    
     //adjust
    
   
    
    penaltySlopeGR = originalGroundRoll *  (_sliderSlopeTO.value /100);
    totalGroundRoll = originalGroundRoll + penaltyWindGR + penaltyRunwayConditionsGR + penaltySlopeGR;
    
    //**************************************************
    //Distance over 50ft
    //**************************************************
    
    originalDistance50ft = 0;
    penaltyWind50ft = 0;
    penaltyRunwayConditions50ft = 0;
    penaltySlope50ft = 0;
    totalDistance50ft = 0;
    
    originalDistance50ft = resultTO50ft;
    penaltyRunwayConditions50ft = penaltyRunwayConditionsGR;
    
    
    if (headwindcomponentTO >=0) {
        penaltyWind50ft = -1 * ((headwindcomponentTO / 14) * (originalDistance50ft*0.1));
    }else{
        penaltyWind50ft = -1 * ((headwindcomponentTO / 3) * (originalDistance50ft*0.1));
    }
    
    penaltySlope50ft = originalDistance50ft *  (_sliderSlopeTO.value /100);
    totalDistance50ft = originalDistance50ft + penaltyWind50ft + penaltyRunwayConditions50ft + penaltySlope50ft;
    
    
}

- (void) computeLanding_UniversalFixedWing {
    
    // wind rule: decrease by 10% for each 14 knots headwind
    // tailwind : increase by 10% for each 3 knots tailwind
    
    
  
    //**************************************************
    //Ground Roll
    //**************************************************
    
    
    headwindcomponentLD = windSpeedLD * cos (  ( windDirectionLD -  _sliderRundwayHeadingLD.value) * 0.01745);
    
    originalGroundRoll = 0;
    penaltyWindGR = 0;
    penaltyRunwayConditionsGR = 0;
    penaltySlopeGR = 0;
    totalGroundRoll = 0;
    
    originalGroundRoll = resultLDGGroundRoll;
    float factorRWYconditions = 1 + (_sliderRunwayConditionsLD.value/100);
    penaltyRunwayConditionsGR = (originalGroundRoll * factorRWYconditions) - originalGroundRoll;
    
    if (arrayFixedWingSetup.count > 2) {
    //if ([[arrayFixedWingSetup objectAtIndex:8] isEqualToString:@"no"]) {
        _labelConditionsLD.text = [arrayFixedWingSetup objectAtIndex:13];
        if (headwindcomponentLD >=0) {
            penaltyWindGR = -1 * ((headwindcomponentLD / [[arrayFixedWingSetup objectAtIndex:14] floatValue] ) * (originalGroundRoll*0.1));
        }else{
            penaltyWindGR = -1 * ((headwindcomponentLD / [[arrayFixedWingSetup objectAtIndex:14] floatValue] ) * (originalGroundRoll*0.1));
        }
    }else{
        if ([ AC_Type  rangeOfString:@"DA42"].location != NSNotFound     ) {
            
            _labelConditionsLD.text = @"Conditions: Flaps: LDG, APP or UP, Power: Both IDLE, Approach Speed: VREF";        
            // diamond rule:
            //headwind: Decrease by 10% for each 14 kt  
            //tailwind: Increase by 10% for each 3 kt         
            if (headwindcomponentLD >=0) {
                penaltyWindGR = -1 * ((headwindcomponentLD / 14) * (originalGroundRoll*0.1));
            }else{
                penaltyWindGR = -1 * ((headwindcomponentLD / 3) * (originalGroundRoll*0.1));
            }
        }
        
        if ([ AC_Type  rangeOfString:@"SR22"].location != NSNotFound      ) {
          
            if ([ AC_Type  rangeOfString:@"SR22TG6"].location != NSNotFound      ) {
                _segmentFlapsLD.hidden = NO;
            }
            _labelConditionsLD.text = @"Conditions: 3deg Power Approach to 50 ft, Consult POH for details!";        
            // Cirrus rule:
            //Headwind - Subtract 10% from table distances for each 13 knots headwind.   
            //Tailwind - Add 10% to table distances for each 2 knots tailwind up to 10 knots.
            
            if (headwindcomponentTO >=0) {
                penaltyWindGR = -1 * ((headwindcomponentTO / 13) * (originalGroundRoll*0.1));
            }else{
                penaltyWindGR = -1 * ((headwindcomponentTO / 2) * (originalGroundRoll*0.1));
            }
        }
        
        if ([ AC_Type  rangeOfString:@"P2010"].location != NSNotFound   || [ AC_Type  rangeOfString:@"P2008"].location != NSNotFound  || [ AC_Type  rangeOfString:@"P2006"].location != NSNotFound   ) {
                    
            _labelConditionsLD.text = @"Conditions: Refer to POH";        
            // Cirrus rule:
            //Headwind - Subtract 10% from table distances for each 13 knots headwind.   
            //Tailwind - Add 10% to table distances for each 2 knots tailwind up to 10 knots.
            
            if (headwindcomponentTO >=0) {
                penaltyWindGR = -1 * ((headwindcomponentTO / 13) * (originalGroundRoll*0.1));
            }else{
                penaltyWindGR = -1 * ((headwindcomponentTO / 2) * (originalGroundRoll*0.1));
            }
        }
        
        
    }
    
    //adjust
    
    
    
    
    
    penaltySlopeGR = originalGroundRoll *  (_sliderSlopeLD.value /100);
    totalGroundRoll = originalGroundRoll + penaltyWindGR + penaltyRunwayConditionsGR + penaltySlopeGR;
    
    //**************************************************
    //Distance over 50ft
    //**************************************************
    
    originalDistance50ft = 0;
    penaltyWind50ft = 0;
    penaltyRunwayConditions50ft = 0;
    penaltySlope50ft = 0;
    totalDistance50ft = 0;
    
    originalDistance50ft = resultLDG50ft;
    penaltyRunwayConditions50ft = penaltyRunwayConditionsGR;
    if (headwindcomponentLD >=0) {
        penaltyWind50ft = -1 * ((headwindcomponentLD / 14) * (originalDistance50ft*0.1));
    }else{
        penaltyWind50ft = -1 * ((headwindcomponentLD / 3) * (originalDistance50ft*0.1));
    }
    penaltySlope50ft = originalDistance50ft *  (_sliderSlopeLD.value /100);
    totalDistance50ft = originalDistance50ft + penaltyWind50ft + penaltyRunwayConditions50ft + penaltySlope50ft;
    
    
}





- (void) drawMarksTO {
    
     [_viewRunwayMarksTO.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    
    float xPos = 0;
    float yPos = 0;
    float lineHeight = 6;
    float xIncrements = 4;
    float distanceLines = _viewRunwayMarksTO.frame.size.width / xIncrements;
    float distanceIncrement = _sliderRunwayLength.value / xIncrements;
    
    for (int i = 0; i < xIncrements+1 ; i++) {
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( xPos + i * distanceLines, yPos )];
        [path addLineToPoint:CGPointMake( xPos + i * distanceLines, yPos+ lineHeight  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];
        shapeLayer.lineWidth = 1.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [_viewRunwayMarksTO.layer addSublayer:shapeLayer];
        
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(xPos + i * distanceLines - 40, 5, 80, 21)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        [label setFont:[UIFont systemFontOfSize:13]];
        NSString *labelText = [[NSString alloc] initWithFormat:@"%.0f%@", i * distanceIncrement * conversionFeetToMeter, unitDistance];
        [label  setText: labelText  ];
       
        [_viewRunwayMarksTO addSubview: label];
    }
    
    
}

- (void) drawMarksLD {
    
    [_viewRunwayMarksLD.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    
    float xPos = 0;
    float yPos = 0;
    float lineHeight = 6;
    float xIncrements = 4;
    float distanceLines = _viewRunwayMarksLD.frame.size.width / xIncrements;
    float distanceIncrement = _sliderRunwayLengthLD.value / xIncrements;
    
    for (int i = 0; i < xIncrements+1 ; i++) {
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake( xPos + i * distanceLines, yPos )];
        [path addLineToPoint:CGPointMake( xPos + i * distanceLines, yPos+ lineHeight  )  ];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];
        shapeLayer.lineWidth = 1.5;
        shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [_viewRunwayMarksLD.layer addSublayer:shapeLayer];
        
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectMake(xPos + i * distanceLines - 40, 5, 80, 21)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        [label setFont:[UIFont systemFontOfSize:13]];
        NSString *labelText = [[NSString alloc] initWithFormat:@"%.0f%@", i * distanceIncrement * conversionFeetToMeter, unitDistance];
        [label  setText: labelText  ];
        
        [_viewRunwayMarksLD addSubview: label];
    }
    
    
}


- (void) animateFixedWingTakeoff {
    
    //NSLog(@"animateFixedWingTakeoff");
    
    _iGroundRoll.text = [[NSString alloc] initWithFormat:@"%.0f %@", originalGroundRoll * conversionFeetToMeter, unitDistance ];
    _iWind.text = [[NSString alloc] initWithFormat:@"%.0f %@", penaltyWindGR * conversionFeetToMeter, unitDistance ];
    _iConditions.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltyRunwayConditionsGR * conversionFeetToMeter, unitDistance ];
    _iSlope.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltySlopeGR * conversionFeetToMeter, unitDistance ];
    _iTotalGroundRoll.text = [[NSString alloc] initWithFormat:@"%.0f %@", totalGroundRoll * conversionFeetToMeter, unitDistance ];
    
    _iDistance50ft.text = [[NSString alloc] initWithFormat:@"%.0f %@", originalDistance50ft * conversionFeetToMeter, unitDistance ];
    _iWind50ft.text = [[NSString alloc] initWithFormat:@"%.0f %@", penaltyWind50ft * conversionFeetToMeter, unitDistance ];
    _iConditions50ft.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltyRunwayConditions50ft * conversionFeetToMeter, unitDistance ];
    _iSlope50ft.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltySlope50ft * conversionFeetToMeter, unitDistance ];
    _iTotalDistance50ft.text = [[NSString alloc] initWithFormat:@"%.0f %@", totalDistance50ft * conversionFeetToMeter, unitDistance ];
    _labelSliderACWeightOverrideTO.text = [[NSString alloc] initWithFormat:@"%.0f %@", _sliderAircraftWeightOverrideTO.value, selectedUnitsForItems ];
    
  
    
    resultTOGroundRoll = totalGroundRoll * conversionFeetToMeter;
    resultTO50ft = totalDistance50ft * conversionFeetToMeter;
    
    
    _labelSliderARunwayConditionsTO.text = [[NSString alloc] initWithFormat:@"%.0f %%", _sliderRunwayConditionsTO.value ];
    _labelSliderRunwayHeadingTO.text = [[NSString alloc] initWithFormat:@"%.0fº", _sliderRundwayHeadingTO.value ];
    _labelSliderSlopeTO.text = [[NSString alloc] initWithFormat:@"%.0f %%", _sliderSlopeTO.value ];
    _labelHeadwindComponentTO.text = [[NSString alloc] initWithFormat:@"%.0f kts", headwindcomponentTO ];
    if (headwindcomponentTO >= 1) {
        _labelWindTypeTO.text = @"Headwind Component";
        _labelWindTypeTO.textColor = [UIColor whiteColor];
        _labelHeadwindComponentTO.textColor = [UIColor whiteColor];
    }
    if (headwindcomponentTO <= -1) {
        _labelWindTypeTO.text = @"Tailwind Component !!";
        _labelWindTypeTO.textColor =yellowSpecialColor;
        _labelHeadwindComponentTO.textColor = yellowSpecialColor;
    }
     if (headwindcomponentTO > -1 & headwindcomponentTO < 1) {
         _labelHeadwindComponentTO.hidden = YES;
         _labelWindTypeTO.text = @"No Wind";
         _labelWindTypeTO.textColor = [UIColor whiteColor];
     }else{
          _labelHeadwindComponentTO.hidden = NO;
     }
    
  
    _symRunway.frame = CGRectMake(_symRunway.frame.origin.x , _symRunway.frame.origin.y , initialRunwayFrameWidth , _symRunway.frame.size.height);
     CGAffineTransform rotateValue = CGAffineTransformMakeRotation( (windDirectionTO-_sliderRundwayHeadingTO.value) * M_PI / 180.0);
     CGAffineTransform scaleValue  = CGAffineTransformMakeScale(1, 1);
    _labelRunwayLength.text = [[NSString alloc] initWithFormat:@"%.0f", _sliderRunwayLength.value * conversionFeetToMeter];
     [self drawMarksTO];
    
    // calc runway stuff
    rotateValue = CGAffineTransformMakeRotation( (_sliderRundwayHeadingTO.value + 90) * M_PI / 180.0);
    _runwayTopViewTO.transform = CGAffineTransformConcat(scaleValue, rotateValue );
    rotateValue = CGAffineTransformMakeRotation( (windDirectionTO) * M_PI / 180.0);
    _windsockTO.transform = CGAffineTransformConcat(scaleValue, rotateValue );
   
    
    
    float runwayLengthPixel = _symRunway.frame.size.width - 20;
    float oneFeetInPixel = runwayLengthPixel / (_sliderRunwayLength.value);
    float distanceInFeetOverObstacle = totalDistance50ft;
    float distanceInPixelOverObstacle = oneFeetInPixel * distanceInFeetOverObstacle;
    _symObstacle.frame = CGRectMake(_symRunway.frame.origin.x + distanceInPixelOverObstacle - (_symObstacle.frame.size.width/2), _symRunway.frame.origin.y + (_symRunway.frame.size.height/2)  -  (_symObstacle.frame.size.height), _symObstacle.frame.size.width, _symObstacle.frame.size.height);
    _symAC2.center = CGPointMake( _symObstacle.frame.origin.x + (_symObstacle.frame.size.width/2), _symObstacle.frame.origin.y - (_symAC2.frame.size.height/3));
   
    float distanceInFeetGroundRoll = totalGroundRoll;
    float distanceInPixelGroundRoll = oneFeetInPixel * distanceInFeetGroundRoll;
    _symAC1.center = CGPointMake( _symRunway.frame.origin.x + 0 + distanceInPixelGroundRoll , _symAC1.center.y);
    
   _labelGroundRoll.text = [[NSString alloc] initWithFormat:@"%.0f%@", distanceInFeetGroundRoll * conversionFeetToMeter, unitDistance ];
   _labelGroundRoll.center = CGPointMake( _symAC1.center.x , _symAC1.center.y - 6);
    
   _labelOverObstacle.text = [[NSString alloc] initWithFormat:@"%.0f%@", distanceInFeetOverObstacle * conversionFeetToMeter, unitDistance ];
   _labelOverObstacle.center = CGPointMake( _symAC2.center.x , _symAC2.center.y - 10);
    
    if (windSpeedTO == 0) {
        _windsockRwyTO.hidden = YES;
        _windsockTO.hidden = YES;
    }else{
        _windsockRwyTO.hidden = NO;
        _windsockTO.hidden = NO;
    }
    
    
     scaleValue  = CGAffineTransformMakeScale(1, 1);
     rotateValue = CGAffineTransformMakeRotation( ((_sliderSlopeTO.value/6)*-1)  * M_PI / 180.0);
    _viewTORunway.layer.anchorPoint = CGPointMake(0.0,0.5);
    _viewTORunway.transform = CGAffineTransformConcat(scaleValue, rotateValue );
    
    UIImage *RWYimage = [UIImage imageNamed:@"Runway3-01.png"];
    [_symRunway setImage:RWYimage];
    if (_sliderRunwayConditionsTO.value > 25 || _sliderSlopeTO.value > 10) {
        UIImage *RWYimage = [UIImage imageNamed:@"RunwayOrange.png"];
        [_symRunway setImage:RWYimage];
    }
    if (_sliderRunwayConditionsTO.value > 80|| _sliderSlopeTO.value > 15) {
        UIImage *RWYimage = [UIImage imageNamed:@"RunwayRed.png"];
        [_symRunway setImage:RWYimage];
        
    }
    
   
}


- (void) animateFixedWingLanding {
    
    //NSLog(@"animateFixedWingLanding");
    //NSLog(@"totalGroundRoll %.0f", totalGroundRoll * conversionFeetToMeter);
    //NSLog(@"conversionFeetToMeter %.3f", conversionFeetToMeter);
    
    
    _iGroundRollLD.text = [[NSString alloc] initWithFormat:@"%.0f %@", originalGroundRoll * conversionFeetToMeter, unitDistance ];
    _iWindLD.text = [[NSString alloc] initWithFormat:@"%.0f %@", penaltyWindGR * conversionFeetToMeter, unitDistance ];
    _iConditionsLD.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltyRunwayConditionsGR * conversionFeetToMeter, unitDistance ];
    _iSlopeLD.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltySlopeGR * conversionFeetToMeter, unitDistance ];
    _iTotalGroundRollLD.text = [[NSString alloc] initWithFormat:@"%.0f %@", totalGroundRoll * conversionFeetToMeter, unitDistance ];
    
    _iDistance50ftLD.text = [[NSString alloc] initWithFormat:@"%.0f %@", originalDistance50ft * conversionFeetToMeter, unitDistance ];
    _iWind50ftLD.text = [[NSString alloc] initWithFormat:@"%.0f %@", penaltyWind50ft * conversionFeetToMeter, unitDistance ];
    _iConditions50ftLD.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltyRunwayConditions50ft * conversionFeetToMeter, unitDistance ];
    _iSlope50ftLD.text = [[NSString alloc] initWithFormat:@"+%.0f %@", penaltySlope50ft * conversionFeetToMeter, unitDistance ];
    _iTotalDistance50ftLD.text = [[NSString alloc] initWithFormat:@"%.0f %@", totalDistance50ft * conversionFeetToMeter, unitDistance ];
    _labelSliderACWeightOverrideLD.text = [[NSString alloc] initWithFormat:@"%.0f %@", _sliderAircraftWeightOverrideLD.value, selectedUnitsForItems ];
    
    resultLDGGroundRoll = totalGroundRoll * conversionFeetToMeter;
    resultLDG50ft = totalDistance50ft * conversionFeetToMeter;
    
    
    _labelSliderARunwayConditionsLD.text = [[NSString alloc] initWithFormat:@"%.0f %%", _sliderRunwayConditionsLD.value ];
    _labelSliderRunwayHeadingLD.text = [[NSString alloc] initWithFormat:@"%.0fº", _sliderRundwayHeadingLD.value ];
    _labelSliderSlopeLD.text = [[NSString alloc] initWithFormat:@"%.0f %%", _sliderSlopeLD.value ];
    _labelHeadwindComponentLD.text = [[NSString alloc] initWithFormat:@"%.0f kts", headwindcomponentLD ];
    if (headwindcomponentLD >= 1) {
        _labelWindTypeLD.text = @"Headwind Component";
        _labelWindTypeLD.textColor = [UIColor whiteColor];
        _labelHeadwindComponentLD.textColor = [UIColor whiteColor];
    }
    if (headwindcomponentLD <= -1) {
        _labelWindTypeLD.text = @"Tailwind Component !!";
        _labelWindTypeLD.textColor =yellowSpecialColor;
        _labelHeadwindComponentLD.textColor = yellowSpecialColor;
    }
    if (headwindcomponentLD > -1 & headwindcomponentLD < 1) {
        _labelHeadwindComponentLD.hidden = YES;
        _labelWindTypeLD.text = @"No Wind";
        _labelWindTypeLD.textColor = [UIColor whiteColor];
    }else{
        _labelHeadwindComponentLD.hidden = NO;
    }
    
    
    _symRunwayLD.frame = CGRectMake(_symRunwayLD.frame.origin.x , _symRunwayLD.frame.origin.y , initialRunwayFrameWidth , _symRunwayLD.frame.size.height);
    CGAffineTransform rotateValue = CGAffineTransformMakeRotation( (windDirectionLD - _sliderRundwayHeadingLD.value) * M_PI / 180.0);
    CGAffineTransform scaleValue  = CGAffineTransformMakeScale(1, 1);
    _labelRunwayLengthLD.text = [[NSString alloc] initWithFormat:@"%.0f", _sliderRunwayLengthLD.value * conversionFeetToMeter ];
    [self drawMarksLD];
    
    // calc runway stuff
    rotateValue = CGAffineTransformMakeRotation( (_sliderRundwayHeadingLD.value + 90) * M_PI / 180.0);
    _runwayTopViewLD.transform = CGAffineTransformConcat(scaleValue, rotateValue );
    rotateValue = CGAffineTransformMakeRotation( (windDirectionLD) * M_PI / 180.0);
    _windsockLD.transform = CGAffineTransformConcat(scaleValue, rotateValue );
 
    
    float runwayLengthPixel = _symRunwayLD.frame.size.width - 20;
    float oneFeetInPixel = runwayLengthPixel / _sliderRunwayLengthLD.value;
    float distanceInFeetOverObstacle = totalDistance50ft;
    float distanceInPixelOverObstacle = oneFeetInPixel * distanceInFeetOverObstacle;
    _symAC2LD.frame = CGRectMake(_symRunwayLD.frame.origin.x + distanceInPixelOverObstacle - (_symAC2LD.frame.size.width/2), _symRunwayLD.frame.origin.y + (_symRunwayLD.frame.size.height/2)  -  (_symAC2LD.frame.size.height), _symAC2LD.frame.size.width, _symAC2LD.frame.size.height);
    
    float distanceInFeetGroundRoll = totalGroundRoll;
    float distanceInPixelGroundRoll = oneFeetInPixel * distanceInFeetGroundRoll;
    _symAC1LD.center = CGPointMake( _symObstacleLD.center.x + distanceInPixelGroundRoll - 40, _symAC2LD.center.y);
    
    
    _labelLandingDistanceToTouchDown.text = [[NSString alloc] initWithFormat:@"%.0f%@", distanceInFeetGroundRoll * conversionFeetToMeter, unitDistance ];
    _labelLandingDistanceToTouchDown.center = CGPointMake( _symAC1LD.center.x , _symAC1LD.center.y - 6);
    
    _labelLandingDistanceToStop.text = [[NSString alloc] initWithFormat:@"%.0f%@", distanceInFeetOverObstacle * conversionFeetToMeter, unitDistance ];
    _labelLandingDistanceToStop.center = CGPointMake( _symAC2LD.center.x , _symAC2LD.center.y - 10);
    
    
    
    if (windSpeedLD == 0) {
        _windsockLD.hidden = YES;
    }else{
        _windsockLD.hidden = NO;
    }
    
    
    scaleValue  = CGAffineTransformMakeScale(1, 1);
    rotateValue = CGAffineTransformMakeRotation( ((_sliderSlopeLD.value/6))  * M_PI / 180.0);
    _viewLDRunway.layer.anchorPoint = CGPointMake(0.0,0.5);
    _viewLDRunway.transform = CGAffineTransformConcat(scaleValue, rotateValue );
    
    
    UIImage *RWYimage = [UIImage imageNamed:@"Runway3-01.png"];
    [_symRunwayLD setImage:RWYimage];
    if (_sliderRunwayConditionsLD.value > 25 || _sliderSlopeLD.value > 10) {
        UIImage *RWYimage = [UIImage imageNamed:@"RunwayOrange.png"];
        [_symRunwayLD setImage:RWYimage];
    }
    if (_sliderRunwayConditionsLD.value > 50|| _sliderSlopeLD.value > 15) {
        UIImage *RWYimage = [UIImage imageNamed:@"RunwayRed.png"];
        [_symRunwayLD setImage:RWYimage];
    }
    
    
    
}










- (void) calcPerformance {
    
    
    specialChart = @"";
    computationErrorMessage = @"";
    
    //NSLog(@" calcPerformance ACCategory %@  ----------------------", ACCategory );
    
   totalAirspeedPenalty = 0;
   totalFuelFlowPenalty = 0;
   totalRangePenalty = 0;

   
    resultCruiseFuelBurn = 0;
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  ) { 
         //NSLog(@"this is fixed wing, so not doing xxx");
        
    }else{
        //NSLog(@"this is NOT fixed wing, so doing xxx");
        _cruiseInputFuelFlow.text = @"xxx"; 
          //NSLog(@"now setting xxx");
        
    }
 
    ViewController *parent = (ViewController *)self.parentViewController;
    parent.self.sliderMSL.enabled = YES;
    parent.self.sliderOATforOGE.enabled = YES;
    parent.self.sliderQNH.enabled = YES;
    parent.self.sliderISADiff.enabled = YES;
    
    parent.self.buttonEnterMSLfeet.hidden = NO;
    parent.self.buttonEnterMSLfeet.hidden = NO;
    parent.self.buttonISA.hidden = NO;
    parent.self.buttonOAT.hidden = NO;
    parent.self.buttonSetISA.hidden = NO;
    parent.self.buttonEnterQNH.hidden = NO;
    
    
    enviSliderSetForTakeoff = @"";
    enviSliderSetForLanding = @"";
    
    
    if ([ACCategory isEqualToString:@"FixedWing"]) {
        
        if (_segmentMeterFeet.selectedSegmentIndex == 0) {
            conversionFeetToMeter = 1;
             conversionNNMtoKM = 1;  
            unitDistance = @"ft";
            unitDistanceNMkm  = @"NM"; 
        }else{
            conversionFeetToMeter = 0.3048;
            conversionNNMtoKM = 1.852;
            unitDistance = @"m";
            unitDistanceNMkm  = @"km";
        }
        
        
        [self calcPerformanceActual];
        [self setACSideViewImages];
    }else{
        [self calcPerformanceActual];
        // do power check for 412EP
        if ([AC_Type isEqualToString:@"412EP"]) {
            
            _inputEngineTorque1.text = [[NSString alloc] initWithFormat:@"%.1f", _sliderEngineTorque1.value ];
            _inputEngineTorque2.text = [[NSString alloc] initWithFormat:@"%.1f", _sliderEngineTorque2.value ];
            
            _inputITT1.text = [[NSString alloc] initWithFormat:@"%.0f", _sliderITT1.value ];
            _inputITT2.text = [[NSString alloc] initWithFormat:@"%.0f", _sliderITT2.value ];
            
            
            
            for (int i = 1; i < resultsAllChartNames.count; i++) {
                
                
                if (_segentCheckType.selectedSegmentIndex == 0) {
                    
                    if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Heli_Bell_412EP_NONE_FMS56_Fig4_1_PAC_Hover1"].location != NSNotFound  ) {
                        _labelMaxAllowableITTEngine1.text = [[NSString alloc] initWithFormat:@"%.0f ºC", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ] ;
                    }
                    
                    if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Heli_Bell_412EP_NONE_FMS56_Fig4_1_PAC_Hover2"].location != NSNotFound  ) {
                        _labelMaxAllowableITTEngine2.text = [[NSString alloc] initWithFormat:@"%.0f ºC", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ] ;
                    }
                    
                }else{
                    
                    if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Heli_Bell_412EP_NONE_FMS56_Fig4_1_PAC_Inflight1"].location != NSNotFound  ) {
                        _labelMaxAllowableITTEngine1.text = [[NSString alloc] initWithFormat:@"%.0f ºC", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ] ;
                    }
                    
                    if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Heli_Bell_412EP_NONE_FMS56_Fig4_1_PAC_Inflight2"].location != NSNotFound  ) {
                        _labelMaxAllowableITTEngine2.text = [[NSString alloc] initWithFormat:@"%.0f ºC", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ] ;
                    }
                    
                    
                    
                    
                    
                    
                }
                
                
            }
            
            
            float margineEngine1 = [_labelMaxAllowableITTEngine1.text floatValue] - [_inputITT1.text floatValue];
            _labelMargineEngine1.text = [[NSString alloc] initWithFormat:@"%.0f ºC", margineEngine1 ] ;
            
            
            float margineEngine2 = [_labelMaxAllowableITTEngine2.text floatValue] - [_inputITT2.text floatValue];
            _labelMargineEngine2.text = [[NSString alloc] initWithFormat:@"%.0f ºC", margineEngine2 ] ;
            
            
            if (margineEngine1 > 0) {
                _labelPowerCheckResult1.text = @"Power Check for Engine 1 OK.";
                _labelPowerCheckResult1.textColor = [UIColor greenColor];
                _labelPowerCheckResult1.backgroundColor = [UIColor clearColor];
                _labelMargineEngine1.textColor = [UIColor greenColor];
                _labelMargineEngine1.backgroundColor = [UIColor clearColor];
            }else{
                
                _labelPowerCheckResult1.text = @"Power Check for Engine 1 FAILED!";
                _labelPowerCheckResult1.textColor = [UIColor whiteColor];
                _labelPowerCheckResult1.backgroundColor = [UIColor redColor];
                _labelMargineEngine1.textColor = [UIColor whiteColor];
                _labelMargineEngine1.backgroundColor = [UIColor redColor];
            }
            
            
            if (margineEngine2 > 0) {
                _labelPowerCheckResult2.text = @"Power Check for Engine 2 OK.";
                _labelPowerCheckResult2.textColor = [UIColor greenColor];
                _labelPowerCheckResult2.backgroundColor = [UIColor clearColor];
                _labelMargineEngine2.textColor = [UIColor greenColor];
                _labelMargineEngine2.backgroundColor = [UIColor clearColor];
                
            }else{
                _labelPowerCheckResult2.text = @"Power Check for Engine 2 FAILED!";
                _labelPowerCheckResult2.textColor = [UIColor whiteColor];
                _labelPowerCheckResult2.backgroundColor = [UIColor redColor];
                _labelMargineEngine2.textColor = [UIColor whiteColor];
                _labelMargineEngine2.backgroundColor = [UIColor redColor];
            }
            
            
            
            
        }
        
    }
    triggerLoadSliderData = 0;
   
    //NSLog(@"cruiseInputFuelFlow %@", _cruiseInputFuelFlow.text);    
    //NSLog(@"resultCruiseFuelBurn %.1f", resultCruiseFuelBurn);
    
    if (resultCruiseFuelBurn != 0) {
        _cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", resultCruiseFuelBurn ];
    }
    
    
}



- (void) calcPerformanceActual {
    
    //NSLog(@"calcPerformanceActual -------------");
    // load basics
    
    _segmentFlapsLD.hidden = YES;
    
    serverUrl  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"serverUrl"];
    ACCategory  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"ACCategory"];
    ACmanufacturer  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"ACmanufacturer"];
    AC_Type  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"AC_Type"];
    ACVariant  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"ACVariant"];
    
    [resultsAllEnviSettings removeAllObjects];
    
    flagWeHaveAS365PC2computation = 0;
    flagPC2dataOutOfRange = 0;
    
    float flagIsLandscape = 1;
    
    flagCustomPageIsOn = 0;
    
    if (fullScreenPerfCharts == 0 & flagIsLandscape == 1) {
        _masterViewCharts.frame = CGRectMake( 0, 0, 644, 632 ); // landscape
    }
    if (fullScreenPerfCharts == 1 & flagIsLandscape == 1) {
        _masterViewCharts.frame = CGRectMake( 0, 0, 1024, 690 ); // landscape full screen
    }
    if (fullScreenPerfCharts == 0 & flagIsLandscape == 0) {
        _masterViewCharts.frame = CGRectMake( 0, 0, 644, 628 ); // portrait
    }
    if (fullScreenPerfCharts == 1 & flagIsLandscape == 0) {
        _masterViewCharts.frame = CGRectMake( 0, 0, 768, 950 ); // portrait full screen
    }
    
    
    // **********************************************************************************************************************************************************************************************************
    // **********************************************************************************************************************************************************************************************************
    // START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START
    // START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START    START
    // **********************************************************************************************************************************************************************************************************
    // **********************************************************************************************************************************************************************************************************
    
  
    
    if ([specialChart isEqualToString:@""]) {
        
        [resultsAllChartNames removeAllObjects];
        [resultsAllChartUserNames removeAllObjects];
        [resultsAllDataOutOfRange removeAllObjects];
        [resultsAllChartValues removeAllObjects];
        [resultsAllUnits removeAllObjects];
        [resultsAllPrintOnManifest removeAllObjects];
        
        //NSLog(@"computing ----------------------");
        //NSLog(@"ACCategory %@", ACCategory);
        //NSLog(@"ACmanufacturer %@", ACmanufacturer);
        //NSLog(@"AC_Type %@", AC_Type);
        
        //1. get amount of available charts to compute
      
        ViewController *parent = (ViewController *)self.parentViewController;
        NSArray *componentsReducedCharts = [[NSArray alloc] init]; 
        if (parent.arrayName25.count >=53 ) {
            NSString *reducedPerfCharts = [parent.arrayName25 objectAtIndex:53]; //extra10
            NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+"];
            componentsReducedCharts = [reducedPerfCharts componentsSeparatedByCharactersInSet:charSet];  
        } 
        
        if (componentsReducedCharts.count > 1) {
            chartsArray = componentsReducedCharts;
        }else{
            // get chart names from chartsArray
            arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"availableCharts" ];
            chartsArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];       
        }
         
        //NSLog(@"chartsArray %@", chartsArray);
  
        
        
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"fixedWingSetupText" ];
        fixedWingSetupText = [[NSUserDefaults standardUserDefaults] objectForKey:arrayKey]; 
        arrayFixedWingSetup = [[NSArray alloc] init];
        if (fixedWingSetupText.length > 4) {
             NSCharacterSet* charSet0 = [NSCharacterSet characterSetWithCharactersInString:@"}"];
              arrayFixedWingSetup = [fixedWingSetupText componentsSeparatedByCharactersInSet:charSet0];
        }       
        
        //NSLog(@"loading fixedWingSetupText -%@-", fixedWingSetupText);
        //NSLog(@"arrayFixedWingSetup %@", arrayFixedWingSetup);
        
        numberOfChartsForThisAircraft = (int)chartsArray.count;
        
        //NSLog(@"1 numberOfChartsForThisAircraft = %d  ******************************", numberOfChartsForThisAircraft  );
        
        actualButtonNumber = 0;
        //NSLog(@"setting actualButtonNumber to zero");
        
        [self hideAllViews];
        
    }else{
        
        //NSLog(@" do special chart %@ ", specialChart);
        
    }
    
    
    
    //2. loop all charts
    
    //NSLog(@"numberOfChartsForThisAircraft %d ", numberOfChartsForThisAircraft);
    
    actualChartNumber = 0;
    
    //NSLog(@"start*****************");
    
    resultsAllMargins = [[NSMutableArray alloc] init];
    
   
    _robinsonLabelCarbHeat.text = @"";
    
    _robinsonViewCarbHeat.hidden = YES; 
     
    
    for (nChart =0; nChart<numberOfChartsForThisAircraft; nChart ++) {
        
        // check if you need to use a weight penalty
        acWeight = unchangedACWeight;        
        //NSLog(@"[chartsArray objectAtIndex:nChart] %@ ", [chartsArray objectAtIndex:nChart]);        
        if ([[chartsArray objectAtIndex:nChart]  rangeOfString:@"EnRoute_OEI_MCP_Sup911_FigA25_CX"].location != NSNotFound    ) {
            //NSLog(@"changing acWeight with penalty %.0f ", penaltyWeight);
            acWeight = unchangedACWeight - penaltyWeight;
        }
        _MTOWcorrected.text = [[NSString alloc] initWithFormat:@"%.0f kg", unchangedACWeight - penaltyWeight ];
        //NSLog(@"using acWeight %.0f ", unchangedACWeight - penaltyWeight);
        
        
        if (![specialChart isEqualToString:@""]) {
            if (![[chartsArray objectAtIndex:nChart] isEqualToString:specialChart]) {
                continue;
            }else{
                //NSLog(@"I am doing chartNameForThisInfoFile %@ ", [chartsArray objectAtIndex:nChart]);
            }
        }
        
        
        actualButtonNumber = actualButtonNumber +1;
        actualChartNumber = actualChartNumber + 1;
        //NSLog(@"adding actualButtonNumber %d ", actualButtonNumber);
        
        [self getInfoForCurrentChart];        
        
        // check if we have a PC2 computations               
        if ([AC_Type isEqualToString:@"AS365N3"] && [chartUserName rangeOfString:@"PC2"].location != NSNotFound ) {
            flagWeHaveAS365PC2computation = 1;
        }
   
        // check dependency
        int numberOfChartsToCombine = 0;
        NSString *criteria;
        NSString *criteriaObject;
        float criteriaValue = 0;
        float criteriaValueMid1= 0;
        float criteriaValueMid2= 0;
        float criteriaValueMid3= 0;
        float criteriaValueMid4= 0;
        float criteriaValueMid5= 0;
                   
        //NSLog(@"chartUserName %@", chartUserName);  
        //NSLog(@"userNameForComputation %@", userNameForComputation);  
        ViewController *parent = (ViewController *)self.parentViewController;
         parent.self.viewButtonAutoCalcMode.hidden =YES;
        
        //NSLog(@"infoArray %@", infoArray);  
        //NSLog(@"chartUserName %@", chartUserName); 
        
     
        
        //NSLog(@"1 here triggerLoadSliderData %d", triggerLoadSliderData);
        
       
        if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomR44"].location != NSNotFound) {
            
           //NSLog(@"infoArray %@", infoArray);  
            
          
                    
            if ([[infoArray objectAtIndex:6]  rangeOfString:@"R44RavenIIManifold"].location != NSNotFound) {  
                
                _labelRobinsonMinusInches.text = @"- 2.8\"";                
                UIImage *graphic = [UIImage imageNamed:@"manifold_R44_RavenII_v2.png"];
                [_graphicRobinsonMAPinstrument setImage:graphic];
                graphic = [UIImage imageNamed:@"R44RavenIIMCPchart.png"];
                [_graphicRobinsonMAPchart setImage:graphic];
               
                
                [self calcR44RavenIIMAP];
            }
            
            
            if ([[infoArray objectAtIndex:6]  rangeOfString:@"R22BetaIIManifold"].location != NSNotFound) {  
                
                _robinsonViewCarbHeat.hidden = NO;  
                         
                NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];             
                _robinsonSwitchCarbHeat.on = [[NSUserDefaults standardUserDefaults] boolForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_robinsonSwitchCarbHeat" ]];
                
                if (_robinsonSwitchCarbHeat.on == YES) {
                    _robinsonLabelCarbHeat.text = @"ADD 1.5 \"HG";
                }
                
                _labelRobinsonMinusInches.text = @"- 1.0\"";                
                UIImage *graphic = [UIImage imageNamed:@"Manifold_R2_Beta_II.png"];
                [_graphicRobinsonMAPinstrument setImage:graphic];
                graphic = [UIImage imageNamed:@"new R22 Beta II MCP chart graphic-01.png"];
                [_graphicRobinsonMAPchart setImage:graphic];
                
                [self calcMAP_BetaII];
            }
            
            
            
            
            if ([[infoArray objectAtIndex:6]  rangeOfString:@"R44RavenAstroManifold"].location != NSNotFound) {  
                
                _robinsonViewCarbHeat.hidden = NO;                
                NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];             
                _robinsonSwitchCarbHeat.on = [[NSUserDefaults standardUserDefaults] boolForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_robinsonSwitchCarbHeat" ]];
                
                if (_robinsonSwitchCarbHeat.on == YES) {
                    _robinsonLabelCarbHeat.text = @"ADD 1.5 \"HG";
                }
                
                _labelRobinsonMinusInches.text = @"- 1.6\"";  
                UIImage *graphic = [UIImage imageNamed:@"manifold_R44_RavenAstro_v3.png"];
                [_graphicRobinsonMAPinstrument setImage:graphic];
                graphic = [UIImage imageNamed:@"MCP Astro chart color.png"];
                [_graphicRobinsonMAPchart setImage:graphic];
                
                
                [self calcR44RavenAstroMAP];
            }
            
            //NSLog(@"[infoArray objectAtIndex:6] %@", [infoArray objectAtIndex:6]);
            
            if ([[infoArray objectAtIndex:6]  rangeOfString:@"R44RavenIIVNE"].location != NSNotFound) {                 
                UIImage *graphic = [UIImage imageNamed:@"R44RavenIIVNE.png"];
                [_graphicRobinsonVNEchart setImage:graphic];  
                graphic = [UIImage imageNamed:@"R44_Airspeed2.png"];
                [_robinsonAirspeedIndicator setImage:graphic];  
                [self calcR44RavenIIVNE];
            }
            
            if ([[infoArray objectAtIndex:6]  rangeOfString:@"R44RavenAstroVNE"].location != NSNotFound) {                 
                UIImage *graphic = [UIImage imageNamed:@"R44RavenAstroVNE.png"];
                [_graphicRobinsonVNEchart setImage:graphic];  
                graphic = [UIImage imageNamed:@"R44_Airspeed2.png"];
                [_robinsonAirspeedIndicator setImage:graphic];  
                [self calcR44RavenAstroVNE];
            }
            
            if ([[infoArray objectAtIndex:6]  rangeOfString:@"R22BetaIIVNE"].location != NSNotFound) { 
                UIImage *graphic = [UIImage imageNamed:@"R22BetaIIVNE.png"];
                [_graphicRobinsonVNEchart setImage:graphic];  
                graphic = [UIImage imageNamed:@"R22_airspeedindicator.png"];
                [_robinsonAirspeedIndicator setImage:graphic];  
                [self calculateNeverExceedSpeedBetaII];
            }
            
            
            
        }
        
        
        
      //NSLog(@"1 acWeight %.0f ", acWeight);
        
        if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  ) { 
            
            
            parent.self.viewButtonAutoCalcMode.hidden =NO;
            
            //NSLog(@"1 here triggerLoadSliderData %d", triggerLoadSliderData);
            
            if (triggerLoadSliderData == 1 ) {
                [self loadFixedWingSliders];
            }
            [self saveFixedWingSliders];
            
                                    
            
            
            //NSLog(@"1infoArray %@ ", infoPartArray);
            arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@", chartNameForThisInfoFile, infoPartNumber, @"infoFile" ];
            infoPartArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
            //NSLog(@"1infoPartArray %@ ", infoPartArray);
            originalPerformanceDistanceUnits = [infoPartArray objectAtIndex:14];
            //NSLog(@"originalPerformanceDistanceUnits %@", originalPerformanceDistanceUnits);            
            //NSLog(@"userNameForComputation %@", userNameForComputation);   
            
            if ([chartUserName isEqualToString:@"ClimbComp"] ) {                
                if ([ACweightUnitsUsed isEqualToString:@"lbs"] && [originalPerformanceDistanceUnits isEqualToString:@"kg"] ) {
                    //convert acweight from lbs to kg
                    acWeight = acWeight / 2.2046;
                }               
                
                if (lockACweightOverrideTO == 0) {
                    acWeight = _sliderAircraftWeightOverrideTO.value;
                }
                
                
            }
            
            if ([chartUserName isEqualToString:@"CruiseComp"] ) {
                
                if ([ACweightUnitsUsed isEqualToString:@"lbs"] && [originalPerformanceDistanceUnits isEqualToString:@"m"] ) {
                    //convert acweight from lbs to kg
                    acWeight = acWeight / 2.2046;
                }               
                
                if (lockACweightOverrideTO == 0) {
                    acWeight = _sliderAircraftWeightOverrideTO.value;
                }
                
                
            }
            
            
            if ([chartUserName isEqualToString:@"TOGroundRoll"] || [chartUserName isEqualToString:@"TO50ft"]) {
                
                //NSLog(@"ACweightUnitsUsed %@ ", ACweightUnitsUsed);
                
                //NSLog(@"originalPerformanceDistanceUnits %@ ", originalPerformanceDistanceUnits);
                
                if ([ACweightUnitsUsed isEqualToString:@"lbs"] && [originalPerformanceDistanceUnits isEqualToString:@"m"] ) {
                    //convert acweight from lbs to kg
                    acWeight = acWeight / 2.2046;
                }                
                
                if (lockACweightOverrideTO == 0) {
                    acWeight = _sliderAircraftWeightOverrideTO.value;
                }
                //NSLog(@"TO acWeight %.0f ", acWeight);
            }
            
            
            
            if ([chartUserName isEqualToString:@"LDGGroundRoll"] || [chartUserName isEqualToString:@"LDG50ft"]) {
                acWeight = acLandingWeight;
                //NSLog(@"using ac landing weight %.0f ", acWeight);
                
                if ([ACweightUnitsUsed isEqualToString:@"lbs"] && [originalPerformanceDistanceUnits isEqualToString:@"m"] ) {
                    //convert acweight from lbs to kg
                    acWeight = acWeight / 2.2046;
                }                
              
                if (lockACweightOverrideLD == 0) {
                    acWeight = _sliderAircraftWeightOverrideLD.value;
                }
                
                
                //NSLog(@"LD acWeight %.0f ", acWeight);
                
            }
                       
                       
            
            //NSLog(@"chartUserName %@", chartUserName);
            //NSLog(@"real acWeight %.0f ", acWeight);
            
            //NSLog(@"userNameForComputation %@ ", userNameForComputation);
            
            
            if ([userNameForComputation isEqualToString:@"TOGroundRoll"]) {
                windDirectionTO = IAS;
                windSpeedTO = headWindKTS;
                ACweightTO = acWeight;
            }
            if ([userNameForComputation isEqualToString:@"TO50ft"]) {
                windDirectionTO = IAS;
                windSpeedTO = headWindKTS;
                ACweightTO = acWeight;
            }
            if ([userNameForComputation isEqualToString:@"LDGGroundRoll"]) {
                windDirectionLD = IAS;
                windSpeedLD = headWindKTS;
                ACweightLD = acWeight;
            }
            if ([userNameForComputation isEqualToString:@"LDG50ft"]) {
                windDirectionLD = IAS;
                windSpeedLD = headWindKTS;
                ACweightLD = acWeight;
            }
            
            if ([userNameForComputation isEqualToString:@"ClimbComp"]) {
                windSpeedClimb = headWindKTS;                
                ACweightClimb = acWeight;
            }
            
            if ([userNameForComputation isEqualToString:@"CruiseComp"]) {
                windSpeedCruise = headWindKTS;                
                ACweightCruise = acWeight;
            }
            
            
            //NSLog(@"ACweightClimb %.0f ", ACweightClimb);
            
            //NSLog(@"windSpeedTO %.0f", windSpeedTO);
            //NSLog(@"windSpeedClimb %.0f", windSpeedClimb);
            //NSLog(@"windSpeedLD %.0f", windSpeedLD);
            
        }
    
        
        //NSLog(@"2 acWeight %.0f ", acWeight);
        
        //NSLog(@"setting windDirectionTO %.0f ", windDirectionTO);
        //NSLog(@"setting windDirectionLD %.0f ", windDirectionLD);
        
        // check if this is a ceiling computation i.e. "1 part ceiling"
        flagCeilingComputation = 0;
        //NSLog(@"infoArray %@ ", infoArray);
        
        if ([[infoArray objectAtIndex:2]  rangeOfString:@"Ceiling"].location != NSNotFound    ) {
            flagCeilingComputation = 1;
        }
        
        if ([[infoArray objectAtIndex:2]  rangeOfString:@"CeilingROC"].location != NSNotFound    ) {
            flagCeilingComputation = 2;
        }
        
    
        //NSLog(@"infoArray %@", infoArray);
        
        if ([ [infoArray objectAtIndex:3]  rangeOfString:@"next3"].location != NSNotFound      ) {
           
            numberOfChartsToCombine = 3;
            // get criteria
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"acWeight"].location != NSNotFound      ) {
                criteria = @"acWeight";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                //NSLog(@"criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                criteriaValue = acWeight;
                //NSLog(@"criteriaValue TOW %.0f", criteriaValue);
            }
            
        }else if ([ [infoArray objectAtIndex:3]  rangeOfString:@"next4"].location != NSNotFound      ) {
          
            numberOfChartsToCombine = 4;
            // get criteria
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"acWeight"].location != NSNotFound      ) {
                criteria = @"acWeight";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                criteriaValueMid3 = [[infoArray objectAtIndex:7] floatValue];
                //NSLog(@"criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                criteriaValue = acWeight;
                //NSLog(@"criteriaValue TOW %.0f", criteriaValue);
            }
            
        }else if ([ [infoArray objectAtIndex:3]  rangeOfString:@"next5"].location != NSNotFound      ) {
          
            numberOfChartsToCombine = 5;
            // get criteria
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"acWeight"].location != NSNotFound      ) {
                criteria = @"acWeight";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                criteriaValueMid3 = [[infoArray objectAtIndex:7] floatValue];
                criteriaValueMid4 = [[infoArray objectAtIndex:8] floatValue];
                //NSLog(@"criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                criteriaValue = acWeight;
                //NSLog(@"criteriaValue TOW %.0f", criteriaValue);
            }
            
        }else if ([ [infoArray objectAtIndex:3]  rangeOfString:@"next6"].location != NSNotFound      ) {
          
            numberOfChartsToCombine = 6;
            // get criteria
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"acWeight"].location != NSNotFound      ) {
               
                criteria = @"acWeight";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                criteriaValueMid3 = [[infoArray objectAtIndex:7] floatValue];
                criteriaValueMid4 = [[infoArray objectAtIndex:8] floatValue];
                criteriaValueMid5 = [[infoArray objectAtIndex:9] floatValue];
                //NSLog(@"criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                criteriaValue = acWeight;
                //NSLog(@"criteriaValue TOW %.0f", criteriaValue);
            }
        }else if ([ [infoArray objectAtIndex:3]  rangeOfString:@"next2"].location != NSNotFound      ) {
       
            //NSLog(@"infoArray %@", infoArray);
            
            
            
            numberOfChartsToCombine = 2;
            // get criteria
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"acWeight"].location != NSNotFound      ) {
              
                criteria = @"acWeight";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                //NSLog(@"1 criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                //NSLog(@"acWeight %.0f", acWeight);
                criteriaValue = acWeight;
                //NSLog(@"1 criteriaValue TOW %.0f", criteriaValue);
            }
            
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"OAT"].location != NSNotFound      ) {
               
                criteria = @"OAT";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                //NSLog(@"1 criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                criteriaValue = OAT;
                //NSLog(@"1 criteriaValue OAT %.0f", criteriaValue);
            }
            
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"flapSettingLD"].location != NSNotFound      ) {
                
                criteria = @"flapSettingLD";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                //NSLog(@"1 criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                //criteriaValue = flapSettingLD;
                
                if (_segmentFlapsLD.selectedSegmentIndex == 0) {
                    criteriaValue = 100;
                }else{
                    criteriaValue = 50;
                } 
                
                
                //NSLog(@"1 criteriaValue OAT %.0f", criteriaValue);
            }
            
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"flapSettingTO"].location != NSNotFound      ) {
                
                criteria = @"flapSettingTO";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                //NSLog(@"1 criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"criteriaValueMid2 %.0f", criteriaValueMid2);
                criteriaValue = flapSettingTO;
                //NSLog(@"1 criteriaValue OAT %.0f", criteriaValue);
            }
            
            
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"ISAdiff"].location != NSNotFound      ) {
                
                criteria = @"ISAdiff";
                criteriaValueMid1 = [[infoArray objectAtIndex:5] floatValue];
                criteriaValueMid2 = [[infoArray objectAtIndex:6] floatValue];
                //NSLog(@"1 criteriaValueMid1 %.0f", criteriaValueMid1);
                //NSLog(@"2criteriaValueMid2 %.0f", criteriaValueMid2);
                criteriaValue = ISADiff;
                //NSLog(@"3 criteriaValue ISAdiff %.0f", criteriaValue);
            }
            
            if ([ [infoArray objectAtIndex:4]  rangeOfString:@"specialData1"].location != NSNotFound      ) {
             
                criteria = specialdata1;
                criteriaObject = [infoArray objectAtIndex:5];
                
                //NSLog(@"criteria %@", criteria);
                //NSLog(@"criteriaObject %@", criteriaObject);
                
                if ([criteria isEqualToString: criteriaObject]) {
                    criteriaValue = 1;
                    criteriaValueMid1 = 0;
                }else{
                    criteriaValue = 0;
                    criteriaValueMid1 = 1;
                }
                
            }
            
            
        }else if ([ [infoArray objectAtIndex:3]  rangeOfString:@"Custom"].location != NSNotFound      ) {
            //NSLog(@"!Custom");
            numberOfChartsToCombine = 0;
        }else if ([ [infoArray objectAtIndex:3]  rangeOfString:@"ClimbComp"].location != NSNotFound   || [ [infoArray objectAtIndex:3]  rangeOfString:@"CruiseComp"].location != NSNotFound    ) {
            
            numberOfChartsToCombine = 1;
            
        }else{
            numberOfChartsToCombine = 1;
        }
      
        
     
  //NSLog(@"4 do that numberOfChartsToCombine %d", numberOfChartsToCombine);
        
        // CUSTOM CHART **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** ****
        if (numberOfChartsToCombine == 0) {
            
            //NSLog(@"infoArray %@", infoArray);
            
            //NSLog(@"CUSTOM CHART **** **** **** **** **** **** **** **** **** **** ");
            unitResult = @"-";
            resultComputation = 999999;
            
            [resultsAllChartNames addObject: chartNameForThisInfoFile];
            [resultsAllChartUserNames addObject: chartUserName];
            [resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagInputDataOutOfRange]];
            
            if (infoArray.count >3) {
                 [resultsAllChartValues addObject: [infoArray objectAtIndex:4]];
                //NSLog(@"adding %@", [infoArray objectAtIndex:4]);
            }
            unitResult = @"noUnit";
            [resultsAllUnits addObject:unitResult];
   
            
            chartNumberForResult = nChart;
            [self writeButtonLabels];
            
            if (selectedChartButton == actualButtonNumber) {
                
                if (nChart == 0) {
                    
                    if ([AC_Type isEqualToString:@"AS365N2"] || [AC_Type isEqualToString:@"AS365N3"]) {
                        _viewPC2OverviewAS365.hidden = NO;
                    }else{
                        _viewCATAOverview1.hidden = NO;
                    }
                    
                }
                if (nChart == 1) {
                    _viewCATAOverview2.hidden = NO;
                }
                if (nChart == 2) {
                    _viewCATAOverview3.hidden = NO;
                }
               
                chartNameToLoad = chartNameForThisInfoFile;
            }
              
            //NSLog(@"selectedChartButton  %.0f", selectedChartButton );            
            //NSLog(@"displayWindow  %.0f", displayWindow );            
            //NSLog(@"actualButtonNumber  %d", actualButtonNumber );            
            //NSLog(@"actualChartNumber %d", actualChartNumber );            
            //NSLog(@"chartNameForSliderDefaults %@", chartNameForSliderDefaults );            
            //NSLog(@"[resultsAllChartUserNames objectAtIndex:chartNumberForResult] %@", [resultsAllChartUserNames objectAtIndex:chartNumberForResult] );
            
            
            ViewController *parent = (ViewController *)self.parentViewController;
            dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   actualButtonNumber + 100  ];
            
            
            
            sliderEngineRPMincrement = 50;
            _labelSliderEngineRPM.text = @"Engine RPM";
          
            if ( [[infoArray objectAtIndex:3]  rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound ) {
                
                if (lockACweightOverrideLD == 0) {
                    acLandingWeight = _sliderAircraftWeightOverrideLD.value;
                    //NSLog(@"2override %.0f", acLandingWeight);
                }
                
                parent.self.viewButtonAutoCalcMode.hidden =NO;
                
                //NSLog(@"CustomFixedWingOLD ---------------");
                 compString = [infoArray objectAtIndex:6] ;
                
                
                float sliderMinVal = [[infoArray objectAtIndex:7] floatValue];
                float sliderMaxVal = [[infoArray objectAtIndex:8] floatValue];
                
                calcPerfC172 *_calcPerfC172= [[calcPerfC172 alloc]init];
                originalPerformanceDistanceUnits = @"ft";
                originalPerformanceWeightUnits = @"lbs";
                float initialConversionFactor = 1;
                                
                
                if (    [compString rangeOfString:@"DA40-180"].location != NSNotFound ){
                     originalPerformanceWeightUnits = @"kg";
                }
                
                if ([originalPerformanceWeightUnits isEqualToString:@"lbs"] & [selectedUnitsForItems isEqualToString:@"kg"]  ) {
                    initialConversionFactor = 1/2.2046;
                } 
                
                if ([originalPerformanceWeightUnits isEqualToString:@"kg"] & [selectedUnitsForItems isEqualToString:@"lbs"]  ) {
                    initialConversionFactor = 2.2046;
                }
               
                float acWeightForTO = acWeight;
                //NSLog(@"acWeightForTO %.1f", acWeightForTO);
                
                
                float acWeightForLD = acLandingWeight;
                
                if (triggerLoadSliderData == 1 ) {
                    [self loadFixedWingSliders];
                }
                [self saveFixedWingSliders];
                               
               //NSLog(@"compString %@", compString);
                
                NSString *ACgroup = @"";
                
                if (    [compString rangeOfString:@"C172"].location != NSNotFound 
                     || [compString rangeOfString:@"C182"].location != NSNotFound
                     || [compString rangeOfString:@"C152"].location != NSNotFound
                     || [compString rangeOfString:@"PA28"].location != NSNotFound 
                     || [compString rangeOfString:@"DA40-180"].location != NSNotFound) {
                    
                    ACgroup = @"1";
                }
                        
                
                
                if ([ACgroup isEqualToString:@"1"]  && [compString rangeOfString:@"takeoff"].location != NSNotFound ) {
           
                    _labelConditionsTO.text = [[infoArray objectAtIndex:9]stringByReplacingOccurrencesOfString:@"_" withString:@" "];                     
                    _sliderAircraftWeightOverrideTO.maximumValue = sliderMaxVal * initialConversionFactor;
                    _sliderAircraftWeightOverrideTO.minimumValue = sliderMinVal * initialConversionFactor;  
                    
                 
                    
                    if (lockACweightOverrideTO == 1) {
                        _sliderAircraftWeightOverrideTO.value = acWeightForTO * initialConversionFactor;
                    }else{
                        // unlocked, slider rules
                        acWeightForTO = _sliderAircraftWeightOverrideTO.value / initialConversionFactor;
                    } 
                    
                 
                    windDirectionTO = IAS;                    
                    headwindcomponentTO = headWindKTS * cos (  ( windDirectionTO -  _sliderRundwayHeadingTO.value) * 0.01745);
                                      
                    [_calcPerfC172 fwValueTransfer:OAT sendPA:Hp  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headwindcomponentTO  sendACweight:acWeightForTO sendACType:AC_Type sendComputation:compString];
                    TO_PA = Hp;
                    
                    [self computeTakeoff_UniversalWithFixedData];
                    [self animateFixedWingTakeoff];
                }
                
                if ([ACgroup isEqualToString:@"1"]  && [compString rangeOfString:@"landing"].location != NSNotFound ) {                    
                    _labelConditionsLD.text  = [[infoArray objectAtIndex:9]stringByReplacingOccurrencesOfString:@"_" withString:@" "];                    
                    _sliderAircraftWeightOverrideLD.maximumValue = sliderMaxVal * initialConversionFactor;
                    _sliderAircraftWeightOverrideLD.minimumValue = sliderMinVal * initialConversionFactor;    
                    
                
                    
                    if (lockACweightOverrideLD == 1) {
                        _sliderAircraftWeightOverrideLD.value = acWeightForLD * initialConversionFactor;
                    }else{
                        // unlocked, slider rules
                        acWeightForLD = _sliderAircraftWeightOverrideLD.value / initialConversionFactor;
                    } 
                   
                    
                    windDirectionLD = IAS;                    
                    headwindcomponentLD = headWindKTS * cos (  ( windDirectionLD -  _sliderRundwayHeadingLD.value) * 0.01745);
                    
                    //NSLog(@"sending landing weight %.0f", acWeightForLD);
                    [_calcPerfC172 fwValueTransfer:OAT sendPA:Hp  sendISAdiff:ISADiff sendQNH_USA:altimeterInches sendHeadWindKts:headwindcomponentLD  sendACweight:acWeightForLD sendACType:AC_Type sendComputation:compString];
                    [self computeLanding_CessnaC172];
                    [self animateFixedWingLanding];
                }
                
                if ([ACgroup isEqualToString:@"1"]  && [compString rangeOfString:@"Climb"].location != NSNotFound ) {  
                                       
                    maxPAforThisComputation = 12000;
                    maxClimbDistanceForGraph = 50;
                    maxClimbDistanceSteps = 5;
                    _labelConditionsClimb.text = [[infoArray objectAtIndex:9]stringByReplacingOccurrencesOfString:@"_" withString:@" "];                     
                   
                    
                    if ([compString rangeOfString:@"DA40-180"].location != NSNotFound ) {
                         [self computeClimbIfRocDataOnly: @"DA40-180"];  
                    }else{
                         [self computeClimbUniversal: @""];  
                        
                    }
                }                
                
       
                if ([ACgroup isEqualToString:@"1"]  && [compString rangeOfString:@"Cruise"].location != NSNotFound ) {   
                    //NSLog(@"compString %@", compString);
                    _iCruiseConditions.text = [[infoArray objectAtIndex:9]stringByReplacingOccurrencesOfString:@"_" withString:@" "];    
                    CruiseMaxElevation = 12000;
                    CruiseElevationincrement = 1000;
                    CruiseMaxDistance = 800;
                    
                    if ([compString rangeOfString:@"PA28"].location != NSNotFound || [compString rangeOfString:@"DA40-180"].location != NSNotFound  ){
                        _labelSliderEngineRPM.text = @"Engine Power %";
                        sliderEngineRPMincrement = 1;
                    }
                   
                    if ( [compString rangeOfString:@"DA40-180"].location != NSNotFound  ){
                        CruiseMaxElevation = 14000;
                    }
                        
                        
                    [self computeCruiseUniversal]; 
                }
                
                
                
                
                 
                
                
            }// end custom fixed wing old
            
            /// ************* end custom fixed wing old 
            
            
            
            
       
            if (infoArray.count >5) {             ;
                NSString *viewString = [infoArray objectAtIndex:5] ;
                //NSLog(@"viewString %@", viewString);
                if ([viewString isEqualToString:@"viewPowerCheck"]) {
                    _viewPowerCheck.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewPowerCheck];
                    flagCustomPageIsOn = 1;
                }
            }
        
            
        }
        
    
      
        if (numberOfChartsToCombine == 1) {
           
            //NSLog(@"1 nChart %d", nChart);
            //NSLog(@"flagCeilingComputation %d", flagCeilingComputation);
            unitResult = @"-";
            //arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@", chartNameForThisInfoFile, infoPartNumber, @"infoFile" ];
            //infoPartArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
            //NSLog(@"[infoPartArray objectAtIndex: 18  ] %@", [infoPartArray objectAtIndex: 18]  );
            
            //NSLog(@"infoArray>%@<", infoArray );
            //NSLog(@"[infoArray objectAtIndex:3] >%@<", [infoArray objectAtIndex:3]  );
            
            //NSLog(@"[infoPartArray objectAtIndex: 3  ] %@", [infoArray objectAtIndex: 3  ]  );
            
          //NSLog(@"flagCeilingComputation %d", flagCeilingComputation);
            
            if (flagCeilingComputation == 0) {
               
                if ([ [infoArray objectAtIndex:3]  rangeOfString:@"ClimbComp"].location != NSNotFound      ) {
                    
                    //NSLog(@"warum?"); 
                    
                    if (fixedWingSetupText.length > 4) {
                        
                    }
                    
                    
                    if (arrayFixedWingSetup.count > 2) {
                        maxPAforThisComputation = [[arrayFixedWingSetup objectAtIndex:0]floatValue]; 
                        CruiseMaxElevation  = [[arrayFixedWingSetup objectAtIndex:1]floatValue];
                        CruiseElevationincrement  = [[arrayFixedWingSetup objectAtIndex:2]floatValue];
                        CruiseMaxDistance  = [[arrayFixedWingSetup objectAtIndex:3]floatValue];
                        maxClimbDistanceForGraph  = [[arrayFixedWingSetup objectAtIndex:4]floatValue];
                        maxClimbDistanceSteps  = [[arrayFixedWingSetup objectAtIndex:5]floatValue];
                        chartNumberForResult = nChart;
                        _labelClimbTempCorrectionInfo.text = [arrayFixedWingSetup objectAtIndex:6];
                        
                        //NSLog(@"setting maxPAforThisComputation %f", maxPAforThisComputation); 
                        [self prepareChartComp];                       
                        [self computeClimbUniversal: @"universal"];  
                        
                    }else{
                        
                        if ([ AC_Type  rangeOfString:@"DA42"].location != NSNotFound || [ AC_Type  rangeOfString:@"DA62"].location != NSNotFound      ) {
                                              maxPAforThisComputation = 18000; 
                                              CruiseMaxElevation = 18000;
                                              CruiseElevationincrement = 2000;
                                              CruiseMaxDistance = 650;
                                              maxClimbDistanceForGraph = 50;
                                              maxClimbDistanceSteps = 5;
                                              chartNumberForResult = nChart;                        
                                              _labelClimbTempCorrectionInfo.text = @"Includes 10% for time, fuel and distance for each 10°C/12°F increase in OAT";
                                              [self prepareChartComp];                       
                                              [self computeClimbUniversal: @"DA42"];                        
                                          }
                                           
                                           if ([ AC_Type  rangeOfString:@"SR22"].location != NSNotFound      ) {
                                               maxPAforThisComputation = 25000;  
                                               CruiseMaxElevation = 25000;
                                               CruiseElevationincrement = 2500;
                                               CruiseMaxDistance = 1000;
                                               maxClimbDistanceForGraph = 70;
                                               maxClimbDistanceSteps = 10;
                                               chartNumberForResult = nChart;  
                                               _labelClimbTempCorrectionInfo.text = @"Includes 10% to computed values for each 10ºC above standard";
                                               [self prepareChartComp];                       
                                               [self computeClimbUniversal: @"SR22TG6"];                        
                                           }
                                           
                                           if ([ AC_Type  isEqualToString:@"P2010"]    ) {
                                               maxPAforThisComputation = 14000;  
                                               CruiseMaxElevation = 14000;
                                               CruiseElevationincrement = 2000;
                                               CruiseMaxDistance = 500;
                                               maxClimbDistanceForGraph = 60;
                                               maxClimbDistanceSteps = 10;
                                               chartNumberForResult = nChart; 
                                               _labelConditionsClimb.text = @"En-Route @ 2557lbs/1160kg, @ ISA temp, Fuel Flow: 14gal/h - 53ltr/h";
                                               
                                               [self prepareChartComp];                       
                                               [self computeClimbUniversal: @"P2010"];                        
                                           }
                                           
                                           if ([ AC_Type  isEqualToString:@"P2008JC"]    ) {
                                               maxPAforThisComputation = 14000;  
                                               CruiseMaxElevation = 14000;
                                               CruiseElevationincrement = 2000;
                                               CruiseMaxDistance = 500;
                                               maxClimbDistanceForGraph = 60;
                                               maxClimbDistanceSteps = 10;
                                               chartNumberForResult = nChart; 
                                               _labelConditionsClimb.text = @"En-Route @ 1389lbs/630kg, @ ISA temp, Fuel Flow: 14gal/h - 53ltr/h";
                                               
                                               [self prepareChartComp];                       
                                               [self computeClimbUniversal: @"P2010"];                        
                                           }
                                           
                                           if ([ AC_Type  isEqualToString:@"P2006T"]    ) {
                                               maxPAforThisComputation = 14000;  
                                               CruiseMaxElevation = 14000;
                                               CruiseElevationincrement = 2000;
                                               CruiseMaxDistance = 500;
                                               maxClimbDistanceForGraph = 60;
                                               maxClimbDistanceSteps = 10;
                                               chartNumberForResult = nChart; 
                                               _labelConditionsClimb.text = @"En-Route Vy @ 2712lbs/1230kg, @ ISA temp, Fuel Flow: 10.5al/h - 40ltr/h";
                                               
                                               [self prepareChartComp];                       
                                               [self computeClimbUniversal: @"P2006"];                        
                                           }
                        
                    }
                    
                    
                  
                    
                    
                    //adjust
                                
                    [self writeButtonLabels];
                    
                    
                    
                }else if ([ [infoArray objectAtIndex:3]  rangeOfString:@"CruiseComp"].location != NSNotFound      ) {
                    
                    //NSLog(@"CruiseComp nChart %d", nChart  );
                    chartNumberForResult = nChart; 
                    
                    [self prepareChartComp];
                    
                    [self computeCruiseUniversal]; 
                    
                    
                    
                    
                    [self writeButtonLabels];
                    
                    
                    
                }else {
                    //NSLog(@"unitResult %@", unitResult  );
                    
                    [self loopAllPartsAndSaveResults];
                    chartNumberForResult = nChart;             
                    [self writeButtonLabels]; 
                    
                }
               
                
                
            }else if (flagCeilingComputation == 2) {
                //NSLog(@"flagCeilingComputationnew");
                // calc ceiling
                minResult = 0;
                maxResult = 9999;
                float hpMerker = Hp;
                float OATmerker = OAT;
                
                float internalHp =0;
                float internalOAT =0;
                
                for (int i = 1; i < 450; i++) {
                    internalHp = [[infoPartArray objectAtIndex: 18] floatValue] - ( i * 100); // this is max input Y elevation
                    // get temperature for PA
                    float tempISAatSimElevation = 15 - ( 1.98 * (internalHp / 1000)  );
                    internalOAT = tempISAatSimElevation + ISADiff;
                    
                    ceilingInputYAxis = internalHp;                    
                    ceilingInputCurve = internalOAT;
                    
                    //NSLog(@"internalHp  %.0f", internalHp);
                    //NSLog(@"internalOAT %.0f", internalOAT);   
                           
                    [self getInfoForCurrentChart];
                    [self loopAllPartsAndSaveResults];
                    //NSLog(@"resultComputation %.0f ", resultComputation);
                    
                    // ROC Ceiling
                    if (resultComputation > 50.0) {
                        float paCalc = ((29.92 - altimeterInches) *1000 );
                        resultComputation = ceilingInputYAxis - paCalc ;
                        //NSLog(@"1 ROC CEILING MSL   %f", resultComputation );
                        break;
                    }
                }
                
                Hp = hpMerker;
                OAT = OATmerker;
                [resultsAllChartNames addObject: chartNameForThisInfoFile];
                [resultsAllChartUserNames addObject: chartUserName];
                [resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagInputDataOutOfRange]];
                [resultsAllChartValues addObject: [ [NSString alloc] initWithFormat:@"%.5f", resultComputation ]];
                [resultsAllUnits addObject:unitResult];
                
                chartNumberForResult = nChart;             
                [self writeButtonLabels];
                
            }else{
                
              
                
                
                float maxCeilingValue = 20000;
                
                if (yToX == 1) {
                    maxCeilingValue = [[infoPartArray objectAtIndex: 18] floatValue] +50;
                }
                
                
                float minCeilingValue = 0;
                if (infoArray.count >4) {
                    maxCeilingValue = [[infoArray objectAtIndex:3] floatValue];
                    minCeilingValue = [[infoArray objectAtIndex:4] floatValue];
                    //NSLog(@"maxCeilingValue  %.0f", maxCeilingValue);
                    //NSLog(@"minCeilingValue  %.0f", minCeilingValue);
                }
                
                // calc ceiling
                minResult = 0;
                maxResult = 9999;
                float hpMerker = Hp;
                float OATmerker = OAT;
                
                // fine tune
                float maxAlt1 = 0;
                float maxAlt2 = 0;
                float maxAlt3 = 0;
                
               
                for (int i = 1; i < 50; i++) {
                  
                    totalCeilingSteps1 = totalCeilingSteps1 + 1;
                    Hp = maxCeilingValue - ( i * 5000);
                    if (Hp <= minCeilingValue) {
                        Hp = minCeilingValue;
                    }
                    // get temperature for PA
                    float tempISAatSimElevation = 15 - ( 1.98 * (Hp / 1000)  );
                    OAT = tempISAatSimElevation + ISADiff;
                    [self getInfoForCurrentChart];
                    [self loopAllPartsAndSaveResults];
                    
                    // OGE / IGE ceiling
                    if (resultComputation > acWeight || Hp <= minCeilingValue ) {
                        float paCalc = ((29.92 - altimeterInches) *1000 );
                        maxAlt1 = Hp - paCalc +5000 ;
                        //NSLog(@"maxAlt1   %f", maxAlt1 );
                        break;
                    }
                }
                
              
                for (int i = 1; i < 450; i++) {
                    totalCeilingSteps2 = totalCeilingSteps2 + 1;
                    Hp = maxAlt1 - ( i * 1000);
                    if (Hp <= minCeilingValue) {
                        Hp = minCeilingValue;
                    }
                    // get temperature for PA
                    float tempISAatSimElevation = 15 - ( 1.98 * (Hp / 1000)  );
                    OAT = tempISAatSimElevation + ISADiff;
                    [self getInfoForCurrentChart];
                    [self loopAllPartsAndSaveResults];
                    // OGE / IGE ceiling
                    if (resultComputation > acWeight || Hp <= minCeilingValue) {
                        float paCalc = ((29.92 - altimeterInches) *1000 );
                        maxAlt2 = Hp - paCalc +1000 ;
                        //NSLog(@"maxAlt2   %f", maxAlt2 );
                        break;
                    }
                }
                
                
                
                for (int i = 1; i < 450; i++) {
                    
                    totalCeilingSteps3 = totalCeilingSteps3 + 1;
                    Hp = maxAlt2 - ( i * 200);
                    if (Hp <= minCeilingValue) {
                        Hp = minCeilingValue;
                    }
                    // get temperature for PA
                    float tempISAatSimElevation = 15 - ( 1.98 * (Hp / 1000)  );
                    OAT = tempISAatSimElevation + ISADiff;
                    [self getInfoForCurrentChart];
                    [self loopAllPartsAndSaveResults];
                    // OGE / IGE ceiling
                    if (resultComputation > acWeight || Hp <= minCeilingValue) {
                        float paCalc = ((29.92 - altimeterInches) *1000 );
                          maxAlt3 = Hp - paCalc + 200;
                         //NSLog(@"maxAlt3   %f", maxAlt3 );
                         //NSLog(@"CEILING MSL   %f", resultComputation );
                        break;
                    }
                }
                
             
                for (int i = 1; i < 450; i++) {
                    
                    totalCeilingSteps4 = totalCeilingSteps4 + 1;
                    
                    Hp = maxAlt3 - ( i * 50);
                    if (Hp <= minCeilingValue) {
                        Hp = minCeilingValue;
                    }
                    // get temperature for PA
                    float tempISAatSimElevation = 15 - ( 1.98 * (Hp / 1000)  );
                    OAT = tempISAatSimElevation + ISADiff;
                    [self getInfoForCurrentChart];
                    [self loopAllPartsAndSaveResults];
                    // OGE / IGE ceiling
                    if (resultComputation > acWeight || Hp <= minCeilingValue) {
                        float paCalc = ((29.92 - altimeterInches) *1000 );
                        resultComputation = Hp - paCalc ;
                        //NSLog(@"CEILING MSL   %f", resultComputation );
                        break;
                    }
                }
                Hp = hpMerker;
                OAT = OATmerker;
                [resultsAllChartNames addObject: chartNameForThisInfoFile];
                [resultsAllChartUserNames addObject: chartUserName];
                [resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagInputDataOutOfRange]];
                [resultsAllChartValues addObject: [ [NSString alloc] initWithFormat:@"%.5f", resultComputation ]];
                [resultsAllUnits addObject:unitResult];
                chartNumberForResult = nChart;
                [self writeButtonLabels];
                
                
            }
            
            
            
            
            if (selectedChartButton == actualButtonNumber) {
                
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
             
            }
           
            
            
            
            
            
        }
        
      
        if (numberOfChartsToCombine == 2) {
            //NSLog(@"do the next two charts"  );
            
            unitResult = @"-";
            
            chartNameForCriteria = chartNameForThisInfoFile;
            
            //NSLog(@"1 chartNameForCriteria %@", chartNameForCriteria);
            
                
            //1
            if (flagCeilingComputation == 0) {
                [self loopAllPartsAndSaveResults];
            }
            
            
            if (flagCeilingComputation == 2) {
               //NSLog(@"flagCeilingComputation ");
                // calc ceiling
                minResult = 0;
                maxResult = 9999;
                float hpMerker = Hp;
                float OATmerker = OAT;
                for (int i = 1; i < 450; i++) {
                    Hp = 20000 - ( i * 100);
                    // get temperature for PA
                    float tempISAatSimElevation = 15 - ( 1.98 * (Hp / 1000)  );
                    OAT = tempISAatSimElevation + ISADiff;
                    [self getInfoForCurrentChart];
                    [self loopAllPartsAndSaveResults];
                    //NSLog(@"resultComputation %.0f ", resultComputation);
                    
                    // ROC Ceiling
                    if (resultComputation > 50.0) {
                        float paCalc = ((29.92 - altimeterInches) *1000 );
                        resultComputation = Hp - paCalc ;
                        //NSLog(@"1 ROC CEILING MSL   %f", resultComputation );
                        break;
                    }
                }
                
                Hp = hpMerker;
                OAT = OATmerker;
                [resultsAllChartNames addObject: chartNameForThisInfoFile];
                [resultsAllChartUserNames addObject: chartUserName];
                [resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagInputDataOutOfRange]];
                [resultsAllChartValues addObject: [ [NSString alloc] initWithFormat:@"%.5f", resultComputation ]];
                [resultsAllUnits addObject:unitResult];
            }
            
            
            // show chart depening on criteria
            if (selectedChartButton == actualButtonNumber & criteriaValue <= criteriaValueMid1  ) {
                //NSLog(@"1 ??");
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            
            //2
            nChart ++; actualChartNumber = actualChartNumber + 1;
            [self getInfoForCurrentChart];
            chartNameForCriteria = chartNameForThisInfoFile;
            //NSLog(@"2 chartNameForCriteria %@", chartNameForCriteria);
            
            
            if (flagCeilingComputation == 0) {
                [self loopAllPartsAndSaveResults];
            }
            if (flagCeilingComputation == 2) {
                // calc ceiling
                minResult = 0;
                maxResult = 9999;
                float hpMerker = Hp;
                float OATmerker = OAT;
                
                for (int i = 1; i < 450; i++) {
                    Hp = 20000 - ( i * 100);
                    // get temperature for PA
                    float tempISAatSimElevation = 15 - ( 1.98 * (Hp / 1000)  );
                    OAT = tempISAatSimElevation + ISADiff;
                    [self getInfoForCurrentChart];
                    [self loopAllPartsAndSaveResults];
                    
                    // ROC Ceiling
                    if (resultComputation > 50.0) {
                        float paCalc = ((29.92 - altimeterInches) *1000 );
                        resultComputation = Hp - paCalc ;
                        //NSLog(@"2 ROC CEILING MSL   %f", resultComputation );
                        break;
                    }
                }
                
                Hp = hpMerker;
                OAT = OATmerker;
                [resultsAllChartNames addObject: chartNameForThisInfoFile];
                [resultsAllChartUserNames addObject: chartUserName];
                [resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagInputDataOutOfRange]];
                [resultsAllChartValues addObject: [ [NSString alloc] initWithFormat:@"%.5f", resultComputation ]];
                [resultsAllUnits addObject:unitResult];
            }
            
            
      
            
            // show chart depening on criteria
            if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid1   ) {
                //NSLog(@"selectedChartButton == actualButtonNumber ??");
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            
            //NSLog(@"1criteriaValue %.0f", criteriaValue);
            //NSLog(@"1criteriaValueMid1 %.0f", criteriaValueMid1);
            // now make decison what chart has result and what chart is to display
            
            if (criteriaValue <= criteriaValueMid1  ) {
                 //NSLog(@"case 1");
                chartNumberForResult  = nChart -1;
               
                // get info file for this part
                arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@", chartNameForThisInfoFile, infoPartNumber, @"infoFile" ];
                infoPartArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
                //NSLog(@"infoPartArray %@", infoPartArray);
            }
            
            if (criteriaValue > criteriaValueMid1 ) {
                //NSLog(@"case 2");
                chartNumberForResult  = nChart;
            }
            
            //NSLog(@"1chartNumberForResult %d", chartNumberForResult);
            
             [self writeButtonLabels];
            
            
        }// end compute two charts
        
       
        
        if (numberOfChartsToCombine == 3) {
            //NSLog(@"do the next three charts"  );
            
            unitResult = @"-";
            //1
            [self loopAllPartsAndSaveResults];
            // show chart depening on criteria
            
            if (selectedChartButton == actualButtonNumber & criteriaValue <= criteriaValueMid1  ) {
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            
            //2
            nChart ++; actualChartNumber = actualChartNumber + 1;
            [self getInfoForCurrentChart];
            [self loopAllPartsAndSaveResults];
            
            if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2   ) {
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            
            
            //3
            nChart ++; actualChartNumber = actualChartNumber + 1;
            [self getInfoForCurrentChart];
            [self loopAllPartsAndSaveResults];
         
            
            if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid2   ) {
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            
            
            
            // now make decison what chart has result and what chart is to display
            if (criteriaValue <= criteriaValueMid1  ) {
                chartNumberForResult  = nChart -2;
            }
            
            if (criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2 ) {
                chartNumberForResult  = nChart -1;
            }
            
            if (criteriaValue > criteriaValueMid2 ) {
                chartNumberForResult  = nChart;
            }
            
            if (nChart == 2) {
                //NSLog(@" %@ = %@", [resultsAllChartNames objectAtIndex:2] , [resultsAllChartValues objectAtIndex:2]  );
            }
            
            [self writeButtonLabels];
            
            
            
        }// end compute two charts
        
        if (numberOfChartsToCombine == 4) {
            //NSLog(@"do the next three charts"  );
            
            //1
            [self loopAllPartsAndSaveResults];
            // show chart depening on criteria
            if (selectedChartButton == actualButtonNumber & criteriaValue <= criteriaValueMid1  ) {
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            //2
            nChart ++; actualChartNumber = actualChartNumber + 1;
            [self getInfoForCurrentChart];
            [self loopAllPartsAndSaveResults];
            if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2   ) {
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            //3
            nChart ++; actualChartNumber = actualChartNumber + 1;
            [self getInfoForCurrentChart];
            [self loopAllPartsAndSaveResults];
            if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid2 & criteriaValue <= criteriaValueMid3   ) {
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            //4
            nChart ++; actualChartNumber = actualChartNumber + 1;
            [self getInfoForCurrentChart];
            [self loopAllPartsAndSaveResults];
            if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid3   ) {
                chartNameToLoad = chartNameForThisInfoFile;
                [self drawCrossesAndLines];
                [self loadChartImage];
            }
            
            
            // now make decison what chart has result and what chart is to display
            if (criteriaValue <= criteriaValueMid1  ) {
                chartNumberForResult  = nChart -3;
            }
            if (criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2 ) {
                chartNumberForResult  = nChart -2;
            }
            if (criteriaValue > criteriaValueMid2 & criteriaValue <= criteriaValueMid3 ) {
                chartNumberForResult  = nChart -1;
            }
            if (criteriaValue > criteriaValueMid3 ) {
                chartNumberForResult  = nChart;
            }
            [self writeButtonLabels];
            
        }// end compute 4 charts
        
        if (numberOfChartsToCombine == 5) {
                       //NSLog(@"do the next five charts"  );
                       
                       //1
                       [self loopAllPartsAndSaveResults];
                       // show chart depening on criteria
                       if (selectedChartButton == actualButtonNumber & criteriaValue <= criteriaValueMid1  ) {
                           chartNameToLoad = chartNameForThisInfoFile;
                           [self drawCrossesAndLines];
                           [self loadChartImage];
                       }
                       //2
                       nChart ++; actualChartNumber = actualChartNumber + 1;
                       [self getInfoForCurrentChart];
                       [self loopAllPartsAndSaveResults];
                       if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2   ) {
                           chartNameToLoad = chartNameForThisInfoFile;
                           [self drawCrossesAndLines];
                           [self loadChartImage];
                       }
                       //3
                       nChart ++; actualChartNumber = actualChartNumber + 1;
                       [self getInfoForCurrentChart];
                       [self loopAllPartsAndSaveResults];
                       if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid2 & criteriaValue <= criteriaValueMid3   ) {
                           chartNameToLoad = chartNameForThisInfoFile;
                           [self drawCrossesAndLines];
                           [self loadChartImage];
                       }
                       //4
                       nChart ++; actualChartNumber = actualChartNumber + 1;
                       [self getInfoForCurrentChart];
                       [self loopAllPartsAndSaveResults];
                       if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid3 & criteriaValue <= criteriaValueMid4   ) {
                           chartNameToLoad = chartNameForThisInfoFile;
                           [self drawCrossesAndLines];
                           [self loadChartImage];
                       }
                       
                       //5
                       nChart ++; actualChartNumber = actualChartNumber + 1;
                       [self getInfoForCurrentChart];
                       [self loopAllPartsAndSaveResults];
                       if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid4 & criteriaValue <= criteriaValueMid5   ) {
                           chartNameToLoad = chartNameForThisInfoFile;
                           [self drawCrossesAndLines];
                           [self loadChartImage];
                       }
                       
                       
                       // now make decison what chart has result and what chart is to display
                       
                       if (criteriaValue <= criteriaValueMid1  ) {
                           chartNumberForResult  = nChart -4;
                       }
                       if (criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2 ) {
                           chartNumberForResult  = nChart -3;
                       }
                       if (criteriaValue > criteriaValueMid2 & criteriaValue <= criteriaValueMid3 ) {
                           chartNumberForResult  = nChart -2;
                       }
                       if (criteriaValue > criteriaValueMid3 & criteriaValue <= criteriaValueMid4 ) {
                           chartNumberForResult  = nChart -1;
                       }                       
                       if (criteriaValue > criteriaValueMid4 ) {
                           chartNumberForResult  = nChart;
                       }
                       [self writeButtonLabels];
                       
                   }// end compute 4 charts
        
        
        
          
        if (numberOfChartsToCombine == 6) {
                //NSLog(@"do the next three charts"  );
                
                //1
                [self loopAllPartsAndSaveResults];
                // show chart depening on criteria
                if (selectedChartButton == actualButtonNumber & criteriaValue <= criteriaValueMid1  ) {
                    chartNameToLoad = chartNameForThisInfoFile;
                    [self drawCrossesAndLines];
                    [self loadChartImage];
                }
                //2
                nChart ++; actualChartNumber = actualChartNumber + 1;
                [self getInfoForCurrentChart];
                [self loopAllPartsAndSaveResults];
                if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2   ) {
                    chartNameToLoad = chartNameForThisInfoFile;
                    [self drawCrossesAndLines];
                    [self loadChartImage];
                }
                //3
                nChart ++; actualChartNumber = actualChartNumber + 1;
                [self getInfoForCurrentChart];
                [self loopAllPartsAndSaveResults];
                if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid2 & criteriaValue <= criteriaValueMid3   ) {
                    chartNameToLoad = chartNameForThisInfoFile;
                    [self drawCrossesAndLines];
                    [self loadChartImage];
                }
                //4
                nChart ++; actualChartNumber = actualChartNumber + 1;
                [self getInfoForCurrentChart];
                [self loopAllPartsAndSaveResults];
                if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid3 & criteriaValue <= criteriaValueMid4   ) {
                    chartNameToLoad = chartNameForThisInfoFile;
                    [self drawCrossesAndLines];
                    [self loadChartImage];
                }
                
                //5
                nChart ++; actualChartNumber = actualChartNumber + 1;
                [self getInfoForCurrentChart];
                [self loopAllPartsAndSaveResults];
                if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid4 & criteriaValue <= criteriaValueMid5   ) {
                    chartNameToLoad = chartNameForThisInfoFile;
                    [self drawCrossesAndLines];
                    [self loadChartImage];
                }
                
                //6
                nChart ++; actualChartNumber = actualChartNumber + 1;
                [self getInfoForCurrentChart];
                [self loopAllPartsAndSaveResults];
                if (selectedChartButton == actualButtonNumber & criteriaValue > criteriaValueMid5   ) {
                    chartNameToLoad = chartNameForThisInfoFile;
                    [self drawCrossesAndLines];
                    [self loadChartImage];
                }
                
                
                // now make decison what chart has result and what chart is to display
                
                if (criteriaValue <= criteriaValueMid1  ) {
                    chartNumberForResult  = nChart -5;
                }
                if (criteriaValue > criteriaValueMid1 & criteriaValue <= criteriaValueMid2 ) {
                    chartNumberForResult  = nChart -4;
                }
                if (criteriaValue > criteriaValueMid2 & criteriaValue <= criteriaValueMid3 ) {
                    chartNumberForResult  = nChart -3;
                }
                if (criteriaValue > criteriaValueMid3 & criteriaValue <= criteriaValueMid4 ) {
                    chartNumberForResult  = nChart -2;
                }
                if (criteriaValue > criteriaValueMid4 & criteriaValue <= criteriaValueMid5 ) {
                    chartNumberForResult  = nChart -1;
                }
                if (criteriaValue > criteriaValueMid5 ) {
                    chartNumberForResult  = nChart;
                }
                [self writeButtonLabels];
                
            }// end compute 6 charts
  
        //NSLog(@"infoPartArray %@", infoPartArray);
        
         if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomR44"].location != NSNotFound) {
             
             if (selectedChartButton == actualButtonNumber) {                 
                 NSString *viewString = [infoArray objectAtIndex:5] ;
                 //NSLog(@"infoArray %@", infoArray);
                 //NSLog(@"viewString %@", viewString);
                 if ([viewString isEqualToString:@"viewR44Manifold"]) {
                     _viewR44Manifold.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewR44Manifold];
                     flagCustomPageIsOn = 1;
                 }   
                 
                 if ([viewString isEqualToString:@"viewR44VNE"]) {
                     _viewR44VNE.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewR44VNE];
                     flagCustomPageIsOn = 1;
                 } 
                 
                 
                 //chartNameToLoad = chartNameForThisInfoFile;
             }
         }
        
        
        if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound) {
            
            // open special pages for fixed wing stuff
            if (selectedChartButton == actualButtonNumber) {
                
                NSString *viewString = [infoArray objectAtIndex:5] ;
                //NSLog(@"infoArray %@", infoArray);
                //NSLog(@"viewString %@", viewString);
                if ([viewString isEqualToString:@"viewTakeoff"]) {
                    _viewTakeoff.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewTakeoff];
                    flagCustomPageIsOn = 1;
                }
                if ([viewString isEqualToString:@"viewClimb"]) {
                    _viewClimb.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewClimb];
                    flagCustomPageIsOn = 1;
                }
                if ([viewString isEqualToString:@"viewCruise"]) {
                    _viewCruise.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewCruise];
                    flagCustomPageIsOn = 1;
                }
                if ([viewString isEqualToString:@"viewLanding"]) {
                    _viewLanding.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewLanding];
                    flagCustomPageIsOn = 1;
                }
                chartNameToLoad = chartNameForThisInfoFile;
            }
            
        }
        
        
        //NSLog(@"flagCustomPageIsOn %d", flagCustomPageIsOn);            
        //NSLog(@"do this");        
        //NSLog(@"infoArray %@", infoArray);        
        //NSLog(@"chartNumberForResult %d", chartNumberForResult);
        
        if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  ) {
           //NSLog(@"111userNameForComputation %@", userNameForComputation);            
            originalPerformanceDistanceUnits = [infoPartArray objectAtIndex:14];            
            //NSLog(@"1 userNameForComputation %@", userNameForComputation);
            //NSLog(@"1 chartUserName %@", chartUserName);
            
            if ([userNameForComputation isEqualToString:@"CruiseComp"]) {
                OAT_Cruise = OAT;
                PA_Cruise = Hp;
                Wind_Cruise = headWindKTS;
               
            } 
            
            if ([userNameForComputation isEqualToString:@"ClimbComp"]) {
                OAT_Climb = OAT;
                PA_Climb = Hp;
                Wind_Climb= headWindKTS;
               
            } 
            
            if ([userNameForComputation isEqualToString:@"TOGroundRoll"]) {
                //NSLog(@"TOGroundRoll originalPerformanceDistanceUnits %@", originalPerformanceDistanceUnits);
                //NSLog(@"resultFromComputations %.0f", resultFromComputations);
                if ([originalPerformanceDistanceUnits isEqualToString:@"m"] ) {
                    resultFromComputations =  resultFromComputations / 0.3048;                   
                }
                resultTOGroundRoll = resultFromComputations;
                //NSLog(@"resultTOGroundRoll %.0f", resultTOGroundRoll);
            }            
            if ([userNameForComputation isEqualToString:@"TO50ft"]) {
                //NSLog(@"TO50ft originalPerformanceDistanceUnits %@", originalPerformanceDistanceUnits);
                 //NSLog(@"resultFromComputations %.0f", resultFromComputations);
                if ([originalPerformanceDistanceUnits isEqualToString:@"m"] ) {
                    resultFromComputations =  resultFromComputations / 0.3048;
                }
                resultTO50ft = resultFromComputations;
                //NSLog(@"resultTO50ft %.0f", resultTO50ft);
            }
            if ([userNameForComputation isEqualToString:@"LDGGroundRoll"]) {
                if ([originalPerformanceDistanceUnits isEqualToString:@"m"] ) {
                    resultFromComputations =  resultFromComputations / 0.3048;
                }
                resultLDGGroundRoll = resultFromComputations;
                //NSLog(@"resultLDGGroundRoll %.0f", resultLDGGroundRoll);
               
            }
            if ([userNameForComputation isEqualToString:@"LDG50ft"]) {
                if ([originalPerformanceDistanceUnits isEqualToString:@"m"] ) {
                    resultFromComputations =  resultFromComputations / 0.3048;
                }
                resultLDG50ft = resultFromComputations;
                //NSLog(@"resultLDG50ft %.0f", resultLDG50ft);
            }        
            if ([userNameForComputation isEqualToString:@"TO50ft"]) {
                //NSLog(@"acWeight %.0f", acWeight);                        
                //NSLog(@"1 windSpeedTO %.0f", windSpeedTO);
                [self computeTakeoff_UniversalFixedWing];
                [self animateFixedWingTakeoff];
                OAT_TO = OAT;
                PA_TO = Hp;
                Wind_TO = headWindKTS;                
            }
            if ([userNameForComputation isEqualToString:@"LDG50ft"]) {
                //NSLog(@"acLandingWeight %.0f", acLandingWeight);                       
                //NSLog(@"2 windSpeedLD %.0f", windSpeedLD);
                [self computeLanding_UniversalFixedWing];
                [self animateFixedWingLanding];
                OAT_LD = OAT;
                PA_LD = Hp;
                Wind_LD = headWindKTS;
                
            }
            
             
            
            
        }
        
        triggerPerformanceOutOfRange = 0;
        if (criteriaValue < criteriaValueMid1  ) {
            triggerPerformanceOutOfRange = 1;
            //NSLog(@"triggerPerformanceOutOfRange = 1 ", triggerPerformanceOutOfRange);
        }
        
        
    }// end do all charts
    
    
    previousmMaxPAforThisComputation =  maxPAforThisComputation;
    //NSLog(@"end*------------------");
   
   
    
     //NSLog(@"do that");

    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  ) {
        
        // this is NOT for Cessna!
        //NSLog(@"und nun...frohe Weihnachten 2018!");        
        // mal wieder hier in Malta Ende Juni 2019
        // mal wieder hier vor Elba 17. Juni 2020 Corona
        //NSLog(@"resultLDGGroundRoll %.0f", resultLDGGroundRoll);        
        
        ViewController *parent = (ViewController *)self.parentViewController;
        
        //takeoff ************************************
        
        dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   1 + 200  ];
        if (_segmentMeterFeet.selectedSegmentIndex == 0) {
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0f'", resultTOGroundRoll,  resultTO50ft ];            
        }else{
            dL.text = [ [NSString alloc] initWithFormat:@"%.0fm/%.0fm", resultTOGroundRoll,  resultTO50ft ];
        }
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
        
        NSString *enviText =   [ [NSString alloc] initWithFormat:@"%@|%@|%.0f|%.0f|%.0f|%@", @"Takeoff", dL.text ,OAT_TO, PA_TO, Wind_TO, @"FXX" ]; 
        //NSLog(@"1 enviText %@", enviText);
        if (resultsAllEnviSettings.count > 0) {
             [resultsAllEnviSettings replaceObjectAtIndex:0 withObject:enviText];
        }
        
       //climbComp ************************************
      
        dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   2 + 200  ];
         dL.text = [ [NSString alloc] initWithFormat:@"%@ / %@", _iClimbTimeTotal.text, _iClimbDistanceTotal.text];
        [dL setFont:[UIFont boldSystemFontOfSize:14]];
        
        enviText =   [ [NSString alloc] initWithFormat:@"%@|%@|%.0f|%.0f|%.0f|%@", @"ClimbComp", dL.text ,OAT_Climb, PA_Climb, Wind_Climb, @"FXX" ]; 
        //NSLog(@"2 enviText %@", enviText);
        if (resultsAllEnviSettings.count > 1) {        
            [resultsAllEnviSettings replaceObjectAtIndex:1 withObject:enviText];
        }
        
        //landing ************************************
        
        if (![resultsAllChartUserNames containsObject: @"ClimbComp"]) {
            dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   2 + 200  ];
        }else{
            dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   3 + 200  ];
        }

        
       
        
        if (_segmentMeterFeet.selectedSegmentIndex == 0) {
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0f'", resultLDGGroundRoll,  resultLDG50ft ];
        }else{
            dL.text = [ [NSString alloc] initWithFormat:@"%.0fm/%.0fm", resultLDGGroundRoll,  resultLDG50ft ];
        }
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
        
        enviText =   [ [NSString alloc] initWithFormat:@"%@|%@|%.0f|%.0f|%.0f|%@", @"Landing", dL.text ,OAT_LD, PA_LD, Wind_LD, @"FXX" ]; 
        //NSLog(@"3 enviText %@", enviText);
        if (resultsAllEnviSettings.count > 1) {        
            [resultsAllEnviSettings replaceObjectAtIndex:2 withObject:enviText];
        }
        
        
        //CruiseComp ************************************
        
        dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   4 + 200  ];
        
        dL.text = [ [NSString alloc] initWithFormat:@"MAX %.0f NM", totalTripRange ];
         [dL setFont:[UIFont boldSystemFontOfSize:14]];
        
        enviText =   [ [NSString alloc] initWithFormat:@"%@|%@|%.0f|%.0f|%.0f|%@", @"CruiseComp", dL.text ,OAT_Cruise, PA_Cruise, Wind_Cruise, @"FXX" ]; 
        //NSLog(@"4 enviText %@", enviText);
        if (resultsAllEnviSettings.count > 1) {        
            [resultsAllEnviSettings replaceObjectAtIndex:3 withObject:enviText];
        }
        
        //************************************************************************************************************************************************
      
        
        if (selectedChartButton == 1) {
            //NSLog(@"1 selectedChartButton");
            _viewTakeoff.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewTakeoff];
        }        
        if (selectedChartButton == 2) {
            //NSLog(@"2 selectedChartButton");
            //sdf
            //_viewClimb.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewClimb];
            
            _viewLanding.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewLanding];
            
        }        
        if (selectedChartButton == 3) {
            //NSLog(@"2 selectedChartButton");
            _viewLanding.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewLanding];
        }        
        if (selectedChartButton == 4) {
            //NSLog(@"2 selectedChartButton");
            _viewCruise.hidden = NO; [_viewChartContainer bringSubviewToFront:_viewCruise];
        }
        
        
    }
    

    //NSLog(@"resultsAllChartUserNames %@", resultsAllChartUserNames);
    //NSLog(@"resultsAllChartValues %@", resultsAllChartValues);
    
    
    [[NSUserDefaults standardUserDefaults]  setObject: resultsAllEnviSettings       forKey:@"resultsAllEnviSettings"];    
    [[NSUserDefaults standardUserDefaults]  setObject: resultsAllChartUserNames       forKey:@"resultsAllChartUserNames"];
    [[NSUserDefaults standardUserDefaults]  setObject: resultsAllChartValues       forKey:@"resultsAllChartValues"];
    [[NSUserDefaults standardUserDefaults]  setObject: resultsAllUnits       forKey:@"resultsAllUnits"];
    [[NSUserDefaults standardUserDefaults]  setObject: resultsAllPrintOnManifest       forKey:@"resultsAllPrintOnManifest"];
    
    
    
    
    if (flagWeHavePenaltyData == 1) {  
        //NSLog(@"totalAirspeedPenalty %.0f", totalAirspeedPenalty);  
        ViewController *parent = (ViewController *)self.parentViewController;
        UILabel *label =(UILabel*)[parent.viewOptions viewWithTag: 1000] ;
        [label  setText: [ [NSString alloc] initWithFormat:@"TAS Penalty = %.0f km/h", totalAirspeedPenalty ] ];        
        label =(UILabel*)[parent.viewOptions viewWithTag: 1001] ;
        [label  setText: [ [NSString alloc] initWithFormat:@"Fuel Flow Penalty = %.0f kg/h", totalFuelFlowPenalty ] ];        
        label =(UILabel*)[parent.viewOptions viewWithTag: 1002] ;
        [label  setText: [ [NSString alloc] initWithFormat:@"Fuel Range Penalty = %.0f NM", totalRangePenalty ] ];        
    }
    

    
    
     
    //NSLog(@"saving resultsAllEnviSettings %@", resultsAllEnviSettings);
    //NSLog(@"transferValueDictionary %@", transferValueDictionary);
    //NSLog(@"resultsAllCharts %@ , %@", resultsAllChartNames, resultsAllChartValues);
    
    
}

- (void) triggerPresetSliders {

    
    [self presetFixedWingSliders];
    allowFixedWingSliderSaving = 1;
    [self saveFixedWingSliders];
    
}

- (void) presetFixedWingSliders {
    
    
  
    NSString *tempACtype = [[NSUserDefaults standardUserDefaults]  stringForKey: @"tempACtype"]; 
    
        
    //NSLog(@"> presetFixedWingSliders tempACtype %@", tempACtype);
 
    _sliderRundwayHeadingTO.value  = 0;
    _sliderRunwayConditionsTO.value  = 0;
    _sliderSlopeTO.value  = 0;
    _sliderRundwayHeadingLD.value  = 0;
    _sliderRunwayConditionsLD.value  = 0;
    _sliderSlopeLD.value  = 0;
    
    _switchOverrideCruiseInput.on = NO;
    statusOverride = 0;
        
    
    //adjust
    if ([ tempACtype  rangeOfString:@"P2010"].location != NSNotFound  || [ tempACtype  rangeOfString:@"P2008"].location != NSNotFound || [ tempACtype  rangeOfString:@"P2006"].location != NSNotFound    ) {
        
        //takeoff
        _sliderRunwayLength.minimumValue = 1500;
        _sliderRunwayLength.maximumValue = 9000;
        _sliderRunwayLength.value = 2500;
        
        //landing
        _sliderRunwayLengthLD.minimumValue = 1500;
        _sliderRunwayLengthLD.maximumValue = 9000;
        _sliderRunwayLengthLD.value = 2500;
        frwyIncrement = 100;
        
        //cruise
        _sliderTripDistanceNM.minimumValue = 0;
        _sliderTripDistanceNM.maximumValue = 1000;
        _sliderTripDistanceNM.value = 200;
        
        if ([ tempACtype  rangeOfString:@"P2010"].location != NSNotFound ){
             _cruiseInputTAS.text = @"122";
             
             }
        
        if ([ tempACtype  rangeOfString:@"P2006"].location != NSNotFound ){
            _cruiseInputTAS.text = @"122";
           
        }
        
        
    }else if ( [tempACtype  rangeOfString:@"C172"].location != NSNotFound 
              || [tempACtype  rangeOfString:@"C182"].location != NSNotFound 
              || [tempACtype  rangeOfString:@"PA28"].location != NSNotFound 
              || [tempACtype  rangeOfString:@"DA40-180"].location != NSNotFound 
              || [tempACtype  rangeOfString:@"C152"].location != NSNotFound ) {
        
        //takeoff
        _sliderRunwayLength.minimumValue = 1500;
        _sliderRunwayLength.maximumValue = 9000;
        _sliderRunwayLength.value = 2000;
        
        //landing
        _sliderRunwayLengthLD.minimumValue = 1500;
        _sliderRunwayLengthLD.maximumValue = 9000;
        _sliderRunwayLengthLD.value = 2000;
        frwyIncrement = 100;
        
        //cruise
        _sliderTripDistanceNM.minimumValue = 0;
        _sliderTripDistanceNM.maximumValue = 1000;
        _sliderTripDistanceNM.value = 200;
        
        
        if ([ tempACtype  rangeOfString:@"DA40-180"].location != NSNotFound ){
                   _cruiseInputTAS.text = @"125";
                  
               }
        
        
    }else{
        
        //takeoff
        _sliderRunwayLength.minimumValue = 2500;
        _sliderRunwayLength.maximumValue = 9000;
        _sliderRunwayLength.value = 4500;
        
        //landing
        _sliderRunwayLengthLD.minimumValue = 1500;
        _sliderRunwayLengthLD.maximumValue = 9000;
        _sliderRunwayLengthLD.value = 3000;
        frwyIncrement = 100;
        
        //cruise
        _sliderTripDistanceNM.minimumValue = 0;
        _sliderTripDistanceNM.maximumValue = 1000;
        _sliderTripDistanceNM.value = 250;
        
        _cruiseInputTAS.text = @"90";
   
        
                                
                                       
    }
   
    
    ViewController *parent = (ViewController *)self.parentViewController;
    if (parent.self.arrayName21.count > 1) {
       //NSLog(@"preset fuel flow %@", [parent.self.arrayName21 objectAtIndex:27]); 
     
       
        
        // from backend we always get a volume! Gallons or liter
        
        // if backendOriginalFuelUnits = lbs then volume = Gallons
        NSString *backendOriginalFuelUnits =  [parent.arrayName21 objectAtIndex:15];
        
        NSString *backendOriginalFuelFlowAsVolume = [parent.self.arrayName21 objectAtIndex:27]; // preset fuel flow (always a volume)  
            
        // normal case: fuel unit in backend is equal to unit in app and app is in volume
        _cruiseInputFuelFlow.text = backendOriginalFuelFlowAsVolume;
           
        //if not....
            
         if ([backendOriginalFuelUnits isEqualToString:@"lbs"]) {              
               // we have fuel flow info in gallons             
             if ( [selectedUnitForFuel isEqualToString:@"kg"]) { 
                 //NSLog(@"fuelPreset 1");
                 // first we need to convert backend from gallons to liter
                 _cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [[parent.self.arrayName21 objectAtIndex:27]floatValue] * 3.785 ];
                 
                 if ([fuelEnterMode isEqualToString:@"mass"]) {  
                     //NSLog(@"fuelPreset 2");
                   float convertedSpecificFuelDensity = specificFuelDensityValue / 2.2046 / 3.78541;
                   // convert from gallons to liter to kilo    
                  _cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [[parent.self.arrayName21 objectAtIndex:27]floatValue] * 3.785 * convertedSpecificFuelDensity ];    
                 }
                 
             }
             
             if ( [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                  //NSLog(@"fuelPreset 3");
                  // no conversion gallons to gallons              
                  if ([fuelEnterMode isEqualToString:@"mass"]) { 
                      //NSLog(@"fuelPreset 4");
                      //convert gallons to lbs
                      _cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [[parent.self.arrayName21 objectAtIndex:27]floatValue] * specificFuelDensityValue ];  
                  }             
             }
           }
        
        
        if ([backendOriginalFuelUnits isEqualToString:@"kg"]) {              
                      // we have fuel flow info in liter             
                    if ( [selectedUnitForFuel isEqualToString:@"lbs"]) { 
                        //NSLog(@"fuelPreset 5");
                        // first we need to convert backend from liter to gallons
                        _cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [[parent.self.arrayName21 objectAtIndex:27]floatValue] / 3.785 ];
                        
                        if ([fuelEnterMode isEqualToString:@"mass"]) {  
                            //NSLog(@"fuelPreset 6");
                          float convertedSpecificFuelDensity = specificFuelDensityValue * 2.2046 * 3.78541;
                          // convert from liter to gallons to lbs    
                         _cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [[parent.self.arrayName21 objectAtIndex:27]floatValue] / 3.785 * convertedSpecificFuelDensity ];    
                        }                        
                    }                    
                    if ( [selectedUnitForFuel isEqualToString:@"kg"]) { 
                         //NSLog(@"fuelPreset 7");
                         // no conversion liter to liter              
                         if ([fuelEnterMode isEqualToString:@"mass"]) { 
                             //NSLog(@"fuelPreset 8");
                             //convert liter to kg
                             _cruiseInputFuelFlow.text = [ [NSString alloc] initWithFormat:@"%.1f", [[parent.self.arrayName21 objectAtIndex:27]floatValue] * specificFuelDensityValue ];  
                         }             
                    }
                  }
        
        
        
        
         //NSLog(@"presetting _cruiseInputFuelFlow.text %@", _cruiseInputFuelFlow.text); 
        
        
        
        
    }
   
    //NSLog(@"preset _sliderRunwayLength.value %.0f", _sliderRunwayLength.value);
    
    
    _segmentMeterFeet.selectedSegmentIndex = 0;
    _segmentMeterFeetLD.selectedSegmentIndex = 0;
    
    conversionFeetToMeter = 1;
    unitDistance = @"ft";
    
   
    
                     
}

- (void) loadFixedWingSliders {
    
    
    allowFixedWingSliderSaving = 1;
    
    
     NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
    
     //NSLog(@"load FixedWingSliders  vFlightID = %@", vFlightID);
    _sliderRundwayHeadingTO.value = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRundwayHeadingTO" ]];
    _sliderRunwayConditionsTO.value = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRunwayConditionsTO" ]];
    
    
    //NSLog(@"loading _sliderRunwayConditionsTO.value %.0f", _sliderRunwayConditionsTO.value);
    
    
    _sliderSlopeTO.value = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderSlopeTO" ]];
    _sliderRundwayHeadingLD.value = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRundwayHeadingLD" ]];
    _sliderRunwayConditionsLD.value = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRunwayConditionsLD" ]];
    _sliderSlopeLD.value = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderSlopeLD" ]];
    
    
    
    if ([[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderTripDistanceNMmaxVal" ]] > 1) {
        _sliderTripDistanceNM.maximumValue = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderTripDistanceNMmaxVal" ]];
    }
    _sliderTripDistanceNM.value = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderTripDistanceNM" ]];
    _sliderTripDistanceNM.minimumValue  = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderTripDistanceNMminVal" ]];
    
    //NSLog(@"loading _sliderTripDistanceNM.value %@ %.0f", vFlightID, _sliderTripDistanceNM.value);
    
    _sliderEngineRPMcruise.value  = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderEngineRPMcruise" ]];
    _sliderEngineRPMcruise.minimumValue  = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderEngineRPMcruiseminVal" ]];
    _sliderEngineRPMcruise.maximumValue  = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderEngineRPMcruisemaxVal" ]];
    
    
    //NSLog(@"load FixedWingSliders  _sliderTripDistanceNM = %.0f", _sliderTripDistanceNM.value);
    //NSLog(@"load FixedWingSliders  _sliderTripDistanceNM = %.0f", _sliderTripDistanceNM.value);
    //NSLog(@"load FixedWingSliders  _sliderTripDistanceNM = %.0f", _sliderTripDistanceNM.value);
    //NSLog(@"load FixedWingSliders  _sliderTripDistanceNM = %.0f", _sliderTripDistanceNM.value);
    
    _sliderRunwayLength.minimumValue = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMinTO" ]];
    _sliderRunwayLength.maximumValue = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMaxTO" ]];
    _sliderRunwayLength.value  = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyLengthTO" ]];
    
    _sliderRunwayLengthLD.minimumValue = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMinLD" ]];
    _sliderRunwayLengthLD.maximumValue = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMaxLD" ]];
    _sliderRunwayLengthLD.value  = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyLengthLD" ]];
    frwyIncrement = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyIncrement" ]];
    
    //NSLog(@"loading  AC_Type %@ sliderRunwayLength.value %.0f", AC_Type, _sliderRunwayLength.value);
    
    _cruiseInputTAS.text = [[NSUserDefaults standardUserDefaults]  objectForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_cruiseInputTAS" ]];
    _cruiseInputFuelFlow.text = [[NSUserDefaults standardUserDefaults]  objectForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_cruiseInputFuelFlow" ]];
    
    
    
    _segmentMeterFeet.selectedSegmentIndex = [[NSUserDefaults standardUserDefaults]  integerForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_segmentMeterFeet" ]];
    _segmentFlapsLD.selectedSegmentIndex = [[NSUserDefaults standardUserDefaults]  integerForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_segmentFlapsLD" ]];
        
    _segmentCruisePower.selectedSegmentIndex  = [[NSUserDefaults standardUserDefaults]  integerForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_segmentCruisePower" ]];
    
    if (_segmentMeterFeet.selectedSegmentIndex == 0) {
        conversionFeetToMeter = 1;
        unitDistance = @"ft";
    }else{
        conversionFeetToMeter = 0.3048;
        unitDistance = @"m";
    }
    
    
    statusOverride = [[NSUserDefaults standardUserDefaults]  floatForKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"statusOverride" ]];
    if (statusOverride == 1) {
        _switchOverrideCruiseInput.on = YES;
    }else{
      _switchOverrideCruiseInput.on = NO;  
    }
    
     //NSLog(@"loading statusOverride %.0f", statusOverride);
    
    lockACweightOverrideTO = 1; lockACweightOverrideLD = 1;
    UIImage *lock = [UIImage imageNamed:@"lock - locked-01.png"];
    [_lockACweightTO setImage:lock];
    _sliderAircraftWeightOverrideTO.enabled = NO;
    [_lockACweightLD setImage:lock];
    _sliderAircraftWeightOverrideLD.enabled = NO;
   
   
}

- (void) saveFixedWingSliders {
    
    
   
    //we must not save sliders before we loaded on startup!
    
    if (allowFixedWingSliderSaving < 1) {
        //NSLog(@"do not save sliders yet");
        return;
    }
     
    //NSLog(@"saveFixedWingSliders  AC_Type %@", AC_Type);
    
    NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
    //NSLog(@"save FixedWingSliders  vFlightID = %@", vFlightID);
    //NSLog(@"save FixedWingSliders  vFlightID = %@", vFlightID);
    
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderSlopeTO.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderSlopeTO" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayConditionsTO.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRunwayConditionsTO" ]];
    
    //NSLog(@"saving _sliderRunwayConditionsTO.value %.0f", _sliderRunwayConditionsTO.value);
    
    
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRundwayHeadingTO.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRundwayHeadingTO" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderSlopeLD.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderSlopeLD" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayConditionsLD.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRunwayConditionsLD" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRundwayHeadingLD.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderRundwayHeadingLD" ]];
    
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderTripDistanceNM.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderTripDistanceNM" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderTripDistanceNM.minimumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderTripDistanceNMminVal" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderTripDistanceNM.maximumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderTripDistanceNMmaxVal" ]];
    
    //NSLog(@"saving _sliderTripDistanceNM.value %@ %.0f", vFlightID, _sliderTripDistanceNM.value);
    
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderEngineRPMcruise.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderEngineRPMcruise" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderEngineRPMcruise.minimumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderEngineRPMcruiseminVal" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderEngineRPMcruise.maximumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_sliderEngineRPMcruisemaxVal" ]];
    
    
    
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayLength.minimumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMinTO" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayLength.maximumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMaxTO" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayLength.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyLengthTO" ]];
    
    
   
    //NSLog(@"saveFixedWingSliders  AC_Type %@ sliderRunwayLength.value %.0f", AC_Type, _sliderRunwayLength.value);
    
    
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayLengthLD.minimumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMinLD" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayLengthLD.maximumValue     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyMaxLD" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat:_sliderRunwayLengthLD.value     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyLengthLD" ]];
    [[NSUserDefaults standardUserDefaults]  setFloat: frwyIncrement     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"frwyIncrement" ]];
    
    [[NSUserDefaults standardUserDefaults]  setInteger: _segmentMeterFeet.selectedSegmentIndex forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_segmentMeterFeet" ]];
    
    [[NSUserDefaults standardUserDefaults]  setInteger: _segmentFlapsLD.selectedSegmentIndex forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_segmentFlapsLD" ]];
    
    [[NSUserDefaults standardUserDefaults]  setInteger: _segmentCruisePower.selectedSegmentIndex forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_segmentCruisePower" ]];
    
    [[NSUserDefaults standardUserDefaults]  setObject: _cruiseInputTAS.text forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_cruiseInputTAS" ]];
    [[NSUserDefaults standardUserDefaults]  setObject: _cruiseInputFuelFlow.text forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_cruiseInputFuelFlow" ]];
    
   
    if (_switchOverrideCruiseInput.on == YES) {
        statusOverride = 1;
    }else{
        statusOverride = 0;
    }    
    [[NSUserDefaults standardUserDefaults]  setFloat: statusOverride     forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"statusOverride" ]];
    
    //NSLog(@"savin gstatusOverride %.0f", statusOverride);
    
}

- (void) enviLoadSliderData {
    
    //NSLog(@"1 enviLoadSliderData");
    // this loads data for the particular chart > chartUserName
    NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
    NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, chartNameForSliderDefaults ];
    //NSLog(@"loading enviKey =  %@", enviKey);
    envirnomentAdditionalInfo = @"";
    envirnomentAdditionalInfo = [[NSUserDefaults standardUserDefaults]  stringForKey:enviKey];
    ///NSLog(@"loading %@", envirnomentAdditionalInfo );
    
    
}

- (void) enviLoadSliderDataForCopy {
    
    //NSLog(@"1 enviLoadSliderData");
    // this loads data for the particular chart > chartUserName
    //NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
    NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", triggerCopySliderSettingsWithFlightID, chartNameForSliderDefaults ];
    
   
    //NSLog(@"enviLoadSliderDataForCopy enviKey =  %@", enviKey);
    envirnomentAdditionalInfo = @"";
    envirnomentAdditionalInfo = [[NSUserDefaults standardUserDefaults]  stringForKey:enviKey];
    //NSLog(@"loading %@", envirnomentAdditionalInfo );
    
    
}




- (void) enviOverrideAllSliderData {
    
    //NSLog(@"enviOverrideAllSliderData !!!!");
    
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"^"];
    NSArray *components = [envirnomentAdditionalInfo componentsSeparatedByCharactersInSet:charSet];
    
    //NSLog(@"components count %lu", components.count);
    //NSLog(@"components  %@", components);
    
    ViewController *parent = (ViewController *)self.parentViewController;
    
    parent.self.sliderOATforOGE.minimumValue = [[components objectAtIndex:1] floatValue];
    parent.self.sliderOATforOGE.maximumValue = [[components objectAtIndex:2] floatValue];
    parent.self.sliderOATforOGE.value = [[components objectAtIndex:3] floatValue];
    
    parent.self.sliderISADiff.minimumValue = [[components objectAtIndex:4] floatValue];
    parent.self.sliderISADiff.maximumValue = [[components objectAtIndex:5] floatValue];
    parent.self.sliderISADiff.value = [[components objectAtIndex:6] floatValue];
    
    parent.self.sliderMSL.minimumValue = [[components objectAtIndex:7] floatValue];
    parent.self.sliderMSL.maximumValue = [[components objectAtIndex:8] floatValue];
    parent.self.sliderMSL.value = [[components objectAtIndex:9] floatValue];
    
    
    parent.self.sliderQNH.minimumValue = [[components objectAtIndex:10] floatValue];
    parent.self.sliderQNH.maximumValue = [[components objectAtIndex:11] floatValue];
    parent.self.sliderQNH.value = [[components objectAtIndex:12] floatValue];
    parent.self.labelQNH.text = [components objectAtIndex:12];
    parent.self.labelQNHEuro.text = [components objectAtIndex:13];
    
    
    parent.self.titleVariSlider1.text = [ [components objectAtIndex:14] stringByReplacingOccurrencesOfString:@"_" withString:@" "];
    parent.self.unitVariSlider1.text = [components objectAtIndex:15];
    parent.self.sliderHeadwind2.minimumValue = [[components objectAtIndex:16] floatValue];
    parent.self.sliderHeadwind2.maximumValue = [[components objectAtIndex:17] floatValue];
    incrementVariSlider1 = [[components objectAtIndex:18] floatValue];
    parent.self.sliderHeadwind2.value = [[components objectAtIndex:19] floatValue];
    if ([ [components objectAtIndex:19]  rangeOfString:@"L"].location != NSNotFound  ) {
        parent.self.sliderHeadwind2.enabled = NO;
    }else{
        parent.self.sliderHeadwind2.enabled = YES;
    }
    if ([ [components objectAtIndex:14]  rangeOfString:@"OFF"].location != NSNotFound  ) {
        parent.self.viewVariSlider1.hidden = YES;
    }else{
        parent.self.viewVariSlider1.hidden = NO;
    }
    
    parent.self.titleVariSlider2.text = [ [components objectAtIndex:20] stringByReplacingOccurrencesOfString:@"_" withString:@" "];
    parent.self.unitVariSlider2.text = [components objectAtIndex:21];
    parent.self.sliderIAS.minimumValue = [[components objectAtIndex:22] floatValue];
    parent.self.sliderIAS.maximumValue = [[components objectAtIndex:23] floatValue];
    incrementVariSlider2 = [[components objectAtIndex:24] floatValue];
    parent.self.sliderIAS.value = [[components objectAtIndex:25] floatValue];
    if ([ [components objectAtIndex:25]  rangeOfString:@"L"].location != NSNotFound  ) {
        parent.self.sliderIAS.enabled = NO;
    }else{
        parent.self.sliderIAS.enabled = YES;
    }
    if ([ [components objectAtIndex:20]  rangeOfString:@"OFF"].location != NSNotFound  ) {
        parent.self.viewVariSlider2.hidden = YES;
    }else{
        parent.self.viewVariSlider2.hidden = NO;
    }
    
    
    parent.self.titleVariSlider3.text = [ [components objectAtIndex:26] stringByReplacingOccurrencesOfString:@"_" withString:@" "];
    parent.self.unitVariSlider3.text = [components objectAtIndex:27];
    parent.self.sliderRatingIndex.minimumValue = [[components objectAtIndex:28] floatValue];
    parent.self.sliderRatingIndex.maximumValue = [[components objectAtIndex:29] floatValue];
    incrementVariSlider3 = [[components objectAtIndex:30] floatValue];
    parent.self.sliderRatingIndex.value = [[components objectAtIndex:31] floatValue];
    if ([ [components objectAtIndex:22]  rangeOfString:@"L"].location != NSNotFound  ) {
        parent.self.sliderRatingIndex.enabled = NO;
    }else{
        parent.self.sliderRatingIndex.enabled = YES;
    }
    if ([ [components objectAtIndex:26]  rangeOfString:@"OFF"].location != NSNotFound  ) {
        parent.self.viewVariSlider3.hidden = YES;
    }else{
        parent.self.viewVariSlider3.hidden = NO;
    }
    
    
    parent.self.titleVariSlider4.text = [ [components objectAtIndex:32] stringByReplacingOccurrencesOfString:@"_" withString:@" "];
    parent.self.unitVariSlider4.text = [components objectAtIndex:33];
    parent.self.sliderPROPRPM.minimumValue = [[components objectAtIndex:34] floatValue];
    parent.self.sliderPROPRPM.maximumValue = [[components objectAtIndex:35] floatValue];
    incrementVariSlider4 = [[components objectAtIndex:36] floatValue];
    parent.self.sliderPROPRPM.value = [[components objectAtIndex:37] floatValue];
    if ([ [components objectAtIndex:37]  rangeOfString:@"L"].location != NSNotFound  ) {
        parent.self.sliderPROPRPM.enabled = NO;
    }else{
        parent.self.sliderPROPRPM.enabled = YES;
    }
    if ([ [components objectAtIndex:32]  rangeOfString:@"OFF"].location != NSNotFound  ) {
        parent.self.viewVariSlider4.hidden = YES;
    }else{
        parent.self.viewVariSlider4.hidden = NO;
    }
    
    
   
    
    
    //override values
    
    float MSL =  parent.self.sliderMSL.value;
    float paCalc = ((29.92 - parent.self.sliderQNH.value) *1000);
    if (paCalc < 0.001 & paCalc > -0.001) {
        paCalc = 0;
    }
    parent.self.sliderHp.minimumValue = [[components objectAtIndex:7] floatValue];
    parent.self.sliderHp.maximumValue = [[components objectAtIndex:8] floatValue];
    parent.self.sliderHp.value = MSL + paCalc;
    
    //NSLog(@"overriding paCalc %.2f", paCalc);
    
    int   PressAltforDensity = parent.self.sliderHp.value;
    float TKelvin = 273.15 + OAT;
    float TSuper = 273.15 + ( 15 - ( 0.0019812 * PressAltforDensity) );
    float densityalt = PressAltforDensity + (TSuper / 0.0019812) * ( 1- ( powf (TSuper / TKelvin, .2349690) ) ) ;
    parent.self.labelDensityAlt.text = [ [NSString alloc] initWithFormat:@"%.0f ft", densityalt];
    parent.self.labelDisplayPA.text = [ [NSString alloc] initWithFormat:@"%.0f'", parent.self.sliderHp.value];
    parent.self.labelDisplayOAT.text = [ [NSString alloc] initWithFormat:@"%.0fºC", OAT];
    parent.self.labelMainPressureAlt.text = [ [NSString alloc] initWithFormat:@"%.0f", parent.self.sliderHp.value];
    parent.self.labelOATforOGE.text = [ [NSString alloc] initWithFormat:@"%.0f", parent.self.sliderOATforOGE.value];
    parent.self.MSLfeet.text = [ [NSString alloc] initWithFormat:@"%.0f", parent.self.sliderMSL.value];
   
    
    //float calcisa = 15 - (1.98 * (parent.self.sliderHp.value/1000));
    //float OATinISA = calcisa + parent.self.sliderISADiff.value;
    parent.self.labelActualOAT.text = [ [NSString alloc] initWithFormat:@"%.0fºC", parent.self.sliderOATforOGE.value];
    
    
    formatString1 = @"%.0f";
    formatString2 = @"%.0f";
    formatString3 = @"%.0f";
    formatString4 = @"%.0f";
    
    //NSLog(@"[components objectAtIndex:15]  %@", [components objectAtIndex:15] );
    
    
    NSCharacterSet* charSet2 = [NSCharacterSet characterSetWithCharactersInString:@"."];
    
    
    NSArray *components2 = [ [components objectAtIndex:19] componentsSeparatedByCharactersInSet:charSet2];
    if (components2.count > 1) {
        NSString *decimalString = [components2 objectAtIndex:1];
        if ( decimalString.length == 1  ) {  formatString1 = @"%.1f"; }
        if ( decimalString.length == 2  ) {  formatString1 = @"%.2f"; }
    }
    
    components2 = [ [components objectAtIndex:25] componentsSeparatedByCharactersInSet:charSet2];
    if (components2.count > 1) {
        NSString *decimalString = [components2 objectAtIndex:1];
        if ( decimalString.length == 1  ) {  formatString2 = @"%.1f"; }
        if ( decimalString.length == 2  ) {  formatString2 = @"%.2f"; }
    }
    components2 = [ [components objectAtIndex:31] componentsSeparatedByCharactersInSet:charSet2];
    if (components2.count > 1) {
        NSString *decimalString = [components2 objectAtIndex:1];
        if ( decimalString.length == 1  ) {  formatString3 = @"%.1f"; }
        if ( decimalString.length == 2  ) {  formatString3 = @"%.2f"; }
    }
    components2 = [ [components objectAtIndex:37] componentsSeparatedByCharactersInSet:charSet2];
    if (components2.count > 1) {
        NSString *decimalString = [components2 objectAtIndex:1];
        if ( decimalString.length == 1  ) {  formatString4 = @"%.1f"; }
        if ( decimalString.length == 2  ) {  formatString4 = @"%.2f"; }
    }
  
    
    
    parent.self.labelHeadwind2.text = [ [NSString alloc] initWithFormat:formatString1, parent.self.sliderHeadwind2.value];
    parent.self.labelSliderIAS.text = [ [NSString alloc] initWithFormat:formatString2, parent.self.sliderIAS.value];
    parent.self.labelSliderRatingIndex.text = [ [NSString alloc] initWithFormat:formatString3, parent.self.sliderRatingIndex.value];
    parent.self.labelSliderPROPRPM.text = [ [NSString alloc] initWithFormat:formatString4, parent.self.sliderPROPRPM.value];
    
    
    
    
}





- (void) enviOverrideComputationData {
    
    //1addceiling
    if (flagCeilingComputation == 1) {
        return;
    }
    
    //NSLog(@"enviOverrideComputationData ");    
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"^"];
    NSArray *components = [envirnomentAdditionalInfo componentsSeparatedByCharactersInSet:charSet];
       
    if (components.count < 23) {
        //NSLog(@"--- ALAAAARM");
        NSString *standardSetting = @"S^-40^40^15^-60^60^0^-1000^20000^0^29^31^29.92^1013.2^Wind Speed^kts^0^40^5^0.0^Wind Direction [Mag]^º^0^350^10^^OFF^ ^^^^^OFF^^^^^^Runway Length^1500^6000^100^2500^";
        envirnomentAdditionalInfo = standardSetting ;
        components = [envirnomentAdditionalInfo componentsSeparatedByCharactersInSet:charSet];
    }    
    //NSLog(@"userNameForComputation %@ ", userNameForComputation);    
    OAT = [[components objectAtIndex:3] floatValue];
    //NSLog(@"OAT %.0f", OAT);
    ISADiff = [[components objectAtIndex:6] floatValue];
    altimeterInches = [[components objectAtIndex:12] floatValue];
    headWindKTS = [[components objectAtIndex:19] floatValue];
    IAS = [[components objectAtIndex:25] floatValue];
    RATINGINDEX =  [[components objectAtIndex:31] floatValue];
    PROPRPM = [[components objectAtIndex:37] floatValue];
    
    //NSLog(@"selectedChartButton %.0f", selectedChartButton);
    //NSLog(@"actualButtonNumber %d", actualButtonNumber);
    //NSLog(@"OAT %.0f", OAT);
    
    //NSLog(@"displayWindow %.0f", displayWindow);     
    
    nameVariSlider1 =  [components objectAtIndex:14];
    nameVariSlider2 =  [components objectAtIndex:20];
    nameVariSlider3 =  [components objectAtIndex:26];
    nameVariSlider4 =  [components objectAtIndex:32];
       
    float MSL =  [[components objectAtIndex:9] floatValue];
    //NSLog(@"MSL %.0f", MSL);
    float paCalc = ((29.92 - [[components objectAtIndex:12] floatValue]) *1000);
    if (paCalc < 0.001 & paCalc > -0.001) {
        paCalc = 0;
    }
    Hp = MSL + paCalc;
    
    //NSLog(@"chartNameForSliderDefaults %@", chartNameForSliderDefaults);
    
    //sdf
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound   ) {
        //NSLog(@"1");
        if ([chartNameForSliderDefaults rangeOfString:@"landingSliders"].location != NSNotFound ){    
            //NSLog(@"2");
            LDG_OAT =  OAT;
            LDG_ELEV = Hp;
            LDG_ALTIM = [[components objectAtIndex:12] floatValue];
            LDG_ISADIFF =  ISADiff; 
        }
    }else{       
        if ([chartNameForSliderDefaults rangeOfString:@"LDG"].location != NSNotFound ){         
            LDG_OAT =  OAT;
            LDG_ELEV = Hp;
            LDG_ALTIM = [[components objectAtIndex:12] floatValue];
            LDG_ISADIFF =  ISADiff; 
        }
        
    }
    
    //NSLog(@"LDG_OAT %.0f", LDG_OAT);
    
    
  if ([[infoArray objectAtIndex: 3  ] rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound   ) {
      
     
      if ([calcMode isEqualToString:@"plan"]) {          
          //NSLog(@"chartNameForSliderDefaults >%@<", chartNameForSliderDefaults);
          if ([chartNameForSliderDefaults rangeOfString:@"Climb"].location != NSNotFound ){            
              [self overwriteStringFromSliders: @"Climb"];         
          }         
          
          if ([chartNameForSliderDefaults rangeOfString:@"Cruise"].location != NSNotFound ){  
              [self overwriteStringFromSliders: @"Cruise"];         
          }    
          
          ViewController *parent = (ViewController *)self.parentViewController;
          
          if (selectedChartButton == actualButtonNumber && displayWindow > 100) {
              // this is how to see what chart is open:
              //NSLog(@"selected chartNameForSliderDefaults %@", chartNameForSliderDefaults );             
              if ([chartNameForSliderDefaults rangeOfString:@"Climb"].location != NSNotFound ) {                    
                  //NSLog(@"Climb is open");
                  parent.self.labelNotePlanMode.hidden = NO;
                  parent.self.labelNotePlanMode.text = @"Plan Mode: Set Climb Start on Takeoff Page";
                  parent.self.sliderMSL.enabled = NO; 
                  parent.self.sliderOATforOGE.enabled = NO;
                  parent.self.sliderQNH.enabled = NO;
                  parent.self.sliderISADiff.enabled = NO;
                  
                  parent.self.buttonEnterMSLfeet.hidden = YES;
                  parent.self.buttonEnterMSLfeet.hidden = YES;
                  parent.self.buttonISA.hidden = YES;
                  parent.self.buttonOAT.hidden = YES;
                  parent.self.buttonSetISA.hidden = YES;
                  parent.self.buttonEnterQNH.hidden = YES;
              }
          }
          if (selectedChartButton == actualButtonNumber && displayWindow > 100) {
              // this is how to see what chart is open:
              //NSLog(@"selected chartNameForSliderDefaults %@", chartNameForSliderDefaults );             
              if ([chartNameForSliderDefaults rangeOfString:@"Cruise"].location != NSNotFound ) {                    
                  //NSLog(@"Cruise is open");
                  parent.self.labelNotePlanMode.hidden = NO;
                  parent.self.labelNotePlanMode.text = @"Plan Mode: Set Cruise Alt on Climb Page";
                  parent.self.sliderMSL.enabled = NO;
                  parent.self.sliderOATforOGE.enabled = NO;
                  parent.self.sliderQNH.enabled = NO;
                  parent.self.sliderISADiff.enabled = NO;
                  
                  parent.self.buttonEnterMSLfeet.hidden = YES;
                  parent.self.buttonEnterMSLfeet.hidden = YES;
                  parent.self.buttonISA.hidden = YES;
                  parent.self.buttonOAT.hidden = YES;
                  parent.self.buttonSetISA.hidden = YES;
                  parent.self.buttonEnterQNH.hidden = YES;
              }
          }        
      }
      
  }
    
    
  if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound   ) {
        
        if ([calcMode isEqualToString:@"plan"]) {          
            //NSLog(@"chartNameForSliderDefaults >%@<", chartNameForSliderDefaults);
            if ([chartNameForSliderDefaults rangeOfString:@"climbSliders"].location != NSNotFound ){            
                [self overwriteStringFromSliders: @"climbSliders"];         
            } 
            
            if ([chartNameForSliderDefaults rangeOfString:@"cruiseSliders"].location != NSNotFound ){            
                [self overwriteStringFromSliders: @"cruiseSliders"];         
            } 
            
            
            
            ViewController *parent = (ViewController *)self.parentViewController;
            
            //NSLog(@"chartNameForSliderDefaults %@", chartNameForSliderDefaults ); 
           
            
            // selectedChartButton 2 = climb
            // selectedChartButton 3 = landing
            // selectedChartButton 4 = cruise
            
       
            if (selectedChartButton == 2 && displayWindow > 100) {
                // this is how to see what chart is open:
                //NSLog(@"selected chartNameForSliderDefaults %@", chartNameForSliderDefaults );             
                //if ([chartNameForSliderDefaults rangeOfString:@"climbSliders"].location != NSNotFound ) { 
                if ([chartNameForThisInfoFile rangeOfString:@"ClimbComp"].location != NSNotFound) {
                    
                    //NSLog(@"Climb is open");
                    parent.self.labelNotePlanMode.hidden = NO;
                    parent.self.labelNotePlanMode.text = @"Plan Mode: Set Climb Start on Takeoff Page";
                    parent.self.sliderMSL.enabled = NO; 
                    parent.self.sliderOATforOGE.enabled = NO;
                    parent.self.sliderQNH.enabled = NO;
                    parent.self.sliderISADiff.enabled = NO;
                    
                    parent.self.buttonEnterMSLfeet.hidden = YES;
                    parent.self.buttonEnterMSLfeet.hidden = YES;
                    parent.self.buttonISA.hidden = YES;
                    parent.self.buttonOAT.hidden = YES;
                    parent.self.buttonSetISA.hidden = YES;
                    parent.self.buttonEnterQNH.hidden = YES;
                }
            }
           
            
            if (selectedChartButton == 4 && displayWindow > 100) {
                // this is how to see what chart is open:
                //NSLog(@"selected chartNameForThisInfoFile %@", chartNameForThisInfoFile );             
                if ([chartNameForThisInfoFile rangeOfString:@"CruiseComp"].location != NSNotFound ) {                    
                    //NSLog(@"Cruise is open");
                    parent.self.labelNotePlanMode.hidden = NO;
                    parent.self.labelNotePlanMode.text = @"Plan Mode: Set Cruise Alt on Climb Page";
                    parent.self.sliderMSL.enabled = NO;
                    parent.self.sliderOATforOGE.enabled = NO;
                    parent.self.sliderQNH.enabled = NO;
                    parent.self.sliderISADiff.enabled = NO;
                    
                    parent.self.buttonEnterMSLfeet.hidden = YES;
                    parent.self.buttonEnterMSLfeet.hidden = YES;
                    parent.self.buttonISA.hidden = YES;
                    parent.self.buttonOAT.hidden = YES;
                    parent.self.buttonSetISA.hidden = YES;
                    parent.self.buttonEnterQNH.hidden = YES;
                }
            }        
            
            
            
              
        }
        
    } // end if FXX
        
         
    
}

- (void) overwriteStringFromSliders: (NSString*)chartNameToOverwrite {
    
          
    //forwarding
    
    // 1. load takeoff slider
    // 2. get all values that needs to be forwarded
    // 3. overwrite current envirnomentAdditionalInfo for climb
        
    //NSLog(@"1 overwriteStringFromSliders for : %@", chartNameToOverwrite);
    
    NSString *temporaryAdditionalInfo =@"";
    
    int overwriteOAT = 0;
    int overwriteISADiff = 0;
    int overwriteMSL = 0;
    int overwriteAltimeter = 0;
    
    if ([chartNameToOverwrite isEqualToString:@"Climb"]) {
        NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
        NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, @"TO" ];
        //NSLog(@"loading TO enviKey =  %@", enviKey);        
        temporaryAdditionalInfo = [[NSUserDefaults standardUserDefaults]  stringForKey:enviKey];
        overwriteOAT = 1;
        overwriteISADiff = 1;
        overwriteMSL = 1;
        overwriteAltimeter = 1;
    }
    
    if ([chartNameToOverwrite isEqualToString:@"climbSliders"]) {
        NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
        NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, @"takeoffSliders" ];
        //NSLog(@"loading takeoffSliders enviKey =  %@", enviKey);        
        temporaryAdditionalInfo = [[NSUserDefaults standardUserDefaults]  stringForKey:enviKey];
        overwriteOAT = 1;
        overwriteISADiff = 1;
        overwriteMSL = 1;
        overwriteAltimeter = 1;
    }
    
    

  
    if ([chartNameToOverwrite isEqualToString:@"Cruise"]) {
        NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
        NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, @"Climb" ];
        //NSLog(@"loading Climb enviKey =  %@", enviKey); 
        temporaryAdditionalInfo = [[NSUserDefaults standardUserDefaults]  stringForKey:enviKey];
        //NSLog(@"Climb temporaryAdditionalInfo =  %@", temporaryAdditionalInfo);
        overwriteOAT = 1;
        overwriteISADiff = 1;
        overwriteMSL = 1;
        overwriteAltimeter = 1;
    }
    
    if ([chartNameToOverwrite isEqualToString:@"cruiseSliders"]) {
        NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
        NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, @"climbSliders" ];
        //NSLog(@"loading Climb enviKey =  %@", enviKey); 
        temporaryAdditionalInfo = [[NSUserDefaults standardUserDefaults]  stringForKey:enviKey];
        //NSLog(@"Climb temporaryAdditionalInfo =  %@", temporaryAdditionalInfo);
        overwriteOAT = 1;
        overwriteISADiff = 1;
        overwriteMSL = 1;
        overwriteAltimeter = 1;
    }
    
  
    
    if (temporaryAdditionalInfo.length < 1) {
        return;
    }
    
    
     
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"^"];    
    NSArray *components = [envirnomentAdditionalInfo componentsSeparatedByCharactersInSet:charSet];    
    
    
    NSString *enviString = @"";
    enviString = [enviString stringByAppendingString: @"0"];  // 0
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:1] ]; //1
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:2] ];
    enviString = [enviString stringByAppendingString: @"^"];
    
    // OAT    
    NSArray *componentsForOverwrite = [temporaryAdditionalInfo componentsSeparatedByCharactersInSet:charSet];
    NSString *overwriteString;   
    
    if ([chartNameToOverwrite isEqualToString:@"Cruise"] || [chartNameToOverwrite isEqualToString:@"cruiseSliders"]) {
        Climb_EndElevation = [[componentsForOverwrite objectAtIndex:25] floatValue]; 
        Climb_EndAltimeter  = [[componentsForOverwrite objectAtIndex:12] floatValue];  
        
        float paCalc = ((29.92 - Climb_EndAltimeter) *1000);
        if (paCalc < 0.001 & paCalc > -0.001) {
            paCalc = 0;
        } 
        Climb_EndPressureAlt = Climb_EndElevation + paCalc;  // because 1st slider is used 
        Climb_EndISADiff = [[componentsForOverwrite objectAtIndex:6] floatValue];   
        float tempISAatElevation = 15 - ( 1.98 * (Climb_EndPressureAlt / 1000)  );
        Climb_EndOAT = tempISAatElevation + Climb_EndISADiff;                 
        //NSLog(@"Climb_EndAltimeter %.2f", Climb_EndAltimeter); 
        //NSLog(@"Climb_EndPressureAlt %.0f", Climb_EndPressureAlt); 
        //NSLog(@"Climb_EndISADiff %.0f", Climb_EndISADiff);
        //NSLog(@"Climb_EndOAT %.0f", Climb_EndOAT);
        //NSLog(@"Climb_EndElevation %.0f", Climb_EndElevation);
     }
    
    
    
    if (overwriteOAT == 0) {   
       
    }else{
        //NSLog(@"YES overwriting OAT");
        overwriteString = [componentsForOverwrite objectAtIndex:3];                
        if ([chartNameToOverwrite isEqualToString:@"Cruise"] || [chartNameToOverwrite isEqualToString:@"cruiseSliders"]) {            
            overwriteString = [[NSString alloc] initWithFormat:@"%.1f", Climb_EndOAT ]; 
        }
    }
    //NSLog(@"overwriteString OAT from TO = %@ ", overwriteString);    
    enviString = [enviString stringByAppendingString: overwriteString ]; // OAT
    
    
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:4] ]; // 4
    enviString = [enviString stringByAppendingString: @"^"];  
    enviString = [enviString stringByAppendingString: [components objectAtIndex:5] ];
    enviString = [enviString stringByAppendingString: @"^"];
       
    if (overwriteISADiff == 0) {
         
    }else{
         overwriteString = [componentsForOverwrite objectAtIndex:6]; 
        
        if ([chartNameToOverwrite isEqualToString:@"Cruise"] || [chartNameToOverwrite isEqualToString:@"cruiseSliders"]) {
            overwriteString = [[NSString alloc] initWithFormat:@"%.1f", Climb_EndISADiff ];             
        }
        
        
        
        
        
        
    }
    enviString = [enviString stringByAppendingString: overwriteString ]; // 6 isa diff
    
    
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString: [components objectAtIndex:7]] ; //7
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:8] ];
    enviString = [enviString stringByAppendingString: @"^"];    
    
    
    //NSLog(@"chartNameToOverwrite >%@<", chartNameToOverwrite);
          
          
    if (overwriteMSL == 0) {
      
    }else{         
         overwriteString = [componentsForOverwrite objectAtIndex:9];  
        
        if ([chartNameToOverwrite isEqualToString:@"Cruise"] || [chartNameToOverwrite isEqualToString:@"cruiseSliders"]) {
            //NSLog(@"overwrite Cruise ELev mit Climb_EndElevation = %.0f ", Climb_EndElevation);  
            overwriteString = [[NSString alloc] initWithFormat:@"%.1f", Climb_EndElevation ];             
        }
        
        
        
    } 
    enviString = [enviString stringByAppendingString: overwriteString ]; // 9 msl
        
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString: [components objectAtIndex:10] ]; // 10
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString: [components objectAtIndex:11]]; // 11
    enviString = [enviString stringByAppendingString: @"^"]; 
            
    if (overwriteAltimeter == 0) {
                   
    }else{
         overwriteString = [componentsForOverwrite objectAtIndex:12];
        
        if ([chartNameToOverwrite isEqualToString:@"Cruise"] || [chartNameToOverwrite isEqualToString:@"cruiseSliders"]) {
            overwriteString = [[NSString alloc] initWithFormat:@"%.2f", Climb_EndAltimeter ];             
        }
        
        
        
    }    
    enviString = [enviString stringByAppendingString: overwriteString ];  // 12 QNH
        
    
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:13] ];  // 13 QNH ero    
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString: [components objectAtIndex:14]]; // 14
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:15]]; // 15
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:16]]; // 16
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:17]]; // 17
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:18]]; // 18
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:19]]; // 19  headwind (1. vari slider) // zb climbEndElevation
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString: [components objectAtIndex:20]]; // 20
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:21]]; // 21
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:22]]; // 22
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:23]]; //23
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:24]]; // 24
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:25]]; //25   sliderIAS (2. vari slider) 
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString: [components objectAtIndex:26]]; // 26
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:27]]; // 27
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:28]]; // 28
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:29]]; //29
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:30]]; // 30
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:31]]; // 31  ratingIndex (3. vari slider) 
    enviString = [enviString stringByAppendingString: @"^"]; 
    enviString = [enviString stringByAppendingString: [components objectAtIndex:32]]; // 32
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:33]]; // 33
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:34]]; //34
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:35]]; // 35
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:36]]; // 36
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString: [components objectAtIndex:37]]; // 37  PROPRPM (4. vari slider) 
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@"RunwayLengthTO"]; // 38
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; //39
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; // 40
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; // 41
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; // 42
    enviString = [enviString stringByAppendingString: @"^"];
    
    
    //NSLog(@"actualButtonNumber %d   enviString = %@", actualButtonNumber, enviString );
    NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
    NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, chartNameForSliderDefaults ];
    [[NSUserDefaults standardUserDefaults]  setObject: enviString     forKey:enviKey];
    //NSLog(@"saving enviKey =  %@", enviKey);
    //NSLog(@"saving enviString %@", enviString );
    envirnomentAdditionalInfo = enviString;
    
    
}



- (void) enviMakeStringFromSliders {
    
   //NSLog(@"enviMakeStringFromSliders ");
     //NSLog(@"1");
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound   ) { 
         //NSLog(@"2");
        [self saveFixedWingSliders];
    }
     //NSLog(@"3");
    ViewController *parent = (ViewController *)self.parentViewController;
    //NSLog(@"parent.self.titleVariSlider1.text %@", parent.self.titleVariSlider1.text);
       
    if (parent.self.titleVariSlider1.text.length < 1) {
         //NSLog(@"4!!!!!!!!");
        //NSLog(@"overriding %@", parent.self.titleVariSlider1.text);
        //[self enviOverrideAllSliderData];
    }
     //NSLog(@"5");
    
    NSString *enviString = @"";
    enviString = [enviString stringByAppendingString: @"0"];  // 0
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderOATforOGE.minimumValue ]]; //1
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderOATforOGE.maximumValue ]];
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderOATforOGE.value ]];
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderISADiff.minimumValue ]]; // 4
    enviString = [enviString stringByAppendingString: @"^"];  
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderISADiff.maximumValue ]]; // 5
    enviString = [enviString stringByAppendingString: @"^"];   
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderISADiff.value ]]; // 6
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderMSL.minimumValue ]]; //7
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderMSL.maximumValue ]];
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderMSL.value ]];
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderQNH.minimumValue ]]; // 10
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderQNH.maximumValue ]]; // 11
    enviString = [enviString stringByAppendingString: @"^"];    
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.2f", parent.self.sliderQNH.value ]];  // 12
    enviString = [enviString stringByAppendingString: @"^"];
 
  
    
    if (parent.self.labelQNHEuro.text.length < 1) {
        enviString = @"1013.2";
    }else{
        enviString = [enviString stringByAppendingString: parent.self.labelQNHEuro.text];  // 13
    }
    enviString = [enviString stringByAppendingString: @"^"];
    

    
    
    
    enviString = [enviString stringByAppendingString:parent.self.titleVariSlider1.text]; // 14
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:parent.self.unitVariSlider1.text]; // 15
   
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderHeadwind2.minimumValue ]]; // 16
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderHeadwind2.maximumValue ]]; // 17
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", incrementVariSlider1 ]]; // 18
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:formatString1, parent.self.sliderHeadwind2.value ]]; // 19  
    if (parent.self.sliderHeadwind2.enabled == NO) {enviString = [enviString stringByAppendingString:@" L"]; }
    enviString = [enviString stringByAppendingString: @"^"];
  
    enviString = [enviString stringByAppendingString:parent.self.titleVariSlider2.text]; // 20
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:parent.self.unitVariSlider2.text]; // 21
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderIAS.minimumValue ]]; // 22
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderIAS.maximumValue ]]; //23
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", incrementVariSlider2 ]]; // 24
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:formatString2, parent.self.sliderIAS.value ]]; //25
    if (parent.self.sliderIAS.enabled == NO) {enviString = [enviString stringByAppendingString:@" L"]; }
    enviString = [enviString stringByAppendingString: @"^"];

    enviString = [enviString stringByAppendingString:parent.self.titleVariSlider3.text]; // 26
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:parent.self.unitVariSlider3.text]; // 27
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderRatingIndex.minimumValue ]]; // 28
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderRatingIndex.maximumValue ]]; //29
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", incrementVariSlider3 ]]; // 30
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:formatString3, parent.self.sliderRatingIndex.value ]]; // 31
    if (parent.self.sliderRatingIndex.enabled == NO) {enviString = [enviString stringByAppendingString:@" L"]; }
    enviString = [enviString stringByAppendingString: @"^"];
    
    
    enviString = [enviString stringByAppendingString:parent.self.titleVariSlider4.text]; // 32
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:parent.self.unitVariSlider4.text]; // 33
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderPROPRPM.minimumValue ]]; //34
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", parent.self.sliderPROPRPM.maximumValue ]]; // 35
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:@"%.1f", incrementVariSlider4 ]]; // 36
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:[[NSString alloc] initWithFormat:formatString4, parent.self.sliderPROPRPM.value ]]; // 37
    if (parent.self.sliderPROPRPM.enabled == NO) {enviString = [enviString stringByAppendingString:@" L"]; };
    
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@"RunwayLengthTO"]; // 38
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; //39
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; // 40
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; // 41
    enviString = [enviString stringByAppendingString: @"^"];
    enviString = [enviString stringByAppendingString:@""]; // 42
    enviString = [enviString stringByAppendingString: @"^"];
   
    
    //NSLog(@"actualButtonNumber %d   enviString = %@", actualButtonNumber, enviString );
    NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
    NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, chartNameForSliderDefaults ];
    [[NSUserDefaults standardUserDefaults]  setObject: enviString     forKey:enviKey];
   //(@"saving enviKey =  %@", enviKey);
    
    //NSLog(@"OAT %f", parent.self.sliderOATforOGE.value );
    envirnomentAdditionalInfo = enviString;
    
    
     
    
    
    

    
}

- (void) triggerLoadSliderData {
    triggerLoadSliderData = 1;
    
    //NSLog(@"1triggerLoadSliderData ");
           
           
}


- (void) handleFixedWingCharts {
    
    //NSLog(@"1 handleFixedWingCharts ");
    
    ViewController *parent = (ViewController *)self.parentViewController;
    
    //NSLog(@"handleFixedWingCharts  chartNameForThisInfoFile %@", chartNameForThisInfoFile);
    //NSLog(@"actualChartNumber %d  ", actualChartNumber );
    //NSLog(@"actualButtonNumber %d  ", actualButtonNumber );
    //NSLog(@"displayWindow %.0f  ", displayWindow );
   
    
    if (triggerSetDefaultsForPerformanceCharts == 1 ) {
        //NSLog(@" gehe rein triggerSetDefaultsForPerformanceCharts %d  ", triggerSetDefaultsForPerformanceCharts );
        
         //NSLog(@"flagCopyFlight %d  ", flagCopyFlight );
        
       //NSLog(@"triggerSetDefaultsForPerformanceCharts %d  ", triggerSetDefaultsForPerformanceCharts );
        
        if ([chartNameForThisInfoFile rangeOfString:@"TOGroundRoll"].location != NSNotFound || [chartNameForThisInfoFile rangeOfString:@"TO50ft"].location != NSNotFound ) {
        envirnomentAdditionalInfo = takeoffSliderSettings ;
        chartNameForSliderDefaults = @"takeoffSliders";  
            if (flagCopyFlight == 1) { 
                [self enviLoadSliderDataForCopy];
                [self enviOverrideAllSliderData];              
                [self enviOverrideComputationData];            
                [self enviMakeStringFromSliders];             
            }else{
                [self enviOverrideAllSliderData];               
                [self enviOverrideComputationData];              
                [self enviMakeStringFromSliders];
            }
           
            
            if (flagCopyFlight == 0) {     
               //NSLog(@"2");
               [self presetFixedWingSliders]; 
            }
            
        }
        
        if ([chartNameForThisInfoFile rangeOfString:@"ClimbComp"].location != NSNotFound ) {
            envirnomentAdditionalInfo = climbSliderSettings ;
            chartNameForSliderDefaults = @"climbSliders";           
            if (flagCopyFlight == 1) { 
                [self enviLoadSliderDataForCopy];
                [self enviOverrideAllSliderData];              
                [self enviOverrideComputationData];            
                [self enviMakeStringFromSliders];             
            }else{
                [self enviOverrideAllSliderData];               
                [self enviOverrideComputationData];              
                [self enviMakeStringFromSliders];
            }
               
            if (flagCopyFlight == 0) {    
                //NSLog(@"3");
                [self presetFixedWingSliders]; 
            }
        }
        
        
        if ([chartNameForThisInfoFile rangeOfString:@"LDGGroundRoll"].location != NSNotFound || [chartNameForThisInfoFile rangeOfString:@"LDG50ft"].location != NSNotFound ) {
        envirnomentAdditionalInfo = landingSliderSettings ;
        chartNameForSliderDefaults = @"landingSliders";
            if (flagCopyFlight == 1) { 
                [self enviLoadSliderDataForCopy];
                [self enviOverrideAllSliderData];              
                [self enviOverrideComputationData];            
                [self enviMakeStringFromSliders];             
            }else{
                [self enviOverrideAllSliderData];               
                [self enviOverrideComputationData];              
                [self enviMakeStringFromSliders];
            }
              
            if (flagCopyFlight == 0) {  
                //NSLog(@"4");
                [self presetFixedWingSliders]; 
            }
        }
        
        
        if ([chartNameForThisInfoFile rangeOfString:@"CruiseComp"].location != NSNotFound ) {
            envirnomentAdditionalInfo = cruiseSliderSettings ;
            chartNameForSliderDefaults = @"cruiseSliders";        
            if (flagCopyFlight == 1) { 
                [self enviLoadSliderDataForCopy];
                [self enviOverrideAllSliderData];              
                [self enviOverrideComputationData];            
                [self enviMakeStringFromSliders];             
            }else{
                [self enviOverrideAllSliderData];               
                [self enviOverrideComputationData];              
                [self enviMakeStringFromSliders];
            }
              
            if (flagCopyFlight == 0) {    
                //NSLog(@"5");
                [self presetFixedWingSliders]; 
            }
        }
        
    }
    
    NSString *chartNameText = @"";
  
    if (triggerOpenChart == 1 & displayWindow > 100){
        // what chart is open?
        dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   displayWindow   ];
        chartNameText = dL.text ;
        
        //NSLog(@"OPEN chartNameText %@  ", chartNameText );
        
       
        //NSLog(@"displayWindow %.0f  ", displayWindow );
        //NSLog(@"1 chartNameText %@  ", chartNameText );
        //NSLog(@"chartNameForThisInfoFile %@  ", chartNameForThisInfoFile );
         //NSLog(@"triggerLoadSliderData %d  ", triggerLoadSliderData );
        
        
        if ([chartNameText isEqualToString:@"Takeoff"]) {            
            if (triggerLoadSliderData == 1) {
                chartNameForSliderDefaults = @"takeoffSliders";
                [self enviLoadSliderData];
                [self enviOverrideAllSliderData];
                [self loadFixedWingSliders];
            }            
            if ([chartNameForThisInfoFile rangeOfString:@"TOGroundRoll"].location != NSNotFound || [chartNameForThisInfoFile rangeOfString:@"TO50ft"].location != NSNotFound ) {
                //NSLog(@"a takeoff page is open and takeoff is computed, so we need to save the slider settings for takeoff");
                chartNameForSliderDefaults = @"takeoffSliders";
                //NSLog(@"1 enviMakeStringFromSliders" );
                [self enviMakeStringFromSliders];
            }
        }
        
        if ([chartNameText isEqualToString:@"Climb"]) {            
            if (triggerLoadSliderData == 1) {
                chartNameForSliderDefaults = @"climbSliders";
                [self enviLoadSliderData];
                [self enviOverrideAllSliderData];
                [self loadFixedWingSliders];               
            }
            
            if ([chartNameForThisInfoFile rangeOfString:@"ClimbComp"].location != NSNotFound ) {                
                //NSLog(@"2 enviMakeStringFromSliders" );
                chartNameForSliderDefaults = @"climbSliders";
                [self enviMakeStringFromSliders];                
            }
        }
        
        if ([chartNameText isEqualToString:@"Landing"]) {            
            if (triggerLoadSliderData == 1) {
                chartNameForSliderDefaults = @"landingSliders";
                [self enviLoadSliderData];
                [self enviOverrideAllSliderData];
                [self loadFixedWingSliders];                
            }
            if ([chartNameForThisInfoFile rangeOfString:@"LDGGroundRoll"].location != NSNotFound || [chartNameForThisInfoFile rangeOfString:@"LDG50ft"].location != NSNotFound ) {
                //NSLog(@"a LANDING page is open and landing is computed, so we need to save the slider settings for landing");
                chartNameForSliderDefaults = @"landingSliders";
                //NSLog(@"3 enviMakeStringFromSliders" );
                [self enviMakeStringFromSliders];
            }
        }
        
        if ([chartNameText isEqualToString:@"Cruise"]) {            
            if (triggerLoadSliderData == 1) {
                chartNameForSliderDefaults = @"cruiseSliders";
                [self enviLoadSliderData];
                [self enviOverrideAllSliderData];
                [self loadFixedWingSliders];               
            }
            
            if ([chartNameForThisInfoFile rangeOfString:@"CruiseComp"].location != NSNotFound ) {                
                //NSLog(@"2 enviMakeStringFromSliders" );
                chartNameForSliderDefaults = @"cruiseSliders";
                [self enviMakeStringFromSliders];                
            }
        }
        
        
        
        
    }
    
     //NSLog(@"chartNameForThisInfoFile %@", chartNameForThisInfoFile);
    
    if ([chartNameForThisInfoFile rangeOfString:@"LDGGroundRoll"].location != NSNotFound || [chartNameForThisInfoFile rangeOfString:@"LDG50ft"].location != NSNotFound ) {
        //NSLog(@"this is a landing and closed window so we need to load sliders" );        
        chartNameForSliderDefaults = @"landingSliders";
        [self enviLoadSliderData];
        [self enviOverrideComputationData];
    }
    
    
   

    if ([chartNameForThisInfoFile rangeOfString:@"TOGroundRoll"].location != NSNotFound || [chartNameForThisInfoFile rangeOfString:@"TO50ft"].location != NSNotFound ) {
        //NSLog(@"this is a takeoff" );      
        chartNameForSliderDefaults = @"takeoffSliders";
        [self enviLoadSliderData];
        [self enviOverrideComputationData];
        
    }
    
    if ([chartNameForThisInfoFile rangeOfString:@"Climb"].location != NSNotFound ) {
        //NSLog(@"this is a Climb" );
        chartNameForSliderDefaults = @"climbSliders";
        [self enviLoadSliderData];
        [self enviOverrideComputationData];
        
    }
    
    
    if ([chartNameForThisInfoFile rangeOfString:@"Cruise"].location != NSNotFound ) {
        //NSLog(@"this is a Cruise" ); 
        chartNameForSliderDefaults = @"cruiseSliders";
        [self enviLoadSliderData];
        [self enviOverrideComputationData];
        
    }
    
   
    
    
}



- (void) getInfoForCurrentChart {
    
    //NSLog(@"getInfoForCurrentChart ************************");    
    //NSLog(@"actualButtonNumber %d  ", actualButtonNumber );
    //NSLog(@"actualChartNumber %d  ", actualChartNumber );
    //NSLog(@"displayWindow %.0f  ", displayWindow);
    //NSLog(@"triggerSetDefaultsForPerformanceCharts %d  ", triggerSetDefaultsForPerformanceCharts);
    
    
    // get info for next chart *****************************************************************************
    chartNameForThisInfoFile = [chartsArray objectAtIndex:nChart];
    
    //NSLog(@"chartsArray %@", chartsArray);
    //NSLog(@"nChart %d", nChart);
    //NSLog(@"1chartNameForThisInfoFile = %@", chartNameForThisInfoFile  );
    
    //NSLog(@"chartNameForThisInfoFile = %@", chartNameForThisInfoFile  );
    arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@",  chartNameForThisInfoFile, @"infoGeneral" ];
    infoArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
    //NSLog(@"arrayKey = %@", arrayKey );
    //NSLog(@"infoArray = %@", infoArray );
    [resultsAllPrintOnManifest addObject: @"-"];
    
    // get number of computation parts and check if warning or other specials (draw line)
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"+"];
    NSArray *components = [[infoArray objectAtIndex:2] componentsSeparatedByCharactersInSet:charSet];
    
   //NSLog(@"components = %@", components );
    
    numberOfComputationParts = [[components objectAtIndex:0] intValue];
    //NSLog(@"numberOfComputationParts = %d", numberOfComputationParts );
    //NSLog(@"components.count = %d", components.count );
    
    chartAdditionalInfo = @"";
    envirnomentAdditionalInfo = @"";
    
    chartUserName = [infoArray objectAtIndex:1];
    limitationsForHoist = [infoArray objectAtIndex:2];
    
    //NSLog(@"1chartUserName = %@", chartUserName  );    
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound   ) {        
        //NSLog(@"is FXX");  
        
      
        if ([[infoArray objectAtIndex: 1  ] rangeOfString:@"TOGroundRoll"].location != NSNotFound           ) {
            if (components.count >= 2) {
                takeoffSliderSettings = [components objectAtIndex:2] ;
            }
        }
        
        if ([[infoArray objectAtIndex: 1  ] rangeOfString:@"ClimbComp"].location != NSNotFound           ) {
            if (components.count >= 2) {
                climbSliderSettings = [components objectAtIndex:2] ;
            }
        } 
        
        if ([[infoArray objectAtIndex: 1  ] rangeOfString:@"LDGGroundRoll"].location != NSNotFound           ) {
            if (components.count >= 2) {
                landingSliderSettings = [components objectAtIndex:2] ;
            }
        } 
        
        if ([[infoArray objectAtIndex: 1  ] rangeOfString:@"CruiseComp"].location != NSNotFound           ) {
            if (components.count >= 2) {
                cruiseSliderSettings = [components objectAtIndex:2] ;
            }
        } 
        [self handleFixedWingCharts];    
        
    }else{    
        
         //NSLog(@"is NOT FXX");
        if (components.count >= 2) {
            chartAdditionalInfo = [components objectAtIndex:1] ;
        }
        
        
        NSString *sliderGroupName = @"";
        
        if (components.count > 2  ) {
            envirnomentAdditionalInfo = [components objectAtIndex:2] ;
            NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"^"];
            NSArray *components = [envirnomentAdditionalInfo componentsSeparatedByCharactersInSet:charSet];
            sliderGroupName = [components objectAtIndex:0];
        }
        //NSLog(@"triggerCopySliderSettingsWithFlightID = %@", triggerCopySliderSettingsWithFlightID  );
        
        if (![triggerCopySliderSettingsWithFlightID isEqualToString:@""]) {
            //NSLog(@"copy !!!!!!!!!!!"  );
            //NSLog(@"enviLoadSliderData for user name %@", chartUserName);
            // this loads data for the particular chart > chartUserName
            NSString *vFlightID   = triggerCopySliderSettingsWithFlightID;
            //NSLog(@"using vFlightID %@", vFlightID);
            chartNameForSliderDefaults = sliderGroupName;
            
            if (chartNameForSliderDefaults.length < 1) {
                chartNameForSliderDefaults = @"standard";
                //NSLog(@"3 setting standard");
            }
            
            NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, chartNameForSliderDefaults ];
            //NSLog(@"trying loading enviKey =  %@", enviKey);
            envirnomentAdditionalInfo = @"";
            envirnomentAdditionalInfo = [[NSUserDefaults standardUserDefaults]  stringForKey:enviKey];
            //NSLog(@"loading %@", envirnomentAdditionalInfo );
            //NSLog(@"33 ------ STARTUP yes we have data %@", envirnomentAdditionalInfo);
            
            
            [self enviOverrideAllSliderData];
            [self enviOverrideComputationData];
            [self enviMakeStringFromSliders];
            
            if (triggerSetDefaultsForPerformanceCharts != 1) {
                //NSLog(@"setting to zero");
                triggerCopySliderSettingsWithFlightID = @"";
            }            
            
        }else{
            
            if (components.count > 2  ) {
                //NSLog(@"5");
                
                chartNameForSliderDefaults = sliderGroupName;
                
                //NSLog(@"chartNameForSliderDefaults = %@", chartNameForSliderDefaults  );
                //NSLog(@"------- getInfoForCurrentChart actualButtonNumber %d",actualButtonNumber);
                // if chart is opened, load slider and override
                if (triggerOpenChart == 1 & displayWindow > 100) {
                    //NSLog(@"6");
                    if (displayWindow - 100 == actualButtonNumber) {
                        //NSLog(@"7");
                        //NSLog(@"this chart is open > actualButtonNumber %d", actualButtonNumber);
                        // if chart that we are computing right now is also opened
                        // save the settings
                        
                        [self enviLoadSliderData];
                        if (envirnomentAdditionalInfo.length > 4 ) {
                            //NSLog(@"8");
                            // we have data
                            [self enviOverrideAllSliderData];
                            [self enviOverrideComputationData];
                        }
                    }
                }
                
                //NSLog(@"0");
                //NSLog(@"triggerSetDefaultsForPerformanceCharts %d", triggerSetDefaultsForPerformanceCharts);
                
                
                if (triggerSetDefaultsForPerformanceCharts != 1) {
                 
                    
                    if (displayWindow - 100 == actualButtonNumber) {
                        //NSLog(@"10");
                        // when a chart is open, save the slider settings
                        if (triggerOpenChart == 1) {                            
                            [self enviLoadSliderData];                            
                            [self enviOverrideAllSliderData];
                            triggerOpenChart = 0;
                        }
                        [self enviMakeStringFromSliders];
                        [self enviOverrideComputationData];
                    }else{
                        //NSLog(@"12");
                        // when the chart is NOT OPEN, then load the settings and just override the settings for computations
                        [self enviLoadSliderData];
                        
                        [self enviOverrideComputationData];
                    }
                }else{
                    
                  
                    //NSLog(@"------ STARTUP triggerSetDefaultsForPerformanceCharts %d", triggerSetDefaultsForPerformanceCharts);
                    // during startup we need to set envi defaults for all sliders
                    if (components.count >= 2) {
                        envirnomentAdditionalInfo = [components objectAtIndex:2] ;
                        if (envirnomentAdditionalInfo.length > 4 ) {
                            //NSLog(@"3 ------ STARTUP yes we have data %@", envirnomentAdditionalInfo);
                            // we have data
                            [self enviOverrideAllSliderData];
                            [self enviOverrideComputationData];
                            [self enviMakeStringFromSliders];
                        }
                    }
                }
                
                if (displayWindow - 100 == actualButtonNumber) {
                    triggerOpenChart = 0;
                }
                
                
            }else{
                
              
                //NSLog(@"2 setting chartUserName %@", chartUserName);
                
                chartNameForSliderDefaults = @"standard";                
                //NSLog(@"------- getInfoForCurrentChart actualButtonNumber %d",actualButtonNumber);
                // if chart is opened, load slider and override
                if (triggerOpenChart == 1 & displayWindow > 100) {
                    //NSLog(@"15");
                    if (displayWindow - 100 == actualButtonNumber) {
                        //NSLog(@"16");
                        //NSLog(@"this chart is open > actualButtonNumber %d", actualButtonNumber);
                        // if chart that we are computing right now is also opened
                        // save the settings
                        
                        [self enviLoadSliderData];
                        if (envirnomentAdditionalInfo.length > 4 ) {
                            //NSLog(@"17");
                            // we have data
                            [self enviOverrideAllSliderData];
                            [self enviOverrideComputationData];
                        }
                    }
                }
                
                //NSLog(@"00");
                //NSLog(@"triggerSetDefaultsForPerformanceCharts %d", triggerSetDefaultsForPerformanceCharts);
                if (triggerSetDefaultsForPerformanceCharts != 1) {
                    //NSLog(@"18");
                    //NSLog(@"8");
                    if (displayWindow - 100 == actualButtonNumber) {
                        //NSLog(@"19");
                        //NSLog(@"11");
                        // when a chart is open, save the slider settings
                        if (triggerOpenChart == 1) {
                            //NSLog(@"20");
                            [self enviLoadSliderData];
                            [self enviOverrideAllSliderData];
                            triggerOpenChart = 0;
                        }
                        [self enviMakeStringFromSliders];
                        [self enviOverrideComputationData];
                    }else{
                        //NSLog(@"21");
                        // when the chart is NOT OPEN, then load the settings and just override the settings for computations
                        [self enviLoadSliderData];
                        [self enviOverrideComputationData];
                    }
                }else{
                    
                    //NSLog(@"22");
                    //NSLog(@"------ STARTUP triggerSetDefaultsForPerformanceCharts %d", triggerSetDefaultsForPerformanceCharts);
                    // during startup we need to set envi defaults for all sliders
                    NSString *standardSetting = @"S^-40^40^15^-60^60^0^-1000^20000^0^29^31^29.92^1013.2^Wind Speed^kts^0^40^5^0.0^Wind Direction [Mag]^º^0^350^10^^OFF^ ^^^^^OFF^^^^^^Runway Length^1500^6000^100^2500^";
                    
                    ViewController *parent = (ViewController *)self.parentViewController;
                    if (![[parent.self.arrayName25 objectAtIndex:37]isEqualToString:@""]) {
                        //use special Envi Standards Settings
                        standardSetting = [parent.self.arrayName25 objectAtIndex:37];
                        standardSetting  = [ standardSetting stringByReplacingOccurrencesOfString:@"_" withString:@"^"];
                        //NSLog(@"using special Envi Standards");
                    }
                        
                        
                    envirnomentAdditionalInfo = standardSetting ;
                    chartNameForSliderDefaults = @"standard";
                    //NSLog(@"33 ------ STARTUP yes we have data %@", envirnomentAdditionalInfo);
                    [self enviOverrideAllSliderData];
                    [self enviOverrideComputationData];
                    [self enviMakeStringFromSliders];
                }
                
                if (displayWindow - 100 == actualButtonNumber) {
                    //NSLog(@"23");
                    triggerOpenChart = 0;
                }
            }            
            //NSLog(@"24");
          }
        //NSLog(@"25");        
    }
    
    
    
}




- (void) loopAllPartsAndSaveResults {
    
    //NSLog(@"loopAllPartsAndSaveResults **********************");
    
    int flagMerker = 0;
    AS365N3minWeight1 = 0;
    AS365N3minWeight2 = 0;
    
    
    computationErrorDisplay = @"";
    
    for (partNumberToCompute =1; partNumberToCompute<numberOfComputationParts+1; partNumberToCompute++) {
        //NSLog(@"compute %@_part%d", chartNameForThisInfoFile, partNumberToCompute);        
        infoPartNumber = partNumberToCompute;
        [self getInfoFileForThisPart];     
        [self getInputForCurveAndAxis];     
        [self checkInputDataRange];
        //NSLog(@"1");
        
        //NSLog(@"flagInputDataOutOfRange %d", flagInputDataOutOfRange);
        
        if ( flagInputDataOutOfRange != 0) {
            flagMerker = flagInputDataOutOfRange;
        }  
        
        [self calcComputation];
        
    
        if (flagAWHVdiagram == 1) {           
            resultComputation = 0;
        }
        
        if (flagYandXinputSpecialChart == 1) {          
            resultComputation = cross2ValueX;
            //NSLog(@"cross2ValueX %.1f", cross2ValueX);
        }
        if (flagYandXinputSpecialChart == 2) {          
            resultComputation = cross3ValueX;
            //NSLog(@"cross2ValueX %.1f", cross2ValueX);
        }
        
        if (flagYandXinputSpecialChart == 3) {     
            ViewController *parent = (ViewController *)self.parentViewController;
            resultComputation = [parent.self.labelCGTakeoff.text floatValue];        
            //resultComputation = 4450;
            //NSLog(@"cross2ValueX %.1f", cross2ValueX);
        }
        
       
 
        foundCATEnvelopeName = @"";
        if (flagFindEnvelopeFromYandX == 1) {
            foundCATEnvelopeName = @"N/A";
            NSArray* componentItems  = [[infoPartArray objectAtIndex:5] componentsSeparatedByString:@"+"]; 
            for (int i = 0; i < componentItems.count ; i++) {
                NSArray* envelopeItems  = [[componentItems objectAtIndex:i] componentsSeparatedByString:@"_"]; 
                //NSLog(@"envelopeName %@",[envelopeItems objectAtIndex:0]);
                //NSLog(@"envelopeValue %@",[envelopeItems objectAtIndex:1]);                
                givenCurveInputValue = [[envelopeItems objectAtIndex:1] floatValue];
                [self calcComputation];
                // this is how high the envelope is for that OAT
                //NSLog(@"resultComputation %f", resultComputation);
                //if the entered PA is lower, then we are in that envelope
                if (Hp <= resultComputation) {
                    //NSLog(@"found Envelope !  = %@",[envelopeItems objectAtIndex:0]);
                    foundCATEnvelopeName = [envelopeItems objectAtIndex:0];
                    break;
                }
                if (i == componentItems.count -1) {
                    foundCATEnvelopeName = @"> Hd Limit";
                    //NSLog(@"> Hd Limit");                    
                }
            }  
            resultComputation = Hp;            
        }
   

        [self limitResultValues];
        
        if (flagYandXinputSpecialChart == 1) {
            
            //NSLog(@"cross2ValueX %.0f",  cross2ValueX);
            resultComputation = 0;
            float slope = 0;
            for (int i = 0; i < 26; i++) {
                
                slope = i;               
                
                givenCurveInputValue = slope;
                [self calcComputation];
                //NSLog(@"slope1 %.0f = %.0f", givenCurveInputValue, resultComputation);
                float slope1 = resultComputation;
                
                givenCurveInputValue = slope + 1;
                [self calcComputation];
                //NSLog(@"slope2 %.0f = %.0f", givenCurveInputValue, resultComputation);
                float slope2 = resultComputation;
                
                resultComputation = 0;
                if (cross2ValueX >= slope1 & cross2ValueX < slope2) {
                    //NSLog(@"slope1 %.0f ", slope1);
                    //NSLog(@"slope2 %.0f ", slope2);
                    //NSLog(@"found givenCurveInputValue = %f", slope);
                    resultComputation = slope;
                   
                    break;
                }                
            }
            
        }
        
       
        if (flagYandXinputSpecialChart == 2) {
           
           
            //NSLog(@"cross2ValueX %f", cross2ValueX);
            //NSLog(@"cross3ValueX %f", cross3ValueX);
          
            resultComputation = 0;
            float slope = 0;
            float incrementSlope = 5;
            for (int i = 1800; i < 2600; i++) {
                
                //NSLog(@"i %d", i);                      
                slope = i; 
                givenCurveInputValue = slope; 
                givenAxisInputValue = cross4ValueY;
                
                [self calcComputation];               
                float slope1 = resultComputation;
                
                givenCurveInputValue = slope + incrementSlope;
                [self calcComputation];                
                float slope2 = resultComputation;
                
                resultComputation = 0;
                if (cross3ValueX >= slope1 - 0.2 & cross3ValueX < slope2 + 0.2) {                   
                    resultComputation = slope;
                    //NSLog(@"found slope %.0f ", slope);
                    cross5ValueX = cross3ValueX;
                    cross5ValueY = cross4ValueY;
                    break;
                }  
                
                  i=i+incrementSlope;
            }
          
        }
        
        
        if (flagYandXinputSpecialChart == 3) {
            
            //NSLog(@"cross2ValueX %.0f",  cross2ValueX);
            resultComputation = 0;
            float slope = 0;
            for (int i = 0; i < 273; i++) {
                
                slope = i; 
                givenCurveInputValue = slope;
                [self calcComputation];
                //NSLog(@"slope1 %.0f = %.1f", givenCurveInputValue, resultComputation);
                float slope1 = resultComputation;
                
                givenCurveInputValue = slope + 1;
                [self calcComputation];
                //NSLog(@"slope2 %.0f = %.1f", givenCurveInputValue, resultComputation);
                float slope2 = resultComputation;
             
                resultComputation = 0;
                if (cross1ValueX >= slope1 & cross1ValueX < slope2) {                    
                    resultComputation = slope;
                    break;
                }                 
                
                if (i >=272) {
                    resultComputation = 0;
                }
                
       
                if ([chartNameForComputation rangeOfString:@"HoistBasicCG"].location != NSNotFound  ) { 
                    maxHoistH145standard = resultComputation;
                }
                if ([chartNameForComputation rangeOfString:@"HoistSpecialCG"].location != NSNotFound  ) { 
                    maxHoistH145special = resultComputation;
                }
            }
            
        }
        
        
       
        
        
      
        //NSLog(@"2");
 
        NSString *test = [[NSString alloc] initWithFormat:@"%@_part%d", chartNameForThisInfoFile, partNumberToCompute ];
        
        if ([test isEqualToString:@"Heli_Airbus_AS365N3_NONE_SUP1_Fig38B_HeliportOps_TO_Dist_part2"]) {           
            AS365N3minWeight1 = resultComputation;
            //NSLog(@"AS365N3minWeight1 %f ", AS365N3minWeight1);
        }
      
        if ([test isEqualToString:@"Heli_Airbus_AS365N3_NONE_SUP1_Fig38B_HeliportOps_TO_Dist_part3"]) {               
            AS365N3minWeight2 = resultComputation;
            //NSLog(@"AS365N3minWeight2 %f ", AS365N3minWeight2);
        }
        
       
        if ([[infoPartArray objectAtIndex:13] isEqualToString:@"resultIsTorquePercent"] ) {
            if (partNumberToCompute == 3) {
                resultTorquePercent = cross3ValueX;
            
            }
            
        }
        
        
       
     
        //NSLog(@"compute %@_part%d  result %f ", chartNameForThisInfoFile, partNumberToCompute, resultComputation);
        
        //NSLog(@"3");
        
        if (flagThisPartResultContainsTransferValue == 1) {         
            NSString *transferValueText =  [ [NSString alloc] initWithFormat:@"%.5f", resultComputation ];
            NSString *saveTextForDictionary =  [ [NSString alloc] initWithFormat:@"%@_part%d", chartNameForThisInfoFile, partNumberToCompute ];
            [transferValueDictionary setObject:transferValueText  forKey:saveTextForDictionary];
            //float transferValTest  = [[transferValueDictionary objectForKey:saveTextForDictionary] floatValue];
            //NSLog(@"saveTextForDictionary %@ ", saveTextForDictionary);
            //NSLog(@"saving transferVal for chart: %@ part %d in dictionary %.3f ", chartNameForThisInfoFile, partNumberToCompute, transferValTest);
        }

    }

     //NSLog(@"4");
    if (flagCeilingComputation == 0) { 
     
        // save chart results
        [resultsAllChartNames addObject: chartNameForThisInfoFile];
     
        [resultsAllChartUserNames addObject: chartUserName];
      
        [resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagMerker]]; 
     
        //[resultsAllDataOutOfRange addObject: [NSString stringWithFormat:@"%d",flagInputDataOutOfRange]];
        
        [resultsAllChartValues addObject: [ [NSString alloc] initWithFormat:@"%.5f", resultComputation ]]; 
      
        //NSLog(@"adding resultComputation =  %.0f", resultComputation);
        
        //NSLog(@"unitResult %@", unitResult);
     
        [resultsAllUnits addObject:unitResult];
        
    }

    
   //NSLog(@"resultsAllDataOutOfRange %@", resultsAllDataOutOfRange);
    

    
}

- (void) computeAS365N3PC2 {
    
    //NSLog(@"computeAS365N3PC2 ");
    UIImage *buttonOrange = [UIImage imageNamed:@"button_orange.png"];
    UIImage *buttonRed = [UIImage imageNamed:@"button_red.png"];
    UIImage *buttonGrey = [UIImage imageNamed:@"button grey top184x52.png"];
    UIImage *buttonBlue = [UIImage imageNamed:@"button blue top184x52.png"];
    
    flagPC2Warning = 0;
    NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"];
    NSString *enviKey = [ [NSString alloc] initWithFormat:@"enviInfo_%@_%@", vFlightID, chartNameForSliderDefaults ];
    //NSLog(@"loading enviKey =  %@", enviKey);    
    if ([enviKey isEqualToString:@"enviInfo_1_A"]) {
        // warning only if sliderset is A
        
        if (ISADiff < -10 || ISADiff > 30) {
            PC2warningString = @"ISA Range TO!"; flagPC2Warning = 1;
            flagPC2dataOutOfRange = 1;
        } 
        
        if (Hp < -1000 || Hp > 1000) {
            PC2warningString = @"Hp Range TO!"; flagPC2Warning = 1;
            flagPC2dataOutOfRange = 1;
        } 
        
        //NSLog(@"flagPC2dataOutOfRange %@", resultText);
        
        if (ISADiff == 0) {
            _PC2labelISARange.text = @"ISA temp";
        }else if (ISADiff > 0) {            
            _PC2labelISARange.text = [[NSString alloc] initWithFormat:@"ISA +%.1fº", ISADiff  ]; 
        }else if (ISADiff < 0) {            
            _PC2labelISARange.text = [[NSString alloc] initWithFormat:@"ISA %.1fº", ISADiff  ]; 
        }
        
        //NSLog(@"resultText %@", resultText);
        
        
        
        NSString *outOfRangeText = @"> Range";
        if (flagPC2dataOutOfRange == 1) {
            
            _PC2labelCATAMTOW.text = outOfRangeText;
            _PC2labelExposureTime1.text = outOfRangeText;
            _PC2labelExposureTimeWind.text = outOfRangeText;
            _PC2labelExposureTimePA.text = outOfRangeText;
            _PC2labelExposureTimeISA.text = outOfRangeText;
            _PC2labelTTET.text = outOfRangeText;
            
        }else{
            
            float PC2MTOW = [resultText floatValue] + 13;
            if (PC2MTOW > 4300) {
                PC2MTOW = 4300;
            }
            
            if ([chartNameForComputation rangeOfString:@"PC2DLE_MaxTakeoffPerf"].location != NSNotFound  ) {  
                _PC2labelCATAMTOW.text = [[NSString alloc] initWithFormat:@"%.0f kg", PC2MTOW];              
            }
            
           
            if ([chartNameForComputation rangeOfString:@"PC2DLE_ExposureTimeSeconds"].location != NSNotFound  ) {  
                _PC2labelExposureTime1.text = resultText;  
                exposureTime = [resultText floatValue];
                //NSLog(@"1exposureTime %f", exposureTime);
                
                _PC2labelActualTOW.text = [[NSString alloc] initWithFormat:@"%.0f kg", acWeight]; 
                
                float correctionEffectWind = -1 * ((4.5/30) * headWindKTS);
                
                
                if (correctionEffectWind >= 0) {
                    _PC2labelExposureTimeWind.text = [[NSString alloc] initWithFormat:@"+%.2f sec", correctionEffectWind ];
                }else{
                    _PC2labelExposureTimeWind.text = [[NSString alloc] initWithFormat:@"%.2f sec", correctionEffectWind ];
                }
                
                
                float correctionEffectPressureAlt = Hp/1000;
                if (correctionEffectPressureAlt >= 0) {
                    _PC2labelExposureTimePA.text = [[NSString alloc] initWithFormat:@"+%.2f sec", correctionEffectPressureAlt ];
                }else{
                    _PC2labelExposureTimePA.text = [[NSString alloc] initWithFormat:@"%.2f sec", correctionEffectPressureAlt ]; 
                }
                
                
                float correctionEffectISA = ISADiff / 10;
                if (correctionEffectISA >= 0) {
                    _PC2labelExposureTimeISA.text = [[NSString alloc] initWithFormat:@"+%.2f sec", correctionEffectISA ]; 
                }else{
                    _PC2labelExposureTimeISA.text = [[NSString alloc] initWithFormat:@"%.2f sec", correctionEffectISA ]; 
                }
                
                float TTET = exposureTime + correctionEffectWind + correctionEffectPressureAlt + correctionEffectISA;
                _PC2labelTTET.text = [[NSString alloc] initWithFormat:@"%.2f sec", TTET ]; 
                
              
            }
            
            
            
        }
        
        
        
        
    }
    
    if ([enviKey isEqualToString:@"enviInfo_1_B"]) {
        // warning only if sliderset is B
        
        if (ISADiff < -10 || ISADiff > 30) {
            PC2warningString = @"ISA Range LND!"; flagPC2Warning = 1;
            flagPC2dataOutOfRange = 1;
        } 
        
        if (Hp < -1000 || Hp > 1000) {
            PC2warningString = @"Hp Range LND!"; flagPC2Warning = 1;
            flagPC2dataOutOfRange = 1;
        } 
        
        //NSLog(@"flagPC2dataOutOfRange %@", resultText);
        
        if (ISADiff == 0) {
            _PC2labelISARangeLD.text = @"ISA temp";
        }else if (ISADiff > 0) {            
            _PC2labelISARangeLD.text = [[NSString alloc] initWithFormat:@"ISA +%.1fº", ISADiff  ]; 
        }else if (ISADiff < 0) {            
            _PC2labelISARangeLD.text = [[NSString alloc] initWithFormat:@"ISA %.1fº", ISADiff  ]; 
        }
        
        //NSLog(@"resultText %@", resultText);
        
        
        
        NSString *outOfRangeText = @"> Range";
        if (flagPC2dataOutOfRange == 1) {
            
            _PC2labelCATAMTOWLD.text = outOfRangeText;
            _PC2labelExposureTime1LD.text = outOfRangeText;
            _PC2labelExposureTimeWindLD.text = outOfRangeText;
            _PC2labelExposureTimePALD.text = outOfRangeText;
            _PC2labelExposureTimeISALD.text = outOfRangeText;
            _PC2labelTTETLD.text = outOfRangeText;
            
        }else{
            
            float PC2MTOW = [resultText floatValue] ;
            if (PC2MTOW > 4300) {
                PC2MTOW = 4300;
            }
            
            if ([chartNameForComputation rangeOfString:@"PC2DLE_LANDING_MaxTakeoffPerf"].location != NSNotFound  ) {  
                _PC2labelCATAMTOWLD.text = [[NSString alloc] initWithFormat:@"%.0f kg", PC2MTOW];              
            }
            
            if ([chartNameForComputation rangeOfString:@"PC2DLE_LANDING_ExposureTimeSeconds"].location != NSNotFound  ) {  
                _PC2labelExposureTime1LD.text = resultText; 
                exposureTimeLD = [resultText floatValue];
                
                float VLSS = 10+ (exposureTimeLD * (17.5/9))  ;
                 _PC2labelVLSS.text = [[NSString alloc] initWithFormat:@"%.1f kt", VLSS ];
                
                
                
                _PC2labelActualTOWLD.text = [[NSString alloc] initWithFormat:@"%.0f kg", ACweightLD]; 
                
                float correctionEffectWind = -1 * ((13.5/30) * headWindKTS);
                
                if (correctionEffectWind >= 0) {
                    _PC2labelExposureTimeWindLD.text = [[NSString alloc] initWithFormat:@"+%.2f sec", correctionEffectWind ];
                }else{
                    _PC2labelExposureTimeWindLD.text = [[NSString alloc] initWithFormat:@"%.2f sec", correctionEffectWind ];
                }            
                
                float correctionEffectPressureAlt = 0;
                
                if (Hp >0) {
                    correctionEffectPressureAlt = (Hp/1000) * 2.0;
                }else{
                    correctionEffectPressureAlt = (Hp/1000) * 0.5;                    
                }
                
                if ([chartNameForComputation rangeOfString:@"PC2DLE_LANDING_ExposureTimeSecondsISAplus20"].location != NSNotFound  ) {  
                    
                    if (Hp >0) {
                        correctionEffectPressureAlt = (Hp/1000) * 2.0;
                    }else{
                        correctionEffectPressureAlt = (Hp/1000) * 1.0;                    
                    }
                    
                    
                }
                
                
                if (correctionEffectPressureAlt >= 0) {
                    _PC2labelExposureTimePALD.text = [[NSString alloc] initWithFormat:@"+%.2f sec", correctionEffectPressureAlt ];
                }else{
                    _PC2labelExposureTimePALD.text = [[NSString alloc] initWithFormat:@"%.2f sec", correctionEffectPressureAlt ]; 
                }            
                
                float correctionEffectISA = ISADiff / 10;
                
                if (ISADiff>0) {
                    correctionEffectISA = (ISADiff / 10) * 2.5;
                }else{
                    correctionEffectISA = (ISADiff / 10) * 0.5;
                }
                
                if ([chartNameForComputation rangeOfString:@"PC2DLE_LANDING_ExposureTimeSecondsISAplus20"].location != NSNotFound  ) {  
                    
                    if (ISADiff>0) {
                        correctionEffectISA = (ISADiff / 10) * 2.5;
                    }else{
                        correctionEffectISA = (ISADiff / 10) * 1.5;
                    }
                    
                }
                
                
                if (correctionEffectISA >= 0) {
                    _PC2labelExposureTimeISALD.text = [[NSString alloc] initWithFormat:@"+%.2f sec", correctionEffectISA ]; 
                }else{
                    _PC2labelExposureTimeISALD.text = [[NSString alloc] initWithFormat:@"%.2f sec", correctionEffectISA ]; 
                }
                
                float TTET = exposureTimeLD + correctionEffectWind + correctionEffectPressureAlt + correctionEffectISA;
                _PC2labelTTETLD.text = [[NSString alloc] initWithFormat:@"%.2f sec", TTET ]; 
                
                //NSLog(@"2eexposureTimeLD %f", exposureTimeLD);
                //NSLog(@"correctionEffectWind %f", correctionEffectWind);
                //NSLog(@"correctionEffectPressureAlt %f", correctionEffectPressureAlt);
                //NSLog(@"correctionEffectISA %f", correctionEffectISA);                
                //NSLog(@"TTET %f", TTET);
                
            }
            
            
            
            
        }
        
        
        
        
    }
    
    
    if (flagPC2dataOutOfRange == 1) {
        
        ViewController *parent = (ViewController *)self.parentViewController;
        dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   1 + 200  ];
        dL.text = PC2warningString;
        
        UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: 1 ];            
        [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateNormal];
        [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateSelected];
                
    }else{
        
        ViewController *parent = (ViewController *)self.parentViewController;
        dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   1 + 200  ];
        dL.text = @"OK";
        
        UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
        [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateNormal];
        if ( [buttonToWarn isSelected ]) {
            [buttonToWarn setBackgroundImage:buttonBlue forState:UIControlStateSelected];
        }else{
            [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateSelected];
        }
        
    }
    
    
}



- (void) writeButtonLabels {
    
    //NSLog(@"writeButtonLabels");
    //NSLog(@"for userNameForComputation %@", userNameForComputation);    
    //NSLog(@"AS365N3minWeight1 %f ", AS365N3minWeight1);
    //NSLog(@"AS365N3minWeight2 %f ", AS365N3minWeight2);
    
    
    
    
    //NSLog(@"resultsAllDataOutOfRange %@", resultsAllDataOutOfRange);
    
    // here we write the button names and show warnings and decide if we need to draw lines on the charts
    
    UIImage *buttonOrange = [UIImage imageNamed:@"button_orange.png"];
    UIImage *buttonRed = [UIImage imageNamed:@"button_red.png"];
    UIImage *buttonGrey = [UIImage imageNamed:@"button grey top184x52.png"];
    UIImage *buttonBlue = [UIImage imageNamed:@"button blue top184x52.png"];
    
    if (![specialChart isEqualToString:@""]) {
        //NSLog(@"NOT writeButtonLabels ");
        return;
    }
    //NSLog(@"chartNumberForResult %d ", chartNumberForResult);
    
    //NSLog(@"resultsAllChartValues %@ ", resultsAllChartValues);
   
    //NSLog(@"chartNameForComputation %@ ", chartNameForComputation);
    
    
    resultFromComputations = [[resultsAllChartValues objectAtIndex:chartNumberForResult] floatValue];
   
    chartNameForComputation = [resultsAllChartNames objectAtIndex:chartNumberForResult] ;
    
    userNameForComputation = [resultsAllChartUserNames objectAtIndex:chartNumberForResult];
    userNameForComputation = [userNameForComputation stringByReplacingOccurrencesOfString:@"_" withString:@" "];  
    unitNameForComputation = [resultsAllUnits objectAtIndex:chartNumberForResult] ;
    
  
    
    [resultsAllPrintOnManifest replaceObjectAtIndex:chartNumberForResult withObject: [infoArray objectAtIndex:2] ];    
    //NSLog(@"resultsAllPrintOnManifest %@ ", resultsAllPrintOnManifest);
   
    ViewController *parent = (ViewController *)self.parentViewController;
    resultFromComputations = resultFromComputations * factorForResult;
    
    if ([unitNameForComputation isEqualToString:@"kg"] & [ACweightUnitsUsed isEqualToString:@"lbs"]) {
        unitNameForComputation = @"lbs";
        resultFromComputations = resultFromComputations * 2.2046;
        //NSLog(@"convert resultFromComputations  %f to lbs:", resultFromComputations );
    }
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location == NSNotFound  ) {
        //!!! dont do this!! warum auch immer
        dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   actualButtonNumber + 100  ];
        dL.text = userNameForComputation;       
    }
  
    
    
     float marginWeight = -9999;
       
       if ([userNameForComputation rangeOfString:@"MLDW"].location != NSNotFound
           ||[userNameForComputation rangeOfString:@"MLDM"].location != NSNotFound) {
          marginWeight = resultFromComputations - [parent.self.labelWeightLanding.text floatValue] ;
       }
       
       if (  [userNameForComputation rangeOfString:@"MTOW"].location != NSNotFound 
           ||[userNameForComputation rangeOfString:@"MTOM"].location != NSNotFound
           ||[userNameForComputation rangeOfString:@"IGE"].location != NSNotFound
           ||[userNameForComputation rangeOfString:@"OGE"].location != NSNotFound
           ||[userNameForComputation rangeOfString:@"WAT"].location != NSNotFound
           ||[userNameForComputation rangeOfString:@"HEC Hoist"].location != NSNotFound) {       
           
           if (AS365N3minWeight1 !=0     ){       
               //NSLog(@"dL.text %@", dL.text);
               marginWeight = AS365N3minWeight1 - [parent.self.labelWeightTakeoff.text floatValue] ;
               //NSLog(@"marginWeight %.0f", marginWeight);
           }else{            
               marginWeight = resultFromComputations - [parent.self.labelWeightTakeoff.text floatValue] ;
           }
           
       }    
    
      if ([userNameForComputation rangeOfString:@"Ceiling"].location != NSNotFound) {
          marginWeight = -9999;
          
      }
    
       
       if (marginWeight != -9999) {
           dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   actualButtonNumber + 2000  ];         
           dL.text = [ [NSString alloc] initWithFormat:@"%.0f%@", marginWeight, unitNameForComputation ];
       }
    
    [resultsAllMargins addObject:[ [NSString alloc] initWithFormat:@"%.0f", marginWeight ]];
    [[NSUserDefaults standardUserDefaults]  setObject: resultsAllMargins       forKey:@"resultsAllMargins"];
    
 
    
    //NSLog(@"userNameForComputation %@ ", userNameForComputation);
    
    //NSLog(@"infoArray %@ ", infoArray);
    
    //NSLog(@"1");
          
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  ) {
         
        if ([userNameForComputation rangeOfString:@"TOGroundRoll"].location != NSNotFound  ||      [userNameForComputation rangeOfString:@"TO50ft"].location != NSNotFound   ){     
            dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   1 + 100  ];
            dL.text = @"Takeoff";
        }
        if ([userNameForComputation rangeOfString:@"ClimbComp"].location != NSNotFound   ){           
            dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   2 + 100  ];
            dL.text = @"Climb";            
        } 
        
        if ([userNameForComputation rangeOfString:@"LDGGroundRoll"].location != NSNotFound  ||      [userNameForComputation rangeOfString:@"LDG50ft"].location != NSNotFound   ){ 
          
            if (![resultsAllChartUserNames containsObject: @"ClimbComp"]) {
                dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   2 + 100  ];
            }else{
               dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   3 + 100  ]; 
            }
            dL.text = @"Landing";            
        }  
        
        if ([userNameForComputation rangeOfString:@"CruiseComp"].location != NSNotFound   ){     
         
            dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   4 + 100  ];
            dL.text = @"Cruise";            
        } 
    }
    
 
 
   if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound  ) {
       
       if ([userNameForComputation rangeOfString:@"TOGroundRoll"].location != NSNotFound  ||      [userNameForComputation rangeOfString:@"TO50ft"].location != NSNotFound   ){
           dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:   (chartNumberForResult +1) + 100  ];
           dL.text = @"Takeoff";
       }
       
       if ([userNameForComputation rangeOfString:@"LDGGroundRoll"].location != NSNotFound  ||      [userNameForComputation rangeOfString:@"LDG50ft"].location != NSNotFound   ){
           dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:  (chartNumberForResult +1) + 100  ];
           dL.text = @"Landing";        
       }
       
       if ([userNameForComputation rangeOfString:@"ClimbComp"].location != NSNotFound    ){
           dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:  (chartNumberForResult +1) + 100  ];
           dL.text = @"Climb";        
       }
       if ([userNameForComputation rangeOfString:@"CruiseComp"].location != NSNotFound    ){
           dL = [[UILabel alloc] init];  dL = (UILabel *)[ parent.self.viewUniversalButtons viewWithTag:  (chartNumberForResult +1) + 100  ];
           dL.text = @"Cruise/Trip";        
       }
    
   }
    
    
    
     NSString *perfLabelAddition = @"";

     if (chartAdditionalInfo.length > 1 ) {    
         
          if ( [chartAdditionalInfo rangeOfString:@"Gradient-1000"].location != NSNotFound ){
              //this is Agusta, we need to decrease 1kt per 1000ft above 10000ft (see screenshot)
              float HPdecrease = 0;
              if (Hp >= 11000) {
                  HPdecrease = (Hp - 10000) / 1000;
              }
              float KIAS = [chartAdditionalInfo floatValue] - HPdecrease;
              //NSLog(@"resultFromComputations %f", resultFromComputations );
              //NSLog(@"KIAS %f", KIAS );              
              float gradientPercent = resultFromComputations / KIAS;              
               //NSLog(@"gradientPercent %f", gradientPercent );              
              perfLabelAddition = [ [NSString alloc] initWithFormat:@" = %.1f%%", gradientPercent  ];;
              
          }else if ( [chartAdditionalInfo rangeOfString:@"Gradient"].location != NSNotFound ){
                      //this is Agusta, we need to decrease 1kt per 1000ft above 10000ft (see screenshot)                     
                      float KIAS = [chartAdditionalInfo floatValue] ;
                      //NSLog(@"22resultFromComputations %f", resultFromComputations );
                      //NSLog(@"22KIAS %f", KIAS );                      
                      float gradientPercent = resultFromComputations / KIAS;                      
                      //NSLog(@"22gradientPercent %f", gradientPercent );                      
                      perfLabelAddition = [ [NSString alloc] initWithFormat:@" = %.1f%%", gradientPercent  ];;
                      
                  }
     }
   
   
    //check if you need to show the difference to TOW
    if (chartAdditionalInfo.length > 1 ) {    
        if ( [chartAdditionalInfo rangeOfString:@"showWeightMarginsIfNegative"].location != NSNotFound ){
            
            float marginWeight = resultFromComputations - [parent.self.labelWeightTakeoff.text floatValue] ;
            if (marginWeight <= 0) {
                perfLabelAddition = [ [NSString alloc] initWithFormat:@" %.0f%@", marginWeight, unitNameForComputation ];
                //NSLog(@"perfLabelAddition %@", perfLabelAddition);
            }
            
        }
        
    }
    
    //check for extraWarning
    
    int triggerWarning = 0;
   
    
    if (chartAdditionalInfo.length > 1 ) {  
        
        NSString *warningName = @"extraWarning";        
        if ( [chartAdditionalInfo rangeOfString:warningName].location != NSNotFound ){  
            //NSLog(@"extraWarning");
            NSRange range = [chartAdditionalInfo rangeOfString:warningName];
            if (range.location == NSNotFound) {
                //NSLog(@"string was not found");
            } else {               
                float pos = range.location;                   
                //check DA or PA...
                NSString *codeItem =  [chartAdditionalInfo substringWithRange:NSMakeRange(pos+12, 2)];                
                NSString *codeKrokodilmaul =  [chartAdditionalInfo substringWithRange:NSMakeRange(pos+14, 1)];
                NSString *codeValue =  [chartAdditionalInfo substringWithRange:NSMakeRange(pos+15, 5)];
                
                //NSLog(@"codeItem %@", codeItem);
                //NSLog(@"codeKrokodilmaul %@", codeKrokodilmaul);
                //NSLog(@"codeValue %@", codeValue);
             
                if ([codeItem isEqualToString:@"DA"]) {                    
                    if ([codeKrokodilmaul isEqualToString:@">"]) {
                        if (DensityAlt > [codeValue floatValue]) {
                            triggerWarning = 1;
                            //NSLog(@"DA alarm");
                            perfLabelAddition = @" >DA";
                        }
                    }                    
                }
                
                if ([codeItem isEqualToString:@"PA"]) {                    
                    if ([codeKrokodilmaul isEqualToString:@">"]) {
                        if (DensityAlt > [codeValue floatValue]) {
                            triggerWarning = 1;
                            //NSLog(@"PA alarm");
                            perfLabelAddition = @" >PA";
                        }
                    }                    
                }
                
                if ([codeItem isEqualToString:@"TK"]) {                    
                    if ([codeKrokodilmaul isEqualToString:@"<"]) {
                        if (resultFromComputations-[codeValue floatValue] <  acWeight & warningsOnOff == 1) {
                            triggerWarning = 2;                            
                            perfLabelAddition = [ [NSString alloc] initWithFormat:@" !<%.0fkg",  [codeValue floatValue]  ];;
                        }
                    }                    
                }
                if ([codeItem isEqualToString:@"TL"]) {                    
                    if ([codeKrokodilmaul isEqualToString:@"<"]) {
                        if (resultFromComputations-[codeValue floatValue] <  acWeight & warningsOnOff == 1) {
                            triggerWarning = 2;                           
                            perfLabelAddition = [ [NSString alloc] initWithFormat:@" !<%.0flbs",  [codeValue floatValue]  ];
                        }
                    }                    
                }
                
                
            }          
        }
        
        
        
        warningName = @"maxOperatingAlt";  //maxOperatingAlt20000and02720to02835is12000and02835to02910is10000Y0600text=12345
        
        if ( [chartAdditionalInfo rangeOfString:warningName].location != NSNotFound ){  
            
                   //NSLog(@"extraWarning");
                   NSRange range = [chartAdditionalInfo rangeOfString:warningName];
                   if (range.location == NSNotFound) {
                       //NSLog(@"string was not found");
                   } else {  
                       
                       float pos = range.location; 
                       if (chartAdditionalInfo.length > pos + 64) {    
                      
                       //check DA or PA...
                       float maxOPAlt =  [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+15, 5)] floatValue];  
                       //NSLog(@"maxOPAlt %f", maxOPAlt);
                       float weight1from =  [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+23, 5)] floatValue];  
                       //NSLog(@"weight1from %f", weight1from);
                       float weight1to =  [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+30, 5)] floatValue];  
                       //NSLog(@"weight1to %f", weight1to);
                       float maxOPAlt1 =  [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+37, 5)] floatValue];  
                       //NSLog(@"maxOPAlt1 %f", maxOPAlt1);
                       
                       float weight2from =  [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+45, 5)] floatValue];  
                       //NSLog(@"weight2from %f", weight2from);
                       float weight2to =  [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+52, 5)] floatValue];  
                       //NSLog(@"weight2to %f", weight2to);
                       float maxOPAlt2 =  [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+59, 5)] floatValue];  
                       //NSLog(@"maxOPAlt2 %f", maxOPAlt2);
                       float labelYpos = 0;
                       NSString *altLimitText = @"";
                       
                       
                           labelYpos = [[chartAdditionalInfo substringWithRange:NSMakeRange(pos+65, 4)] floatValue]; 
                           NSRange rangeEnd = [chartAdditionalInfo rangeOfString:@"EndOfText"];
                           float posEnd = rangeEnd.location;  
                           altLimitText = [chartAdditionalInfo substringWithRange:NSMakeRange(pos+74, ((posEnd-pos)-74))];
                           altLimitText = [altLimitText stringByReplacingOccurrencesOfString:@"_" withString:@" "];
                           //NSLog(@"altLimitText %@",altLimitText);                           
                           UILabel *dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.viewHelicopterInCenter viewWithTag:121212 ];
                           labelYpos = labelYpos;
                           dL.hidden = YES;
                           dL.frame =  CGRectMake(parent.labelConfigurationName2.frame.origin.x, parent.labelConfigurationName2.frame.origin.y + labelYpos, parent.labelConfigurationName2.frame.size.width, parent.labelConfigurationName2.frame.size.height );                        
                           
                           if (Hp > maxOPAlt) {
                               dL.hidden = NO;
                               dL.text = [ [NSString alloc] initWithFormat:@"Max Operating Alt = %.0f ft", maxOPAlt  ];
                           }
                           
                           
                           if (acWeight > weight1from & acWeight <= weight1to) {
                                   dL.hidden = NO;
                                   dL.text = [ [NSString alloc] initWithFormat:altLimitText,  weight1from, maxOPAlt1  ];
                           }
                           
                           if (acWeight > weight2from & acWeight <= weight2to) {
                                   dL.hidden = NO;
                                   dL.text = [ [NSString alloc] initWithFormat:altLimitText,  weight2from, maxOPAlt2  ];
                           }
                           
                           
                           
                       }
                       
                       
                       
                       /*
                       if (Hp > maxOPAlt) {
                           triggerWarning = 1;
                           perfLabelAddition = [ [NSString alloc] initWithFormat:@" >%.0f'", maxOPAlt  ];;
                       }
                       
                       if (acWeight > weight1from & acWeight <= weight1to) {                           
                           if (Hp > maxOPAlt) {
                               triggerWarning = 1;                               
                               perfLabelAddition = [ [NSString alloc] initWithFormat:@" >%.0f'", maxOPAlt1  ];;
                           }
                       }
                       
                       if (acWeight > weight2from & acWeight <= weight2to) {                           
                           if (Hp > maxOPAlt2) {
                               triggerWarning = 1;                               
                               perfLabelAddition = [ [NSString alloc] initWithFormat:@" >%.0f'", maxOPAlt2  ];;
                           }
                       }
                        */
                       
                       
                       
                       
                   }
            
        }
            
        
        
        
        
    }//end of check for extraWarning
   
    //NSLog(@"unitNameForComputation %@", unitNameForComputation);
    
    // check warnings
    dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   actualButtonNumber + 200  ];
    
    // check if percent, then add one digit for precision
    if ([unitNameForComputation rangeOfString:@"%"].location != NSNotFound ){
        
        float altDiff = 0;
        float VTossKIAS = 0;        
        //NSLog(@"unitNameForComputation %@", unitNameForComputation);
        
        if ([unitNameForComputation isEqualToString:@"%GradH145"] ){
            dL.text = [ [NSString alloc] initWithFormat:@"%.1f%%", resultFromComputations  ];
        }        
        if ([unitNameForComputation isEqualToString:@"%Grad"] ){
            altDiff = 165;
            VTossKIAS = 50;
            // compute horizontal distance to climb from 35 to 200 feet at 50 KIAS
            //fpm = Gradient * Speed
            float gradient = resultFromComputations;
            float fpm = gradient * VTossKIAS;
            float timeNeededForClimbMinutes = altDiff / fpm;
            float distanceAtVTOSSinNM = VTossKIAS * timeNeededForClimbMinutes / 60;
            float distanceInFeet = distanceAtVTOSSinNM * 6076.12;
            //dL.text = [ [NSString alloc] initWithFormat:@"%.1f %@", resultFromComputations, unitNameForComputation  ];
            dL.text = [ [NSString alloc] initWithFormat:@"%.1f%% = %.0f ft", resultFromComputations, distanceInFeet  ];
        }
        
        if ([unitNameForComputation isEqualToString:@"%Grad800"] ){
            altDiff = 800;
            VTossKIAS = 60;
            // compute horizontal distance to climb from 35 to 200 feet at 50 KIAS
            //fpm = Gradient * Speed
            float gradient = resultFromComputations;
            float fpm = gradient * VTossKIAS;
            float timeNeededForClimbMinutes = altDiff / fpm;
            float distanceAtVTOSSinNM = VTossKIAS * timeNeededForClimbMinutes / 60;
            float distanceInFeet = distanceAtVTOSSinNM * 6076.12;
            //dL.text = [ [NSString alloc] initWithFormat:@"%.1f %@", resultFromComputations, unitNameForComputation  ];
            dL.text = [ [NSString alloc] initWithFormat:@"%.1f%% = %.0f ft", resultFromComputations, distanceInFeet  ];
        }
        
        if ([unitNameForComputation isEqualToString:@"%Path"] ){
            dL.text = [ [NSString alloc] initWithFormat:@"%.1f%%", resultFromComputations  ];            
        }
        if ([unitNameForComputation isEqualToString:@"%Path0"] ){
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f %%", resultFromComputations  ];            
        }
        
        if ([unitNameForComputation isEqualToString:@"torque%MTOWkg"] ){
            //NSLog(@"resultTorquePercent %f", resultTorquePercent);
            //NSLog(@"resultFromComputations %f", resultFromComputations);
            
            if (resultTorquePercent > 70 & resultFromComputations >2500) {
                
                dL.text = [ [NSString alloc] initWithFormat:@"%.0f%% / 2500kg", resultTorquePercent  ];   
            }else if (resultTorquePercent > 70 & resultFromComputations < 1) {
                
                dL.text = [ [NSString alloc] initWithFormat:@"%.0f%% / 2500kg", resultTorquePercent  ];   
            }else{
                dL.text = [ [NSString alloc] initWithFormat:@"%.0f%% / %.0fkg", resultTorquePercent, resultFromComputations  ];  
            }
                      
        }
        
       
        
        if ([unitNameForComputation isEqualToString:@"torque%TOT"] ){            
                 
                 if (OAT < 3) {                     
                     //NSLog(@"1 chartNameForComputation %@", chartNameForComputation);
                     
                         //NSLog(@"cross4ValueY %.1f", cross4ValueY);
                         //NSLog(@"resultTOT %.1f", resultTOT);
                         
                         
                         if (fabsf(cross4ValueY - resultTOT) < 2) {
                             dL.text = [ [NSString alloc] initWithFormat:@"%.0f%% / %.0fºC", resultTorquePercent, IAS  ];  //IAS ist hier TOT Celsius 
                         }else{
                             dL.text = [ [NSString alloc] initWithFormat:@"%.0f%% / ? ºC", resultTorquePercent  ];  //IAS ist hier TOT Celsius 
                         }
                    
                     
                 }else{
                     //NSLog(@"3");
                     if (fabsf(cross4ValueY - cross5ValueY) < 2) {
                         dL.text = [ [NSString alloc] initWithFormat:@"%.0f%% / %.0fºC", resultTorquePercent, IAS  ];  //IAS ist hier TOT Celsius 
                     }else{
                         dL.text = [ [NSString alloc] initWithFormat:@"%.0f%% / ? ºC", resultTorquePercent  ];  //IAS ist hier TOT Celsius 
                     }
                     
                     
                 }
          
            
            //NSLog(@"cross4ValueY %f", cross4ValueY); 
            //NSLog(@"cross5ValueY %f", cross5ValueY);                   
            
        }
        
        
        
        
        
        
        // if no % is found
    }else if ([unitNameForComputation rangeOfString:@"percGrad"].location != NSNotFound ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.2f %%", resultFromComputations  ];
        
    }else if ([unitNameForComputation rangeOfString:@"sec"].location != NSNotFound ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.1f %@", resultFromComputations , unitNameForComputation ];
        
    }else if ([unitNameForComputation rangeOfString:@"TV"].location != NSNotFound ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.2f %@", resultFromComputations, unitNameForComputation  ];
        
    }else if ([unitNameForComputation rangeOfString:@"noUnit"].location != NSNotFound ){
        
        //NSLog(@"no unit ");
        dL.text = [resultsAllChartValues objectAtIndex:chartNumberForResult];
    }else if ([unitNameForComputation rangeOfString:@"noLabel1digit"].location != NSNotFound ){
        
         dL.text = [ [NSString alloc] initWithFormat:@"%.1f", resultFromComputations  ];
        
    }else if ([unitNameForComputation rangeOfString:@"noLabel2digits"].location != NSNotFound ){
        
         dL.text = [ [NSString alloc] initWithFormat:@"%.2f", resultFromComputations  ];
        
    }else if ([unitNameForComputation rangeOfString:@"envelopeName"].location != NSNotFound ){
        //see swift
        dL.text = [ [NSString alloc] initWithFormat:@"%@", foundCATEnvelopeName  ];
        
        
    }else{
         
        if (flagWeHavePenaltyData == 1) {  
            //NSLog(@"userNameForComputation %@", userNameForComputation);            
            ViewController *parent = (ViewController *)self.parentViewController;
            
            arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"penaltyData" ];
            NSString *penaltyData = [[NSUserDefaults standardUserDefaults] objectForKey:arrayKey]; 
            NSArray* componentItems  = [penaltyData componentsSeparatedByString:@"+"];
            for (int i = 1; i < componentItems.count ; i++) { 
                NSArray *penaltyArray  = [[componentItems objectAtIndex:i] componentsSeparatedByString:@";"];  
                //check if penalty data name is switched on
                for (int segNr = 4; segNr < lineOptions ; segNr++) {
                    if ([[parent.arrayName1 objectAtIndex:segNr] isEqualToString:[penaltyArray objectAtIndex:0]]) {
                        //NSLog(@"found penaltyName %@",[parent.arrayName1 objectAtIndex:segNr]);                    
                        if ([[parent.arrayName8 objectAtIndex:segNr] isEqualToString:@"1"]) {
                            for (int i = 1; i<4;i++) {
                                if ([[penaltyArray objectAtIndex:i] rangeOfString:userNameForComputation].location != NSNotFound     ) {
                                    //NSLog(@"!!!!!! and it is %@", userNameForComputation);    
                                    NSArray *penaltyDetails = [[penaltyArray objectAtIndex:i] componentsSeparatedByString:@"_"];   
                                    //NSLog(@"operand is %@", [penaltyDetails objectAtIndex:1]);  
                                    //NSLog(@"value is %@", [penaltyDetails objectAtIndex:2]); 
                                    //NSLog(@"1 resultFromComputations %f", resultFromComputations); 
                                    if ([[penaltyDetails objectAtIndex:1] isEqualToString:@"num"]) {
                                        resultFromComputations = resultFromComputations + [[penaltyDetails objectAtIndex:2] floatValue];
                                        //NSLog(@"[penaltyDetails objectAtIndex:0] %@", [penaltyDetails objectAtIndex:0]);                                          
                                        if ([[penaltyDetails objectAtIndex:0] isEqualToString:@"TAS CAS"]) {
                                             totalAirspeedPenalty = totalAirspeedPenalty + [[penaltyDetails objectAtIndex:2] floatValue];
                                        }
                                        if ([[penaltyDetails objectAtIndex:0] isEqualToString:@"Fuel Flow"]) {
                                            totalFuelFlowPenalty = totalFuelFlowPenalty + [[penaltyDetails objectAtIndex:2] floatValue];
                                        }
                                        if ([[penaltyDetails objectAtIndex:0] isEqualToString:@"Range Fast Cruise"]) {
                                            totalRangePenalty = totalRangePenalty + [[penaltyDetails objectAtIndex:2] floatValue];
                                        }
                                       
                                    }else{
                                        resultFromComputations = resultFromComputations * (1+([[penaltyDetails objectAtIndex:2] floatValue]/100));
                                        
                                        if ([[penaltyDetails objectAtIndex:0] isEqualToString:@"TAS CAS"]) {
                                            totalAirspeedPenalty = totalAirspeedPenalty + resultFromComputations * ([[penaltyDetails objectAtIndex:2] floatValue]/100);
                                        }
                                        if ([[penaltyDetails objectAtIndex:0] isEqualToString:@"Fuel Flow"]) {
                                            totalFuelFlowPenalty = totalFuelFlowPenalty + resultFromComputations * ([[penaltyDetails objectAtIndex:2] floatValue]/100);
                                        }
                                        if ([[penaltyDetails objectAtIndex:0] isEqualToString:@"Range Fast Cruise"]) {
                                            totalRangePenalty = totalRangePenalty + resultFromComputations * ([[penaltyDetails objectAtIndex:2] floatValue]/100);
                                        }
                                        
                                        
                                    }  
                                    
                                   
                                    
                                }
                             }
                          }
                        
                        break;                        
                    }
                }
                
                //NSLog(@"userNameForComputation %@", userNameForComputation);
                //this is the name of the options switch, we need to know if this is on or not
                //NSLog(@"[penaltyArray objectAtIndex:0] %@", [penaltyArray objectAtIndex:0]); 
                                
            }
        }
        
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f %@", resultFromComputations, unitNameForComputation  ];
        
        if ([unitNameForComputation isEqualToString:@"kg"] && [selectedUnitsForItems isEqualToString:@"kg"]) {
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f kg", resultFromComputations  ];
        }        
        if ([unitNameForComputation isEqualToString:@"kg"] && [selectedUnitsForItems isEqualToString:@"lbs"]) {
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f lbs", resultFromComputations * 2.2046 ];
        }
        
       
        if ([unitNameForComputation isEqualToString:@"lbs"] && [selectedUnitsForItems isEqualToString:@"lbs"]) {
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f lbs", resultFromComputations  ];
        }
        
        if ([unitNameForComputation isEqualToString:@"lbs"] && [selectedUnitsForItems isEqualToString:@"kg"]) {
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f kg", resultFromComputations / 2.2046  ];
        }
                
    }
    
    
    if (computationErrorDisplay.length > 1 ) {
        triggerWarning = 1;
    }    
    
    
    // button warning (only if in noted availableCharts !!)
    if (chartAdditionalInfo.length > 1 ) {
        
        if ( [chartAdditionalInfo rangeOfString:@"warningPAValue"].location != NSNotFound ){
            if (resultFromComputations <  Hp & warningsOnOff == 1) {
                triggerWarning = 1;
                //NSLog(@"case 1");
            }
        }
        
        
        if ( [chartAdditionalInfo rangeOfString:@"warningACweight"].location != NSNotFound ){
            
            if (resultFromComputations <  acWeight & warningsOnOff == 1) {
                triggerWarning = 1;
                
            }
        }
        
        
        if ( [chartAdditionalInfo rangeOfString:@"warningResultValue"].location != NSNotFound ){
            
            float warningValue = [chartAdditionalInfo floatValue] ;
            
            if ( [chartAdditionalInfo rangeOfString:@"<"].location != NSNotFound ){
                if (resultFromComputations <=  warningValue & warningsOnOff == 1) {
                    triggerWarning = 1;
                    //NSLog(@"case 3");
                }
            }
            
            if ( [chartAdditionalInfo rangeOfString:@">"].location != NSNotFound ){
                if (resultFromComputations >=  warningValue & warningsOnOff == 1) {
                    triggerWarning = 1;
                    //NSLog(@"case 4");
                }
            }
        }
        
        
        //NSLog(@"triggerWarning %d", triggerWarning);
        
        
        
        
        if (triggerWarning == 1) {
            UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
            [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateNormal];
            [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateSelected];
        }else if (triggerWarning == 2) {
            UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
            [buttonToWarn setBackgroundImage:buttonOrange forState:UIControlStateNormal];
            [buttonToWarn setBackgroundImage:buttonOrange forState:UIControlStateSelected];
        }else{
            UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
            [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateNormal];
            if ( [buttonToWarn isSelected ]) {
                [buttonToWarn setBackgroundImage:buttonBlue forState:UIControlStateSelected];
            }else{
                [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateSelected];
            }
        }
        
    }
    
    
    
    if (perfLabelAddition.length > 0) {
        
        if ([perfLabelAddition rangeOfString:@"!"].location != NSNotFound && triggerWarning == 1 ){
            perfLabelAddition = @"";
        }
        
        
       dL.text = [dL.text stringByAppendingString: perfLabelAddition  ];
    }
    
    int flagRange = [[resultsAllDataOutOfRange objectAtIndex:chartNumberForResult] intValue];
    
    if ([userNameForComputation rangeOfString:@"H-V_Diagram"].location != NSNotFound  ){
        if (resultFromComputations < 40) {
            dL.text = @"No H-V Area";
        }
    }
    
    
    
    
    if ([userNameForComputation rangeOfString:@"Grnd"].location != NSNotFound        ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0fm", resultFromComputations,  resultFromComputations * 0.3048 ];
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
    }
    
    
    if ([userNameForComputation rangeOfString:@"Stop"].location != NSNotFound        ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0fm", resultFromComputations,  resultFromComputations * 0.3048 ];
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
    }
    
    if ([userNameForComputation rangeOfString:@"TOD"].location != NSNotFound        ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0fm", resultFromComputations,  resultFromComputations * 0.3048 ];
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
    }
  
    if ([userNameForComputation rangeOfString:@"TO "].location != NSNotFound        ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0fm", resultFromComputations,  resultFromComputations * 0.3048 ];
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
    }
    
    //dhc6
    if ([userNameForComputation rangeOfString:@"TOGroundRoll"].location != NSNotFound        ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0fm", resultFromComputations,  resultFromComputations * 0.3048 ];
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
    }
    
 
    if ([userNameForComputation rangeOfString:@"Landing-"].location != NSNotFound        ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0fm", resultFromComputations,  resultFromComputations * 0.3048 ];     
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
    }
  
    
 
    if (AS365N3minWeight1 !=0     ){
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f-%.0f kg", AS365N3minWeight1,  AS365N3minWeight2 ];
        [dL setFont:[UIFont boldSystemFontOfSize:16]];
    }
  
   
   
    
    if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomR44"].location != NSNotFound) {      
        //NSLog(@"[infoArray objectAtIndex:6] %@", [infoArray objectAtIndex:6]);
        if ([[infoArray objectAtIndex:6]  rangeOfString:@"Manifold"].location != NSNotFound  ) {  
        dL.text = [ [NSString alloc] initWithFormat:@"%.1f\" / %.1f\"", fiveMinuteTakeoffPowerResult,  maxContinuousPowerResult ];     
        [dL setFont:[UIFont boldSystemFontOfSize:15]];
        }
    }
    
    if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomR44"].location != NSNotFound) {
        if ([[infoArray objectAtIndex:6]  rangeOfString:@"R44RavenIIVNE"].location != NSNotFound) {  
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f KIAS", VNEinterpolTotal ];     
            [dL setFont:[UIFont boldSystemFontOfSize:15]];
        }
        if ([[infoArray objectAtIndex:6]  rangeOfString:@"R44RavenAstroVNE"].location != NSNotFound) { 
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f KIAS", VNEinterpolTotal ];     
            [dL setFont:[UIFont boldSystemFontOfSize:15]];
        }
        if ([[infoArray objectAtIndex:6]  rangeOfString:@"R22BetaIIVNE"].location != NSNotFound) {  
            dL.text = [ [NSString alloc] initWithFormat:@"%.0f KIAS", VNEinterpolTotal ];     
            [dL setFont:[UIFont boldSystemFontOfSize:15]];
        }
    }
    
    
   
    
    //NSLog(@"resultsAllChartUserNames %@",resultsAllChartUserNames);
    //NSLog(@"actualButtonNumber %d",actualButtonNumber);
    
   
  
     //NSLog(@"1resultLDGGroundRoll %.0f", resultLDGGroundRoll * conversionFeetToMeter);

    
    if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound  ) {
        
        
        
        if ([userNameForComputation rangeOfString:@"TOGroundRoll"].location != NSNotFound  || [userNameForComputation rangeOfString:@"TO50ft"].location != NSNotFound   ){
            dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   (chartNumberForResult +1) + 200  ];
            if (_segmentMeterFeet.selectedSegmentIndex == 0) {
                dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0f'", resultTOGroundRoll,  resultTO50ft ];
            }else{
                dL.text = [ [NSString alloc] initWithFormat:@"%.0fm/%.0fm", resultTOGroundRoll,  resultTO50ft ];
            }
            
            [dL setFont:[UIFont boldSystemFontOfSize:15]];
        }
        
        if ([userNameForComputation rangeOfString:@"Climb"].location != NSNotFound     ){
            dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   (chartNumberForResult +1) + 200  ];
             dL.text = [ [NSString alloc] initWithFormat:@"%@ / %@", _iClimbTimeTotal.text, _iClimbDistanceTotal.text];
            [dL setFont:[UIFont boldSystemFontOfSize:14]];
        }
        
        if ([userNameForComputation rangeOfString:@"Cruise"].location != NSNotFound     ){
            dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   (chartNumberForResult +1) + 200  ];        
            dL.text = [ [NSString alloc] initWithFormat:@"MAX %.0f NM", totalTripRange ];            
            [dL setFont:[UIFont boldSystemFontOfSize:14]];
        }
        
        
        if ([userNameForComputation rangeOfString:@"LDGGroundRoll"].location != NSNotFound  ||      [userNameForComputation rangeOfString:@"LDG50ft"].location != NSNotFound   ){
            dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   (chartNumberForResult +1) + 200  ];
            if (_segmentMeterFeet.selectedSegmentIndex == 0) {
                dL.text = [ [NSString alloc] initWithFormat:@"%.0f'/%.0f'", resultLDGGroundRoll,  resultLDG50ft ];
            }else{
                dL.text = [ [NSString alloc] initWithFormat:@"%.0fm/%.0fm", resultLDGGroundRoll,  resultLDG50ft ];
            }
            [dL setFont:[UIFont boldSystemFontOfSize:15]];
        }
        
        flagRange = 0;
    }
    
     
    
    if (flagRange > 0) {
        dL.text = @"> Range";
    }
    
     //NSLog(@"unitNameForComputation %@", unitNameForComputation);
    
    
    
    //NSLog(@"chartUserName %@", chartUserName);
    
    if ([unitNameForComputation rangeOfString:@"AWHVdiagram"].location != NSNotFound ){        
        if (displayWindow - 100 == actualButtonNumber) {
          parent.viewHVdata.hidden = NO;
          [parent.viewUniversalExtras bringSubviewToFront:parent.viewHVdata];  
          //NSLog(@"switching ON");
            parent.viewHVdata.hidden = NO;
        }else{
            //NSLog(@"switching OFF");
            parent.viewHVdata.hidden = YES;
        }
    
        //see swift     
        //NSLog(@"cross2ValueY %f", cross2ValueY);
        float xLinks = 0;
        float yLinks = cross2ValueY;
        float xRechts = 20;
        float yRechts = 30;
        
        float b5 = xLinks, b6 = yLinks, b7 = xRechts, b8 = yRechts;
        float diffY = b6-b8;
        float diffX = b5-b7;
        float steigung = diffY / diffX;
        float a = b6 - (steigung * b5);
        
        float HV0 = 0 * steigung + a;
        float HV5 =  5 * steigung + a;
        float HV10 =  10 * steigung + a;
        float HV15 =  15 * steigung + a;
        
        if (Yinput < [[infoPartArray objectAtIndex:21] floatValue]) {            
            dL.text = @"NO H-V Area";
            parent.labelNOHVarea.hidden = NO;
            [parent.viewHVdata bringSubviewToFront:parent.labelNOHVarea];  
        }else{
           dL.text = [ [NSString alloc] initWithFormat:@"0kts: %.0f'  10kts: %.0f'", HV0, HV10 ];            
             parent.labelNOHVarea.hidden = YES;            
             parent.lHV0.text = [ [NSString alloc] initWithFormat:@"%.0f'", HV0 ];            
             parent.lHV5.text = [ [NSString alloc] initWithFormat:@"%.0f'", HV5 ];            
             parent.lHV10.text = [ [NSString alloc] initWithFormat:@"%.0f'", HV10 ];            
             parent.lHV15.text = [ [NSString alloc] initWithFormat:@"%.0f'", HV15 ];            
             parent.lHV20.text = [ [NSString alloc] initWithFormat:@"%.0f'", 30.0 ];
        }
    }
    
    if (computationErrorDisplay.length > 1) {
        dL.text = computationErrorDisplay;
    }
    
    
    if (infoPartArray.count > 1 && [[infoPartArray objectAtIndex:14] rangeOfString:@"meterCorrectedByWind"].location != NSNotFound ){   
        //NSLog(@"this is CTO and chartNumberForResult %d ", chartNumberForResult);
        //NSLog(@"cross2ValueX %.0f ", cross2ValueX); // this is the actual distance
        //NSLog(@"cross3ValueX %.0f ", cross3ValueX); // Distance Correction value
        float CTOdistance = cross2ValueX + (cross3ValueX * headWindKTS); //(multiply Distance Correction by HEADWIND component)
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f m", CTOdistance  ];
        
    }
    
    //NSLog(@"userNameForComputation %@", userNameForComputation);
    if ([userNameForComputation rangeOfString:@"CTO Dist OEI"].location != NSNotFound ){
        //NSLog(@"3");
        //NSLog(@"this is CTO and chartNumberForResult %d ", chartNumberForResult);
        //NSLog(@"cross2ValueX %.0f ", cross2ValueX); // this is the actual distance
        //NSLog(@"cross3ValueX %.0f ", cross3ValueX); // Distance Correction value
        float CTOdistance = cross2ValueX + (cross3ValueX * headWindKTS); //(multiply Distance Correction by HEADWIND component)
        dL.text = [ [NSString alloc] initWithFormat:@"%.0f m", CTOdistance  ];
    }
   
    resultText = dL.text;
    
  
    //------------------------------------------------------------------------
    
  
    dL = [[UILabel alloc] init];  dL = (UILabel *)[parent.self.viewUniversalButtons viewWithTag:   actualButtonNumber + 300  ];
    dL.text = chartNameForComputation;
    
   
    
    
    
    if ([limitationsForHoist rangeOfString:@"limitsHoist"].location != NSNotFound ){
        [parent.self.arrayExternalLoadRestrictions addObject:[ [NSString alloc] initWithFormat:@"%.2f", resultFromComputations] ];
        //NSLog(@"adding %@ ", [ [NSString alloc] initWithFormat:@"%.2f", resultFromComputations] );
        //NSLog(@"parent.self.arrayExternalLoadRestrictions %@ ", parent.self.arrayExternalLoadRestrictions );
    }
    
    
    //NSLog(@"infoArray %@", infoArray);
    //NSLog(@"[infoArray objectAtIndex:2];  %@", [infoArray objectAtIndex:2]);
    
    if ([[infoArray objectAtIndex:2] rangeOfString:@"line"].location != NSNotFound) {
        flagDrawACweightLines = 1;
    }else{
        flagDrawACweightLines = 0;
    }
    
   //NSLog(@"flagDrawACweightLines  %d", flagDrawACweightLines);
    
    
    
    
    
    //NSLog(@"check ======== chartAdditionalInfo %@", chartAdditionalInfo);
    

 
    
    
    if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound && [userNameForComputation rangeOfString:@"Cruise"].location != NSNotFound  ) {  
        
        if (triggerCruiseRangeWarning == 1) {
            UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
            [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateNormal];
            [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateSelected];
        }else{
            UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
            [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateNormal];
            if ( [buttonToWarn isSelected ]) {
                [buttonToWarn setBackgroundImage:buttonBlue forState:UIControlStateSelected];
            }else{
                [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateSelected];
            }
        }
    }
    
    
    
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound && [chartNameForThisInfoFile rangeOfString:@"CruiseComp"].location != NSNotFound ) {
        
        //NSLog(@"chartNameForThisInfoFile %@", chartNameForThisInfoFile);
        
        //NSLog(@"triggerCruiseRangeWarning %d", triggerCruiseRangeWarning);
        
        if (triggerCruiseRangeWarning == 1) {
            UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: 4 ];
            [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateNormal];
            [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateSelected];
        }else{
            UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: 4 ];
            [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateNormal];
            if ( [buttonToWarn isSelected ]) {
                [buttonToWarn setBackgroundImage:buttonBlue forState:UIControlStateSelected];
            }else{
                [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateSelected];
            }
        }
        
    }
    
    NSString *enviText =@"";
    
    
   
     if ([[infoArray objectAtIndex:3]  rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound  ) {
        enviText =   [ [NSString alloc] initWithFormat:@"%@|%@|%.0f|%.0f|%.0f|%@", chartUserName, resultText ,OAT, Hp, headWindKTS, @"CustomFixedWingOLD" ];          
     }else if ([[infoArray objectAtIndex:0]  rangeOfString:@"FXX"].location != NSNotFound  ) {
        enviText =   [ [NSString alloc] initWithFormat:@"%@|%@|%.0f|%.0f|%.0f|%@", chartUserName, resultText ,OAT, Hp, headWindKTS, @"FXX" ]; 
     } else {
        enviText =   [ [NSString alloc] initWithFormat:@"%@|%@|%.0f|%.0f|%.0f|%@", chartUserName, resultText ,OAT, Hp, headWindKTS, @"standard" ];
   
     }
    
     //NSLog(@"adding %@", enviText);
     [resultsAllEnviSettings addObject:enviText];
   
    
    if (flagWeHaveAS365PC2computation == 1) {
        [self computeAS365N3PC2];
    }
    
    if ([userNameForComputation rangeOfString:@"RoC"].location != NSNotFound     ){
        //NSLog(@"w1");
        if (flagCeilingComputation == 2) {
            //NSLog(@"w2");
            // it's a ROC ceiling computation!
            //flagDrawACweightLines = 1;
            if (resultFromComputations < Hp) {
                UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
                [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateNormal];
                [buttonToWarn setBackgroundImage:buttonRed forState:UIControlStateSelected];
            }else{
                UIButton *buttonToWarn = (UIButton *)[parent.self.viewUniversalButtons viewWithTag: actualButtonNumber ];
                [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateNormal];
                if ( [buttonToWarn isSelected ]) {
                    [buttonToWarn setBackgroundImage:buttonBlue forState:UIControlStateSelected];
                }else{
                    [buttonToWarn setBackgroundImage:buttonGrey forState:UIControlStateSelected];
                }
            }
        }
        
        
    }
   
   
    
    return;
    
    
    
}




- (void) drawCrossesAndLines {
    
     
     if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  || [[infoArray objectAtIndex: 3  ] rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound          ) {
         //NSLog(@"returning drawCrossesAndLines");
       return;
    }   
    
    viewCross2.hidden = YES;
    viewCross3.hidden = YES;
    viewCross4.hidden = YES;
    viewCross5.hidden = YES;
    
    //[_viewLinesOnChart.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    
    for (UIView *subview in _viewLinesOnChart.subviews) {
        [subview removeFromSuperview];
    }
    
    [_viewLinesOnChart.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines
    
    
    //NSLog(@"newWPDdataAvialable %d " , newWPDdataAvialable);
    
    for (nCross =1; nCross<numberOfComputationParts+1; nCross++) {
        infoPartNumber = nCross;
        [self getInfoFileForThisPart];
        
        if (newWPDdataAvialable == 1) {
            
            xPix1 = [[infoPartArray objectAtIndex:25] floatValue];
            xPix2 = [[infoPartArray objectAtIndex:26] floatValue];
            xPix3 = [[infoPartArray objectAtIndex:29] floatValue];
            
            yPix1 = [[infoPartArray objectAtIndex:27] floatValue];
            yPix2 = [[infoPartArray objectAtIndex:28] floatValue];
            yPix3 = [[infoPartArray objectAtIndex:30] floatValue];
            
            chartWidthPixel = [[infoPartArray objectAtIndex:23] floatValue];
            chartHeightPixel = [[infoPartArray objectAtIndex:24] floatValue];
            
            xLeftChart = [[infoPartArray objectAtIndex:17] floatValue]; // min Input
            yBottomChart = [[infoPartArray objectAtIndex:19] floatValue]; // min Result
            xRightChart = [[infoPartArray objectAtIndex:18] floatValue]; // max Input
            yTopChart = [[infoPartArray objectAtIndex:20] floatValue]; // max Result
            
        }else{
            
            chartWidthPixel = [[infoPartArray objectAtIndex:23] floatValue];
            chartHeightPixel = [[infoPartArray objectAtIndex:24] floatValue];
            
            xLeftChart = [[infoPartArray objectAtIndex:17] floatValue]; // min Input
            yBottomChart = [[infoPartArray objectAtIndex:19] floatValue]; // min Result
            xRightChart = [[infoPartArray objectAtIndex:18] floatValue]; // max Input
            yTopChart = [[infoPartArray objectAtIndex:20] floatValue]; // max Result
            
            xLeftGC = [[infoPartArray objectAtIndex:31] floatValue];
            yBottomGC = [[infoPartArray objectAtIndex:32] floatValue];
            xRightGC = [[infoPartArray objectAtIndex:33] floatValue];
            yTopGC = [[infoPartArray objectAtIndex:34] floatValue];
            
            xposition = ((chartWidthPixel/10 * xLeftGC * (chartWidthInApp / chartWidthPixel))) + (((((chartWidthPixel/10 * xRightGC * (chartWidthInApp / chartWidthPixel))) - ((chartWidthPixel/10 * xLeftGC * (chartWidthInApp / chartWidthPixel))))/((xRightChart - xLeftChart))) * (Xinput  - xLeftChart)) ;
            
            yposition = ((chartHeightPixel - (chartHeightPixel/10 * yBottomGC)) * (chartHeightInApp / chartHeightPixel)) + (((((chartHeightPixel - (chartHeightPixel/10 * yTopGC)) * (chartHeightInApp / chartHeightPixel)) - ((chartHeightPixel - (chartHeightPixel/10 * yBottomGC)) * (chartHeightInApp / chartHeightPixel)))/(yTopChart - yBottomChart)) * (Yinput - yBottomChart)) ;
            
            //NSLog(@"xposition %.3f ", xposition);
            //NSLog(@"yposition %.3f ", yposition);
            
        }
        
        
      
      
        
        if (nCross == 1) {
            Xinput = cross1ValueX;
            Yinput = cross1ValueY;
            [self computeChartSizeInApp];
            _universalChartGraphic.frame = CGRectMake(0, 0, chartWidthInApp, chartHeightInApp);
            if (newWPDdataAvialable == 1) {
                [self drawLine];
            }
            //_crossUniversal1.center = CGPointMake( xposition, yposition);
            viewCross1.center = CGPointMake( xposition, yposition);
        }
        
        
        if (nCross == 2) {
            
            Xinput = cross2ValueX;
            Yinput = cross2ValueY;
            [self computeChartSizeInApp];
            _universalChartGraphic.frame = CGRectMake(0, 0, chartWidthInApp, chartHeightInApp);
            
            if (newWPDdataAvialable == 1) {
                [self drawLine];
            }
            viewCross2.hidden = NO;
            viewCross2.center = CGPointMake( xposition, yposition);
        }
        
        
        if (nCross == 3) {
            Xinput = cross3ValueX;
            Yinput = cross3ValueY;
            [self computeChartSizeInApp];
            _universalChartGraphic.frame = CGRectMake(0, 0, chartWidthInApp, chartHeightInApp);
            if (newWPDdataAvialable == 1) {
                [self drawLine];
            }
            viewCross3.hidden = NO;
            viewCross3.center = CGPointMake( xposition, yposition);
        }
        
        
        if (nCross == 4) {
            Xinput = cross4ValueX;
            Yinput = cross4ValueY;
            
            //NSLog(@"cross4ValueX %f ", cross4ValueX);
            //NSLog(@"cross4ValueY %f ", cross4ValueY);
            
            [self computeChartSizeInApp];
            _universalChartGraphic.frame = CGRectMake(0, 0, chartWidthInApp, chartHeightInApp);
            if (newWPDdataAvialable == 1) {
                [self drawLine];
            }
            viewCross4.hidden = NO;
            viewCross4.center = CGPointMake( xposition, yposition);
        }
        
        
        if (nCross == 5) {
            Xinput = cross5ValueX;
            Yinput = cross5ValueY;
            
            //NSLog(@"cross5ValueX %f ", cross5ValueX);
            //NSLog(@"cross5ValueY %f ", cross5ValueY);
            
            [self computeChartSizeInApp];
            _universalChartGraphic.frame = CGRectMake(0, 0, chartWidthInApp, chartHeightInApp);
            if (newWPDdataAvialable == 1) {
                [self drawLine];
            }
            viewCross5.hidden = NO;
            viewCross5.center = CGPointMake( xposition, yposition);
        }
        
        
        
        
    }
    
    
    
    
}




- (void) drawLine {
    
    
    // make lines
    
    //NSLog(@"drawLine *****************************");
    //NSLog(@"Xinput  %.1f ", Xinput);
    //NSLog(@"Yinput  %.1f ", Yinput);
    //NSLog(@"cross1ValueY  %.0f ", cross1ValueY);        
    
    // x1 lines on chart
    
    float scaleFactorX = _universalChartGraphic.frame.size.width /  chartWidthPixel;
    float xPosX_pixel =  (xPix1)*Xinput + (xPix2)*Yinput+ (xPix3);
    xposition = xPosX_pixel * scaleFactorX;    
    
    //NSLog(@"xPix1  %.10f ", xPix1);
    //NSLog(@"xPix2  %.10f ", xPix2);
    //NSLog(@"xPix3  %.10f ", xPix3);
    
    //NSLog(@"yPix1  %.10f ", yPix1);
    //NSLog(@"yPix2  %.10f ", yPix2);
    //NSLog(@"yPix3  %.10f ", yPix3);
    
    //NSLog(@"cross1ValueY  %.0f ", cross1ValueY);
    //NSLog(@"_universalChartGraphic.frame.size.width  %.0f ", _universalChartGraphic.frame.size.width);
    //NSLog(@"chartWidthPixel  %.0f ", chartWidthPixel);
    //NSLog(@"xposition  %.0f ", xposition);
    
    float yPosY_pixel = (yPix1)*Xinput + (yPix2)*Yinput + (yPix3);
    yposition = yPosY_pixel * scaleFactorX;
    //NSLog(@" (yPix1)*Xinput  %.0f ",  (yPix1)*Xinput);
    //NSLog(@" (yPix2)*Yinput %.0f ",  (yPix2)*Yinput  );
    //NSLog(@" (yPix3) %.0f ",   (yPix3) );
    //NSLog(@"yPosY_pixel  %.0f ", yPosY_pixel);
    //NSLog(@"yposition  %.0f ", yposition);
    
    
    _viewLinesOnChart.frame = CGRectMake(0, 0, _universalChartGraphic.frame.size.width, _universalChartGraphic.frame.size.height);    
    _viewLinesOnChart.backgroundColor = [UIColor clearColor];
    
    if (flagAWHVdiagram == 1) {
        crossLineSequence = @"lcH";        
    }
    
    NSString *lineDirectionFrom = [crossLineSequence substringToIndex:1];  
    NSString *lineDirectionTO = [crossLineSequence substringFromIndex:2];
   
    if (yToX == 0) {
        
        
        // check if base left in the lower x values
        if ( (xPix1)*minInput + (xPix2)*Yinput+ (xPix3)  < (xPix1)*maxInput + (xPix2)*Yinput+ (xPix3) ) {
            // xAxis is normal (left = low right = high)
            //NSLog(@"XtoY *******  xAxis is normal  ");
            lineBaseLeftX =     minInput;
            lineBaseRightX =    maxInput;
        }else{
            //NSLog(@"XtoY *******  xAxis reversed ");
            lineBaseLeftX =     maxInput;
            lineBaseRightX =    minInput;
        }
        
        // check if base top is higher than base bottom
        
        if ( (yPix1)*Xinput + (yPix2)*minResult + (yPix3)  > (yPix1)*Xinput + (yPix2)*maxResult + (yPix3) ) {
            // yAxis is normal (left = low right = high)
            //NSLog(@"XtoY *******  yAxis is normal ");
            lineBaseBottomY =   minResult;
            lineBaseTopY =      maxResult;
        }else{
            //NSLog(@"XtoY *******  yAxis reversed ");
            lineBaseBottomY =   maxResult;
            lineBaseTopY =      minResult;
        }
        
        
        
        if ([lineDirectionFrom isEqualToString:@"b"]) {
            
            // we need to draw from bottom to cross
            float yPosY_pixel_lineBase = (yPix1)*Xinput + (yPix2)*lineBaseBottomY + (yPix3); // here is the base line for Y
            float yposition_lineBase = yPosY_pixel_lineBase * scaleFactorX;
            
            pathLine = [UIBezierPath bezierPath];
            [pathLine moveToPoint:CGPointMake( xposition, yposition_lineBase )]; // move to base
            [pathLine addLineToPoint:CGPointMake( xposition, yposition  )  ]; // from base to cross
            
        }
        
        if ([lineDirectionFrom isEqualToString:@"t"]) {
            
            // we need to draw from top to cross (lineBaseTopY)
            float yPosY_pixel_lineBase = (yPix1)*Xinput + (yPix2)*lineBaseTopY + (yPix3); // here is the base line for Y
            float yposition_lineBase = yPosY_pixel_lineBase * scaleFactorX;
            
            pathLine = [UIBezierPath bezierPath];
            [pathLine moveToPoint:CGPointMake( xposition, yposition_lineBase )]; // move to base
            [pathLine addLineToPoint:CGPointMake( xposition, yposition  )  ]; // from base to cross
            
        }
        
        
        
        if ([lineDirectionFrom isEqualToString:@"f"]) {
            
            //NSLog(@"special draw ");
            
            // prepare Y position
            float yPosY_pixel_lineBase = (yPix1)*1.0 + (yPix2)* drawToFixedPointY + (yPix3); // here is the base line for Y
            float yposition_FIX = yPosY_pixel_lineBase * scaleFactorX;
            
            // prepare X position
            float xPosX_pixel_lineBaseFix =  (xPix1)* drawToFixedPointX + (xPix2)*Yinput+ (xPix3); // here is the base line for X
            float xposition_FIX  = xPosX_pixel_lineBaseFix * scaleFactorX;
            
            
            pathLine = [UIBezierPath bezierPath];
            [pathLine moveToPoint:CGPointMake( xposition_FIX, yposition_FIX )]; // move to base
            [pathLine addLineToPoint:CGPointMake( xposition, yposition  )  ]; // from base to cross
            
        }
        
        // now draw to the left or to the right
        
        
        
        
        
        if ([lineDirectionTO isEqualToString:@"r"]) {
            
            float xPosX_pixel_lineBaseRightX =  (xPix1)*lineBaseRightX + (xPix2)*Yinput+ (xPix3); // here is the base line for X
            float xposition_lineBaseRightX  = xPosX_pixel_lineBaseRightX * scaleFactorX;
            [pathLine addLineToPoint:CGPointMake( xposition_lineBaseRightX, yposition )]; // from cross  to chart edge
            
        }else{
            
            
            
            float xPosX_pixel_lineBaseLeftX =  (xPix1)*lineBaseLeftX + (xPix2)*Yinput+ (xPix3); // here is the base line for X
            float xposition_lineBaseLeftX  = xPosX_pixel_lineBaseLeftX * scaleFactorX;
            [pathLine addLineToPoint:CGPointMake( xposition_lineBaseLeftX, yposition )]; // from cross  to chart edge
        }
        
        
        
        
        
        
        
        
    }
    
    if (yToX == 1) {
        
        //NSLog(@"minResult %.0f ", minResult);
        //NSLog(@"maxResult %.0f ", maxResult);
        //NSLog(@"minInput %.0f ", minInput);
        //NSLog(@"maxInput %.0f ", maxInput);
        
        // check if base left in the lower x values
        if ( (xPix1)*minResult + (xPix2)*Yinput+ (xPix3)  < (xPix1)*maxResult + (xPix2)*Yinput+ (xPix3) ) {
            // xAxis is normal (left = low right = high)
            //NSLog(@"yToX *******  xAxis is normal  ");
            lineBaseLeftX =     minResult;
            lineBaseRightX =    maxResult;
        }else{
            //NSLog(@"yToX *******  xAxis reversed ");
            lineBaseLeftX =     maxResult;
            lineBaseRightX =    minResult;
        }
        
        // check if base top is higher than base bottom
        if ( (yPix1)*Xinput + (yPix2)*minInput + (yPix3)  > (yPix1)*Xinput + (yPix2)*maxInput + (yPix3) ) {
            // yAxis is normal (left = low right = high)
            //NSLog(@"yToX *******  yAxis is normal ");
            lineBaseBottomY =   minInput;
            lineBaseTopY =      maxInput;
        }else{
            //NSLog(@"yToX *******  yAxis reversed ");
            lineBaseBottomY =   maxInput;
            lineBaseTopY =      minInput;
        }
        
      
        
        if ([lineDirectionFrom isEqualToString:@"l"]) {
            // we need to draw from left to cross
            float xPosX_pixel_lineBaseLeftX =  (xPix1)*lineBaseLeftX + (xPix2)*Yinput+ (xPix3); // here is the base line for X
            float xposition_lineBaseLeftX  = xPosX_pixel_lineBaseLeftX * scaleFactorX;
            pathLine = [UIBezierPath bezierPath];
            [pathLine moveToPoint:CGPointMake( xposition_lineBaseLeftX, yposition )]; // move to base
            [pathLine addLineToPoint:CGPointMake( xposition, yposition  )  ]; // from base to cross
        }else{
            // we need to draw from right to cross
            float xPosX_pixel_lineBaseRightX =  (xPix1)*lineBaseRightX + (xPix2)*Yinput+ (xPix3); // here is the base line for X
            float xposition_lineBaseRightX  = xPosX_pixel_lineBaseRightX * scaleFactorX;
            pathLine = [UIBezierPath bezierPath];
            [pathLine moveToPoint:CGPointMake( xposition_lineBaseRightX, yposition )]; // move to base
            [pathLine addLineToPoint:CGPointMake( xposition, yposition  )  ]; // from base to cross
        }
        
        // now draw to the top or bottom
        if ([lineDirectionTO isEqualToString:@"b"]) {
            // draw from cross to bottom
            float yPosY_pixel_lineBase = (yPix1)*Xinput + (yPix2)*lineBaseBottomY + (yPix3); // here is the base line for Y
            float yposition_lineBase = yPosY_pixel_lineBase * scaleFactorX;
            [pathLine addLineToPoint:CGPointMake( xposition, yposition_lineBase )]; // from cross  to chart edge        
        }else if ([lineDirectionTO isEqualToString:@"H"]) {
            lineBaseBottomY = [[infoPartArray objectAtIndex:5] floatValue];            
            float xPosX_pixel_magic = [[infoPartArray objectAtIndex:6] floatValue];      
            float yPosY_pixel_lineBase = (yPix1)*Xinput + (yPix2)*lineBaseBottomY + (yPix3); // here is the base line for Y
            float yposition_lineBase = yPosY_pixel_lineBase * scaleFactorX;
            [pathLine addLineToPoint:CGPointMake( xposition + xPosX_pixel_magic, yposition_lineBase )]; // from cross  to chart edge             
           
            
        }else{
            // draw from cross to top
            float yPosY_pixel_lineBase = (yPix1)*Xinput + (yPix2)*lineBaseTopY + (yPix3); // here is the base line for Y            
            float yposition_lineBase = yPosY_pixel_lineBase * scaleFactorX;
            [pathLine addLineToPoint:CGPointMake( xposition, yposition_lineBase )]; // from cross  to chart edge
        }
    }
    
    markerPointX1 = xposition;
    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    lineLayer.path = [pathLine CGPath];
    lineLayer.strokeColor = [colorSet CGColor];
    lineLayer.lineWidth = 3.0;
    lineLayer.fillColor = [[UIColor clearColor] CGColor];
    [_viewLinesOnChart.layer addSublayer:lineLayer];
    
    // draw line ACweight
    float acWeightForLines = 0;
    if ([unitNameForComputation isEqualToString:@"kg"] & [ACweightUnitsUsed isEqualToString:@"lbs"]) {
        acWeightForLines = acWeight * 2.2046;
    }else{
        acWeightForLines = acWeight;
    }
    
    if ([unitResult isEqualToString:@"kg"] & [ACweightUnitsUsed isEqualToString:@"lbs"]) {               
        acWeightForLines = acWeightForLines / 2.2046;
    }
    
    if ([unitResult isEqualToString:@"lbs"] & [ACweightUnitsUsed isEqualToString:@"kg"]) {               
        acWeightForLines = acWeightForLines * 2.2046;
    }
    
    //NSLog(@"acWeightForLines  %.0f", acWeightForLines);
    //NSLog(@"minResult  %.0f", minResult);
    
    if (acWeightForLines < minResult) {
        acWeightForLines = minResult;
    }
    //NSLog(@"flagDrawACweightLines  %d", flagDrawACweightLines);
    
    if (flagDrawACweightLines == 1 ) {
        
       
        UIImageView *TOMimage =[[UIImageView alloc] initWithFrame:CGRectMake(-1500,0,47,25) ];
        TOMimage.image=[UIImage imageNamed:@"TOMsign.png"];
        TOMimage.tag = 9766;
        
        [_viewLinesOnChart addSubview:TOMimage];        
        
        if (flagOATisXaxis == 0) {
            
            //NSLog(@"unitResult  %@", unitResult );            
            //NSLog(@"acWeightForLines  %.0f", acWeightForLines );            
            //NSLog(@"unitNameForComputation  %@", unitNameForComputation);            
            //NSLog(@"ACweightUnitsUsed  %@", ACweightUnitsUsed);
            
            
            // we need to draw from top to bottom
            // this is the top
            float yPosY_pixel_lineBase = (yPix1)*Xinput + (yPix2)*lineBaseTopY + (yPix3);
            float yposition_lineBase = yPosY_pixel_lineBase * scaleFactorX;
            
            // this is the actual x position (ac weight)
            float xPosX_pixel_lineBaseRightX =  (xPix1)* (acWeightForLines)  + (xPix2)*Yinput+ (xPix3);
            
            
            float xposition_lineBaseRightX  = xPosX_pixel_lineBaseRightX * scaleFactorX;
         
            //NSLog(@"xposition_lineBaseRightX  %.0f", xposition_lineBaseRightX);
            
            // this is the bottom
            float yPosY_pixel_lineBase2 = (yPix1)*1.0 + (yPix2)* lineBaseBottomY + (yPix3);
            float yposition_FIX2 = yPosY_pixel_lineBase2 * scaleFactorX;
            
            
            pathLine = [UIBezierPath bezierPath];
            [pathLine moveToPoint:CGPointMake( xposition_lineBaseRightX, yposition_lineBase )];
            [pathLine addLineToPoint:CGPointMake( xposition_lineBaseRightX, yposition_FIX2  )  ];
            
            CAShapeLayer *lineLayer = [CAShapeLayer layer];
            lineLayer.path = [pathLine CGPath];
            lineLayer.strokeColor = [colorSetOrange CGColor];
            lineLayer.lineWidth = 3.0;
            lineLayer.fillColor = [[UIColor clearColor] CGColor];
            [_viewLinesOnChart.layer addSublayer:lineLayer];
            
            //UIImageView *TOMimage = [[UIImageView alloc] init];
            TOMimage = (UIImageView *)[ _viewLinesOnChart viewWithTag:  9766  ];
            [_viewLinesOnChart bringSubviewToFront:TOMimage];
            TOMimage.center = CGPointMake( xposition_lineBaseRightX, yposition_lineBase - 5 );

            

        }else{
            
            //NSLog(@"flagOATisXaxis %.0f", OAT);
            // we need to draw from left to right at ac weight
            // this is the top
            
            // this is the actual y position (ac weight)
            float yPosY_pixel_lineBase = (yPix1)*Xinput + (yPix2)*acWeightForLines + (yPix3);
            float yposition_lineBase = yPosY_pixel_lineBase * scaleFactorX;
            
            // this is left
            float xPosX_pixel_lineBaseLeftX =  (xPix1)*lineBaseLeftX + (xPix2)*Yinput+ (xPix3); // here is the base line for X
            float xposition_lineBaseLeftX  = xPosX_pixel_lineBaseLeftX * scaleFactorX;

            // this is right
            float xPosX_pixel_lineBaseRightX =  (xPix1)*lineBaseRightX + (xPix2)*Yinput+ (xPix3); // here is the base line for X
            float xposition_lineBaseRightX  = xPosX_pixel_lineBaseRightX * scaleFactorX;
            
            
            pathLine = [UIBezierPath bezierPath];
            [pathLine moveToPoint:CGPointMake( xposition_lineBaseLeftX, yposition_lineBase )];
            [pathLine addLineToPoint:CGPointMake( xposition_lineBaseRightX, yposition_lineBase  )  ];
            
            CAShapeLayer *lineLayer = [CAShapeLayer layer];
            lineLayer.path = [pathLine CGPath];
            lineLayer.strokeColor = [colorSetOrange CGColor];
            lineLayer.lineWidth = 3.0;
            lineLayer.fillColor = [[UIColor clearColor] CGColor];
            [_viewLinesOnChart.layer addSublayer:lineLayer];            
            
        }
        
        
    }

    
    
    return;
    
    
}


- (void) computeChartSizeInApp {
    
    if ([[infoArray objectAtIndex: 3  ] rangeOfString:@"FXX"].location != NSNotFound  || [[infoArray objectAtIndex: 3  ] rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound          ) {
        //NSLog(@"returning drawCrossesAndLines");
        return;
    }
    
    //NSLog(@"computeChartSizeInApp _masterViewCharts.frame.size.width %.0f ", _masterViewCharts.frame.size.width);
    
    float leftBorderForChartContainer = 0;
    
    flagChartsFitToScreenHeight = 1;
    
    float ratioChartSize = chartWidthPixel / chartHeightPixel;
    
    if (chartWidthPixel > chartHeightPixel) {
        
        //NSLog(@"chart is landscape");
        
        chartHeightInApp = _masterViewCharts.frame.size.height ;
        
        chartWidthInApp = _masterViewCharts.frame.size.height * ratioChartSize;
        
        //NSLog(@"chartHeightInApp %.0f ", chartHeightInApp);
        
        //NSLog(@"chartWidthInApp %.0f ", chartWidthInApp);
        
        
        leftBorderForChartContainer = 0;
        
    }else{
        
        //NSLog(@"chart is portrait");
        
        chartHeightInApp = _masterViewCharts.frame.size.height ;
        
        chartWidthInApp = _masterViewCharts.frame.size.height * ratioChartSize;
        
        leftBorderForChartContainer = (_masterViewCharts.frame.size.width - chartWidthInApp)/2;
        
    }
    
    
    float xCenterMasterViewChart = _masterViewCharts.frame.size.width/2 - leftBorderForChartContainer;
    
    float yCenterMasterViewChart = _masterViewCharts.frame.size.height + ( 2 * pinchScale -1);
    
    _viewChartContainer.frame = CGRectMake(0 , 0, _masterViewCharts.frame.size.width , _masterViewCharts.frame.size.height);
    
    
    
    //_viewChartsUniversal.frame = CGRectMake(0 + moveLeftRight +leftBorderForChartContainer - (xCenterMasterViewChart * (pinchScale-1) ) , 0 + moveupDown - (yCenterMasterViewChart * (pinchScale-1)), _viewChartsUniversal.frame.size.width , _viewChartsUniversal.frame.size.height);
    
    
    _viewChartsUniversal.frame = CGRectMake(0 + moveLeftRight +leftBorderForChartContainer - (xCenterMasterViewChart * (pinchScale-1) ) , 0 + moveupDown - (yCenterMasterViewChart * (pinchScale-1)), _masterViewCharts.frame.size.width , _masterViewCharts.frame.size.height);
    
}

- (void) setACSideViewImages {
    
    
    NSString *acTypeForImageName = @"C172";
    
    if (arrayFixedWingSetup.count > 2) {
        
        //NSLog(@"[arrayFixedWingSetup objectAtIndex:7] -%@-", [arrayFixedWingSetup objectAtIndex:7]);
        
        acTypeForImageName  = [arrayFixedWingSetup objectAtIndex:7];
        
    }else{
        if ([AC_Type rangeOfString:@"C172"].location != NSNotFound           ) {
               acTypeForImageName = @"C172";
           }
           if ([AC_Type rangeOfString:@"C182"].location != NSNotFound           ) {
               acTypeForImageName = @"C172";
           }
           if ([AC_Type rangeOfString:@"DA42"].location != NSNotFound           ) {
               acTypeForImageName = @"DA42";
           }
           
           
           if ([AC_Type rangeOfString:@"C208"].location != NSNotFound           ) {
               acTypeForImageName = @"C208";
           }
           
           if ([AC_Type rangeOfString:@"SR22"].location != NSNotFound           ) {
               acTypeForImageName = @"SR22";
           }
           if ([AC_Type rangeOfString:@"PA28"].location != NSNotFound           ) {
               acTypeForImageName = @"PA28";
           }
           if ([AC_Type rangeOfString:@"DA40"].location != NSNotFound           ) {
               acTypeForImageName = @"DA40";
           }
        
    }
 
   
    //adjust
        
    
    NSString *imageName = [[NSString alloc] initWithFormat:@"sideview_%@", acTypeForImageName ];
    UIImage *acImage = [UIImage imageNamed:imageName];
    
    [_symAC0 setImage:acImage];
    [_symAC1 setImage:acImage];
    [_symAC2 setImage:acImage];
    [_symAC0LD setImage:acImage];
    [_symAC1LD setImage:acImage];
    [_symAC2LD setImage:acImage];
    [_symACClimb1 setImage:acImage];
    [_symACClimb2 setImage:acImage];
    [_symACCruise setImage:acImage];
}


- (void) loadChartImage {
    
 
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  || [[infoArray objectAtIndex: 3  ] rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound          ) {
        //NSLog(@"returning drawCrossesAndLines");
        return;
    }
    
    //NSLog(@"loadChartImage chartImagesDictionary.count %d", chartImagesDictionary.count);

    
    if (chartImagesDictionary.count < 1) {
        chartImagesDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"chartImagesDictionary"] mutableCopy];
    }
    
    
    NSString *imageToLoad = [NSString stringWithFormat:@"image_%@", chartNameToLoad ];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    
    //NSLog(@"loadChartImage previousChartName %@", previousChartName);
    
    if ([previousChartName isEqualToString:imageToLoad]) {
        //NSLog(@"same image");
        return;
    }else{
       //NSLog(@"new image to load!  -%@-", imageToLoad);        
         previousChartName = imageToLoad;
        
        //Killer!
        //[_universalChartGraphic setImage: [UIImage imageWithData:[chartImagesDictionary objectForKey: imageToLoad] ]  ];
        [_universalChartGraphic.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines        
        for (UIView *subview in _universalChartGraphic.subviews) {
            [subview removeFromSuperview];
        }
        
        //double size to enhance resolution
        _universalChartGraphic.frame = CGRectMake(0, 0, _universalChartGraphic.frame.size.width * 2, _universalChartGraphic.frame.size.height * 2);        
        _universalChartGraphic.image = nil ;
        
        
        //[_universalChartGraphic setImage: [UIImage imageWithData:[chartImagesDictionary objectForKey: imageToLoad] ]  ];   
        
        NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:imageToLoad];
               UIImage *imageLoaded = [UIImage imageWithContentsOfFile:getImagePath];       
               [_universalChartGraphic setImage: imageLoaded  ];  
        
        
        
        
        CGRect rect = [_universalChartGraphic bounds];
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [_universalChartGraphic.layer renderInContext:context];
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        _universalChartGraphic.image = nil ; 
        UIGraphicsEndImageContext();      
        _universalChartGraphic.image = img;       
        _universalChartGraphic.frame = CGRectMake(0, 0, _universalChartGraphic.frame.size.width / 2, _universalChartGraphic.frame.size.height / 2);
        

    }
   
    
    
}


- (void) getInfoFileForThisPart {
    
    //NSLog(@"getInfoFileForThisPart");
    
    //NSLog(@"[infoPartArray objectAtIndex:10] %@", [infoPartArray objectAtIndex:10]); 
    
    // get info file for this part
    arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@", chartNameForThisInfoFile, infoPartNumber, @"infoFile" ];
    //NSLog(@"arrayKey %@", arrayKey); 
    infoPartArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
    
    //NSLog(@"infoPartArray %@", infoPartArray);
    
    if ([[infoPartArray objectAtIndex:4] isEqualToString:@"ClimbComp_FXX"] || [[infoPartArray objectAtIndex:4] isEqualToString:@"CruiseComp_FXX"]){
        //NSLog(@"[infoPartArray objectAtIndex:4]  %@", [infoPartArray objectAtIndex:4] );
        return;
    }
    
    if ([[infoPartArray objectAtIndex:10] isEqualToString:@"Y"] || [[infoPartArray objectAtIndex:10] isEqualToString:@"y"] ) { yToX = 1; }else{ yToX = 0; }
    
    flagYandXinputSpecialChart = 0;
    if ([[infoPartArray objectAtIndex:10] isEqualToString:@"YandX"] ) {
        yToX = 1;
        flagYandXinputSpecialChart = 1;           
    }
    
    
    if ([[infoPartArray objectAtIndex:10] isEqualToString:@"YandXMBB"] ) {
           yToX = 1;
           flagYandXinputSpecialChart = 2;
    }
    
    if ([[infoPartArray objectAtIndex:10] isEqualToString:@"YandXH145Hoist"] ) {
           yToX = 1;
           flagYandXinputSpecialChart = 3;
    }
    
    
    
    
    flagFindEnvelopeFromYandX = 0;
    if ([[infoPartArray objectAtIndex:10] isEqualToString:@"YandXforEnvelopes"] ) {
        yToX = 0;
        flagFindEnvelopeFromYandX = 1;  
        
    }
    
    flagAWHVdiagram = 0;
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"AWHVdiagram"] ) {
        yToX = 1;
        flagAWHVdiagram = 1;         
    }
   
    
    unitResult = [infoPartArray objectAtIndex:14];
    // get line base for X and Y (line base is the edge of the chart)
    minCurve =   [[infoPartArray objectAtIndex:15] floatValue];
    maxCurve =   [[infoPartArray objectAtIndex:16] floatValue];
    
    minInput =   [[infoPartArray objectAtIndex:17] floatValue];
    maxInput =   [[infoPartArray objectAtIndex:18] floatValue];
    minResult =  [[infoPartArray objectAtIndex:19] floatValue];
    
    
    //NSLog(@"minCurve %@", [infoPartArray objectAtIndex:15]);
    
    //NSLog(@"minCurve %.0f", minCurve);
    //NSLog(@"maxCurve %.0f", maxCurve);
    
    //NSLog(@"minInput %.0f", minInput);
    //NSLog(@"maxInput %.0f", maxInput);
    
    
    
    
    //NSLog(@"unitResult %@", unitResult);
    // check if max result contains text "External" or "hoist" etc
    // then take max value from them
    
    NSString *specialMaxResultString = [infoPartArray objectAtIndex:21];
    //NSLog(@"specialMaxResultString %@", specialMaxResultString);
    maxResult =  [[infoPartArray objectAtIndex:20] floatValue];    
    maxResultWithRestriction = maxResult;
    
    //NSLog(@"maxResultWithRestriction %f", maxResultWithRestriction);
    
   
    // check for "MAX" and 'external" then look for values after "@"
    if ([specialMaxResultString rangeOfString:@"limits"].location != NSNotFound ) {
        
        //NSLog(@"specialMaxResultString. %@", specialMaxResultString);
        //NSLog(@"externalLoadActivated. %d", externalLoadActivated);
        
        NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"@"];
        NSArray *components = [specialMaxResultString componentsSeparatedByCharactersInSet:charSet];
        
        NSString *str1;
        NSString *str2;
        NSString *str3;
        
        //NSLog(@"components %@", components); 
        //NSLog(@"components.count %lu", (unsigned long)components.count); 
        
        if (components.count>=2) {
            str1 = [components objectAtIndex:1]; // normal
        }
        if (components.count>=3) {
            str2 = [components objectAtIndex:2];// external
        }  
        if (components.count>=4) {
            str3 = [components objectAtIndex:3]; // hoist
        }else{
            str3 = str1;
        }
        
        // if no entry in str3, then there is no special restriction for hoist        
        //NSLog(@"externalLoadAttached %f", externalLoadAttached);    
        //NSLog(@"hoistLoadAttached %f", hoistLoadAttached);
        
       
        if (externalLoadAttached == 1) {            
            maxResultWithRestriction =   [str2 floatValue];
           //NSLog(@"1 maxResultWithRestriction  for external load %f", maxResultWithRestriction);
        }else if (hoistLoadAttached == 1) {
            maxResultWithRestriction =   [str3 floatValue];
            //NSLog(@"1 maxResultWithRestriction  for hoist load %f", maxResultWithRestriction);            
        }else{           
           maxResultWithRestriction =  [str1 floatValue];
           //NSLog(@"1 maxResultWithRestriction  no restriction %f", maxResultWithRestriction);  
        }
        
        
        
    }
    
    
    
    if ([specialMaxResultString rangeOfString:@"MAX"].location != NSNotFound || [specialMaxResultString rangeOfString:@"max"].location != NSNotFound) {
        
        if ([specialMaxResultString rangeOfString:@"external"].location != NSNotFound ) {
            
            if (externalLoadActivated == 1 || hoistActivated == 1) {
                // no limit
                //NSLog(@"1 no limit");
            }else{
                //NSLog(@"2 now limit");
                specialMaxResultString = [specialMaxResultString substringFromIndex:3];
                 //NSLog(@"specialMaxResultString %@", specialMaxResultString);
                
                float specialLimitation = [specialMaxResultString floatValue];
                maxResultWithRestriction =  specialLimitation;               
            }
        }else{
            //NSLog(@"3 no limit");
            specialMaxResultString = [specialMaxResultString substringFromIndex:3];
            float specialLimitation = [specialMaxResultString floatValue];
            maxResultWithRestriction =  specialLimitation;
        }
        //NSLog(@"maxResultWithRestriction %.0f", maxResultWithRestriction);
    }
    
 
    //NSLog(@"3maxResultWithRestriction %f", maxResultWithRestriction);
    
    
    // get additional values
    crossLineSequence =  [infoPartArray objectAtIndex:22];
    drawToFixedPointX =  [[infoPartArray objectAtIndex:5] floatValue];
    drawToFixedPointY =  [[infoPartArray objectAtIndex:6] floatValue];
    
    
    // check if part is a transfer value
    if ( [[infoPartArray objectAtIndex:13] floatValue] != 0) {
        factorForResult = [[infoPartArray objectAtIndex:13] floatValue];
    }else{
        factorForResult = 1;
    }
    
    
    if ( [[infoPartArray objectAtIndex:13] isEqualToString:@"TV"]) {
        flagThisPartResultContainsTransferValue = 1;
        
        //NSLog(@"contains transferVal  chart: %@ part %d  ", chartNameForThisInfoFile, partNumberToCompute);
    }else{
        flagThisPartResultContainsTransferValue = 0;
    }
    
    
    if ( ![[infoPartArray objectAtIndex:25] isEqualToString:@""]) {
        newWPDdataAvialable = 1;
    }else{
        newWPDdataAvialable = 0;
    }
    
    
    return;
    
    
    
    

    
}


- (void) getInputForCurveAndAxis {
    
    //NSLog(@"getInputForCurveAndAxis infoPartArray %@", infoPartArray);
    //NSLog(@"getInputForCurveAndAxis [infoPartArray objectAtIndex:5] %@", [infoPartArray objectAtIndex:5]);
    
  /*
   0	Category
   1	Manufacturer
   2	AC Type
   3	AC Variant
   4	Chart Name
   5	Number of Computation Parts
   6	Current Computation Part
   7	Unit Y (kg, lbs...
   8	Unit X (C, PA...
   9	Unit Curves (C, PA...
   10	Input Axis  (y To X)
   11	Input Source 
   12	Input From Chart
   13	Result
   14	Result Unit
   15	Min Value Curve
   16	Max Value Curve
   17	Min Input
   18	Max Input
   19	Min Result
   20	Max Result
   21	Date
   22	Initials (CrossLineSequence)
   23	chart width pixel
   24	chartt height pixel
   25	xPix1
   26	xPix2
   27	yPix1
   28	yPix2
   29	xPix3
   30	yPix3
   31	xLeftGC
   32	yBottomGC
   33	xRightGC
   34	yTopGC
   */
    
    // curve input
    
    //SLog(@"chartNameForComputation %@ %d",  chartNameForComputation, partNumberToCompute);
    
    //NSLog(@"[infoPartArray objectAtIndex:9 %@ %@ ",  [infoPartArray objectAtIndex:9], chartNameForThisInfoFile);
    
   
  
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"Fuel-Percent"]) {              
       
        givenCurveInputValue = fuelPercent ; 
        
    }
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"TV"]) {
               
        float transferVal  = [[transferValueDictionary objectForKey: [infoPartArray objectAtIndex:11] ] floatValue];
        //NSLog(@"loading key  %@ ", [infoPartArray objectAtIndex:11] );
        //NSLog(@"loading transferVal  from dictionary %.3f ", transferVal);
        givenCurveInputValue = transferVal ;  //we need a transfer value
        
    }
    
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"oneLine"]) {
        // curve needs zero
        givenCurveInputValue = 0;
        //NSLog(@"oneLine....");
    }
    
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"C"]) {
        // curve needs celsius
        givenCurveInputValue = OAT;  // curve // OAT = slider 2
    }
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"PA"]) {
        // curve needs celsius
        givenCurveInputValue = Hp;  // Pressure Alt
    }
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"ISAdiff"]) {
        // curve needs ISAdiff       
        givenCurveInputValue = ISADiff;  // Pressure Alt
        //NSLog(@"using ISADiff %.1f ",ISADiff);
       
    }
    
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"acWeight"]  || [[infoPartArray objectAtIndex:9] isEqualToString:@"kg"]   ) {
        // curve needs AC weight
        givenCurveInputValue = acWeight; // AC weight
        
        //NSLog(@"[givenCurveInputValue acWeight  %.0f ", acWeight);
        
        //NSLog(@"unitResult  %@ ", unitResult);
        //NSLog(@"ACweightUnitsUsed  %@ ", ACweightUnitsUsed);
        
        
        NSString *testString = [infoPartArray objectAtIndex:15];
        //NSLog(@"[infoPartArray objectAtIndex:15] %@ ", testString);
        //NSLog(@"[infoPartArray objectAtIndex:15] %.0f ", [testString floatValue]);
        if ([ testString  rangeOfString:@"<"].location != NSNotFound  ) {
            testString  = [ testString stringByReplacingOccurrencesOfString:@"<" withString:@""];
            givenCurveInputValue = [testString floatValue];
            //NSLog(@"givenCurveInputValue %.0f", givenCurveInputValue);
        }
    }
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"acWeightKG"]  || [[infoPartArray objectAtIndex:9] isEqualToString:@"acWeightkg"]   ) {
        // curve needs AC weight in kg!
                
        //Achtung: ACweightUnitsUsed sind immer nativ, also so wie aircraft units in excel/backend
              
        if ([ACweightUnitsUsed isEqualToString:@"lbs"]) {
            //need to convert
            givenCurveInputValue = acWeight / 2.2046; // AC weight in kg!
        }else{
            givenCurveInputValue = acWeight; // AC weight in kg!
        }        
        NSString *testString = [infoPartArray objectAtIndex:15];
        //NSLog(@"[infoPartArray objectAtIndex:15] %@ ", testString);
        //NSLog(@"[infoPartArray objectAtIndex:15] %.0f ", [testString floatValue]);
        if ([ testString  rangeOfString:@"<"].location != NSNotFound  ) {
            testString  = [ testString stringByReplacingOccurrencesOfString:@"<" withString:@""];
            givenCurveInputValue = [testString floatValue];
            //NSLog(@"givenCurveInputValue %.0f", givenCurveInputValue);
        }
    }
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:@"acWeightLBS"]  || [[infoPartArray objectAtIndex:9] isEqualToString:@"acWeightlbs"]   ) {
        // curve needs AC weight in klbs!
        
        //Achtung: ACweightUnitsUsed sind immer nativ, also so wie aircraft units in excel/backend
        
        if ([ACweightUnitsUsed isEqualToString:@"kg"]) {
            //need to convert
            givenCurveInputValue = acWeight * 2.2046; // AC weight in lbs
        }else{
            givenCurveInputValue = acWeight; // AC weight in lbs
        }        
        NSString *testString = [infoPartArray objectAtIndex:15];
        //NSLog(@"[infoPartArray objectAtIndex:15] %@ ", testString);
        //NSLog(@"[infoPartArray objectAtIndex:15] %.0f ", [testString floatValue]);
        if ([ testString  rangeOfString:@"<"].location != NSNotFound  ) {
            testString  = [ testString stringByReplacingOccurrencesOfString:@"<" withString:@""];
            givenCurveInputValue = [testString floatValue];
            //NSLog(@"givenCurveInputValue %.0f", givenCurveInputValue);
        }
    }
    
    
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"ktsWind"] == NSOrderedSame    ) {
        givenCurveInputValue = headWindKTS; // kts wind speed
        //NSLog(@"givenCurveInputValue %f ", givenCurveInputValue);
    }
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"WindKts"] == NSOrderedSame    ) {
        givenCurveInputValue = headWindKTS; // kts wind speed
    }
   
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"indexX"] == NSOrderedSame ) {
        // curve needs X input from first curve
        givenCurveInputValue = cross1ValueX; // X result from previous computation
    }
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"index"] == NSOrderedSame ) {
        // curve needs X input from first curve
        givenCurveInputValue = cross1ValueX; // X result from previous computation
    }
    
    
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"indexX2"] == NSOrderedSame ) {
        // curve needs X input from first curve
        givenCurveInputValue = cross2ValueX; // X result from previous computation
        //NSLog(@"givenCurveInputValue %f", givenCurveInputValue);
    }
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"indexX3"] == NSOrderedSame ) {
        // curve needs X input from first curve
        givenCurveInputValue = cross3ValueX; // X result from previous computation
    }
    
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"indexY"] == NSOrderedSame ) {
        // curve needs Y input from first curve
        givenCurveInputValue = cross1ValueY; // Y result from previous computation
    }
    
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"indexY2"] == NSOrderedSame ) {
        // curve needs Y input from second curve
        givenCurveInputValue = cross2ValueY; // Y result from previous computation
    }
    
    if( [ [infoPartArray objectAtIndex:9] caseInsensitiveCompare:@"indexY3"] == NSOrderedSame ) {
        // curve needs Y input from second curve
        givenCurveInputValue = cross3ValueY; // Y result from previous computation
        
    }
    
    //NSLog(@"headWindKTS %f", headWindKTS); 
    //NSLog(@"IAS %f", IAS);
    //NSLog(@"RATINGINDEX %f", RATINGINDEX);
    //NSLog(@"PROPRPM %f", PROPRPM);
    
    //NSLog(@"9  [infoPartArray objectAtIndex:9] %@", [infoPartArray objectAtIndex:9]);
    //NSLog(@"9  nameVariSlider1                 %@", nameVariSlider1);
    
    
    
    if ([[infoPartArray objectAtIndex:9] isEqualToString:nameVariSlider1]) {
        givenCurveInputValue = headWindKTS;            
    }
    if ([[infoPartArray objectAtIndex:9] isEqualToString:nameVariSlider2]) {
        givenCurveInputValue = IAS;            
    }
    if ([[infoPartArray objectAtIndex:9] isEqualToString:nameVariSlider3]) {
        givenCurveInputValue = RATINGINDEX;            
    }
    if ([[infoPartArray objectAtIndex:9] isEqualToString:nameVariSlider4]) {
        givenCurveInputValue = PROPRPM;            
    }
    
    //NSLog(@"9  givenCurveInputValue            %f", givenCurveInputValue);
    
    
    //NSLog(@"givenCurveInputValue %.0f   ", givenCurveInputValue);
    //NSLog(@"cross1ValueY %.0f   ", cross1ValueY);
    //NSLog(@"cross2ValueY %.0f   ", cross2ValueY);
    //NSLog(@"cross3ValueY %.0f   ", cross3ValueY);
    
    
    
    
    // get input for axis
    // if we go from X to Y, then the unit X is the input data
    // if we go from Y to X, then the unit Y is the input data
    
    //NSLog(@"yToX %d ", yToX);
    
    
     flagOATisXaxis = 0;
    
    
    //NSLog(@"[infoPartArray objectAtIndex:8]  %@",  [infoPartArray objectAtIndex:8] );
    
    if (yToX == 0) {
        // if we go X to Y
        
        
        //NSLog(@"[infoPartArray objectAtIndex:8] %@", [infoPartArray objectAtIndex:8]);        
        //NSLog(@"[infoPartArray objectAtIndex:8  %@ ---- %@ ",  [infoPartArray objectAtIndex:8], chartNameForThisInfoFile);
        //NSLog(@"[infoPartArray objectAtIndex:11 %@ ---- %@ ",  [infoPartArray objectAtIndex:11], chartNameForThisInfoFile);
                  
        
          if ([[infoPartArray objectAtIndex:8] isEqualToString:@"TV"]) {
              
              //NSLog(@"transferValueDictionary %@ ",  transferValueDictionary);                     
              float transferVal  = [[transferValueDictionary objectForKey: [infoPartArray objectAtIndex:11] ] floatValue];
              //NSLog(@"loading key  %@ ", [infoPartArray objectAtIndex:11] );
              //NSLog(@"loading transferVal  from dictionary %.3f ", transferVal);
              givenAxisInputValue = transferVal ;  //we need a transfer value
              
          }
        
        
        
        if ([ [infoPartArray objectAtIndex:8]  rangeOfString:@"fix"].location != NSNotFound      ) {
            NSString *subString =  [infoPartArray objectAtIndex:8];
            subString = [subString substringFromIndex:3];
            float subStringValue = [subString floatValue];
            givenAxisInputValue = subStringValue; // input is a fixed value (see BAZL Velocity part 4
            //NSLog(@"subStringValue %.0f", subStringValue);
            
        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"percentTorque1"] == NSOrderedSame ) {
            // axis needs percentTorque1
            givenAxisInputValue = _sliderEngineTorque1.value; // percentTorque for engine 1
        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"percentTorque2"] == NSOrderedSame ) {
            // axis needs percentTorque1
            givenAxisInputValue = _sliderEngineTorque2.value; // percentTorque for engine 2
        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"acWeight"] == NSOrderedSame ) {
            // axis needs AC weight
            givenAxisInputValue = acWeight; // AC weight
        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"acWeightKG"] == NSOrderedSame ) {
            // axis needs AC weight
            givenAxisInputValue = acWeight; // AC weight
            
            if ([ACweightUnitsUsed isEqualToString:@"lbs"]) {
                //need to convert
                givenCurveInputValue = acWeight / 2.2046; // AC weight in kg!
            }else{
                givenCurveInputValue = acWeight; // AC weight in kg!
            }
            
        }
        
       
        
        
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"acLandingWeight"] == NSOrderedSame ) {
            // axis needs AC weight
            givenAxisInputValue = acLandingWeight; // AC weight
            //NSLog(@"8 needs acLandingWeight weight") ;            
        }
        
        
        
        // DHC 6
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"IAS"] == NSOrderedSame ) {
            givenAxisInputValue = IAS;
        }
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"RATINGINDEX"] == NSOrderedSame ) {
            givenAxisInputValue = RATINGINDEX;
        }
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"PROPRPM"] == NSOrderedSame ) {
            givenAxisInputValue = PROPRPM;
        }
        
       
        
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"ktsWind"] == NSOrderedSame ) {
            givenAxisInputValue = headWindKTS; // kts wind speed
        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"WindKts"] == NSOrderedSame ) {
            givenAxisInputValue = headWindKTS; // kts wind speed
        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"ktsWindRef"] == NSOrderedSame ) {
            givenAxisInputValue = headWindKTS; // kts wind speed
            
            //NSLog(@"ktsWindRef ");
            
        }
        
        if ([[infoPartArray objectAtIndex:8] isEqualToString:@"PA"]) {
            // inout is PA
            givenAxisInputValue = Hp; // PA
        }
        
        
        if ([[infoPartArray objectAtIndex:8] isEqualToString:@"C"] || [[infoPartArray objectAtIndex:8] isEqualToString:@"OAT"] ) {
            // inout is OAT
            givenAxisInputValue = OAT;  // curve // OAT
            flagOATisXaxis = 1;
             //NSLog(@"3 yToX %d ", yToX);
        }
        
        
       
        
        
        if ([ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"indexX"] == NSOrderedSame ) {
            // inout is PA
            givenAxisInputValue = resultComputation;  // result from previous chart

        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"indexX2"] == NSOrderedSame ) {
            givenAxisInputValue = cross2ValueX; // result from second chart
            //NSLog(@"taking result from second chart X  %.0f", givenAxisInputValue );
        }
        
        if( [ [infoPartArray objectAtIndex:8] caseInsensitiveCompare:@"indexX3"] == NSOrderedSame ) {
            givenAxisInputValue = cross3ValueX; // result from second chart
            //NSLog(@"taking result from third chart X  %.0f", givenAxisInputValue );
        }
        
        
       
        
        //NSLog(@"headWindKTS %f", headWindKTS); 
        //NSLog(@"IAS %f", IAS);
        //NSLog(@"RATINGINDEX %f", RATINGINDEX);
        //NSLog(@"PROPRPM %f", PROPRPM);
        if ([[infoPartArray objectAtIndex:8] isEqualToString:nameVariSlider1]) {
            givenAxisInputValue = headWindKTS;            
        }
        if ([[infoPartArray objectAtIndex:8] isEqualToString:nameVariSlider2]) {
            givenAxisInputValue = IAS;            
        }
        if ([[infoPartArray objectAtIndex:8] isEqualToString:nameVariSlider3]) {
            givenAxisInputValue = RATINGINDEX;            
        }
        if ([[infoPartArray objectAtIndex:8] isEqualToString:nameVariSlider4]) {
            givenAxisInputValue = PROPRPM;            
        }
        
        
        //NSLog(@"1 givenAxisInputValue = %f ", givenAxisInputValue );
        
    }else{
        
        
        //NSLog(@"case 2");
        
        //NSLog(@"[infoPartArray objectAtIndex:7] %@", [infoPartArray objectAtIndex:7]);
        
        // if we go Y to X
        
       
        if ([[infoPartArray objectAtIndex:7] isEqualToString:@"TV"]) {
            
            // get transfer value
            
            float transferVal  = [[transferValueDictionary objectForKey: [infoPartArray objectAtIndex:11] ] floatValue];
            
            
            givenAxisInputValue = transferVal;
            
            //NSLog(@"2 is TV so .... givenCurveInputValue %f ", transferVal);
        }
        
        
        
        
        if ([[infoPartArray objectAtIndex:7] isEqualToString:@"acWeight"]  || [[infoPartArray objectAtIndex:7] isEqualToString:@"kg"]   || [[infoPartArray objectAtIndex:7] isEqualToString:@"acWeightKG"]   ) {
            // axis needs AC weight
            givenAxisInputValue = acWeight; // AC weight
            //NSLog(@"[************* Yes, we need AC weight");
        }
        
        if ([[infoPartArray objectAtIndex:7] isEqualToString:@"acWgtPenalty"]    ) {
            // axis needs AC weight
            givenAxisInputValue = unchangedACWeight - penaltyWeight; // AC weight
            //NSLog(@"acWgtPenalty ************* using penalty for chart %@", [infoPartArray objectAtIndex:4] );
            //NSLog(@"acWeight %.0f", acWeight );
            //NSLog(@"givenAxisInputValue %.0f", givenAxisInputValue );
        }
        
        
        
       
        
        if( [ [infoPartArray objectAtIndex:7] caseInsensitiveCompare:@"index"] == NSOrderedSame ) {
            givenAxisInputValue = resultComputation; // result from previous chart
        }
        if( [ [infoPartArray objectAtIndex:7] caseInsensitiveCompare:@"indexX"] == NSOrderedSame ) {
            givenAxisInputValue = resultComputation; // result from previous chart
        }
        
        if( [ [infoPartArray objectAtIndex:7] caseInsensitiveCompare:@"indexX2"] == NSOrderedSame ) {           
            givenAxisInputValue = cross2ValueX; // result from second chart
            //NSLog(@"taking result from second chart X  %.0f", givenAxisInputValue );
        }
        if( [ [infoPartArray objectAtIndex:7] caseInsensitiveCompare:@"indexX3"] == NSOrderedSame ) {           
            givenAxisInputValue = cross3ValueX; // result from second chart
            //NSLog(@"taking result from third chart X  %.0f", givenAxisInputValue );
        }
        
        
        if( [ [infoPartArray objectAtIndex:7] caseInsensitiveCompare:@"indexY"] == NSOrderedSame ) {
             givenAxisInputValue = resultComputation; // result from previous chart
        }
        if( [ [infoPartArray objectAtIndex:7] caseInsensitiveCompare:@"indexY2"] == NSOrderedSame ) {
            givenAxisInputValue = cross2ValueY; // result from second chart
            //NSLog(@"taking result from second chart Y  %.0f", cross2ValueY );
        }
        if( [ [infoPartArray objectAtIndex:7] caseInsensitiveCompare:@"indexY3"] == NSOrderedSame ) {
            givenAxisInputValue = cross3ValueY; // result from second chart
            ///NSLog(@"taking result from third chart Y  %.0f", cross3ValueY );
            //NSLog(@"cross3ValueY %f", cross3ValueY); 
        }
        
       
        
        
        
        if ([[infoPartArray objectAtIndex:7] isEqualToString:@"ktsWind"]) {
            
            givenAxisInputValue = headWindKTS; // kts wind speed
            
            //NSLog(@"givenAxisInputValue = _slider4.value;; // kts wind speed ");
        }
        
        if ([[infoPartArray objectAtIndex:7] isEqualToString:@"WindKts"]) {
            
            givenAxisInputValue = headWindKTS; // kts wind speed
            
            //NSLog(@"givenAxisInputValue = _slider4.value;; // kts wind speed ");
        }
        
        
        
        
        
        if ([[infoPartArray objectAtIndex:7] isEqualToString:@"PA"]) {
            
            givenAxisInputValue = Hp; // PA = slider 1
        }
        
        
        if ([[infoPartArray objectAtIndex:7] isEqualToString:@"C"]  || [[infoPartArray objectAtIndex:7] isEqualToString:@"OAT"] ) {
            // inout is OAT
            givenAxisInputValue = OAT;  // curve // OAT
            
         }
        
        
        //NSLog(@"headWindKTS %f", headWindKTS); 
        //NSLog(@"IAS %f", IAS);
        //NSLog(@"RATINGINDEX %f", RATINGINDEX);
        //NSLog(@"PROPRPM %f", PROPRPM);
        
        //NSLog(@"nameVariSlider1 %@", nameVariSlider1); 
        
        //NSLog(@"[infoPartArray objectAtIndex:7] %@", [infoPartArray objectAtIndex:7]); 
        
        
        if ([[infoPartArray objectAtIndex:7] isEqualToString:nameVariSlider1]) {
            givenAxisInputValue = headWindKTS;            
        }
        if ([[infoPartArray objectAtIndex:7] isEqualToString:nameVariSlider2]) {
            givenAxisInputValue = IAS;            
        }
        if ([[infoPartArray objectAtIndex:7] isEqualToString:nameVariSlider3]) {
            givenAxisInputValue = RATINGINDEX;            
        }
        if ([[infoPartArray objectAtIndex:7] isEqualToString:nameVariSlider4]) {
            givenAxisInputValue = PROPRPM;            
        }
        
        
        
        
        
        
    }
    
    
   
    //NSLog(@"2 givenAxisInputValue = %f ", givenAxisInputValue );
    
    //NSLog(@"givenCurveInputValue = %f ", givenCurveInputValue );
    
   
    
   
    
    return;
    
    
    
    
    
    
    
    
}

- (void) checkInputDataRange {
   
    //NSLog(@"chartNameForThisInfoFile  %@" , chartNameForThisInfoFile);
    //NSLog(@"1 givenCurveInputValue  %.0f" , givenCurveInputValue);    
    //NSLog(@"infoPartArray 15 %@ ", [infoPartArray objectAtIndex:15]);
    
    //NSLog(@"partNumberToCompute %d", partNumberToCompute);
    
    flagInputDataOutOfRange = 0;

    if (givenCurveInputValue < minCurve) {       
        givenCurveInputValue = minCurve;  flagInputDataOutOfRange = 1;       
        //NSLog(@"1 range");
        if ([[infoPartArray objectAtIndex:15] rangeOfString:@"min"].location != NSNotFound  ) {            
            //NSLog(@"exception if min is entered ");
            flagInputDataOutOfRange = 0;
        }
    }
    
    
  
    if (givenCurveInputValue > maxCurve) {
      //NSLog(@"2 range");
        givenCurveInputValue = maxCurve;  flagInputDataOutOfRange = 2;
    }
    
    
    if (givenAxisInputValue < minInput) {
        //NSLog(@"3 range");
        givenAxisInputValue = minInput;  flagInputDataOutOfRange = 3;
        if ([[infoPartArray objectAtIndex:17] rangeOfString:@"min"].location != NSNotFound  ) {          
            //NSLog(@"exception if min is entered ");
            flagInputDataOutOfRange = 0;
        }
    }
    
    if (givenAxisInputValue > maxInput) {
    //NSLog(@"4 range");
        givenAxisInputValue = maxInput;   flagInputDataOutOfRange = 4;        
        //NSLog(@"flagInputDataOutOfRange  %d" , flagInputDataOutOfRange);
        //NSLog(@"flagCeilingComputation %d ", flagCeilingComputation);
        //NSLog(@"maxInput %f ", maxInput);        
        if (flagCeilingComputation == 1) {
            //NSLog(@"5 range");
            flagInputDataOutOfRange = 0;
        }
    }
    
     if ([[infoPartArray objectAtIndex:13] rangeOfString:@"noRangeLimit"].location != NSNotFound  ) {  
        //NSLog(@"6 range");
          flagInputDataOutOfRange = 0;
     }
    
    if ([[infoPartArray objectAtIndex:10] isEqualToString:@"YandXMBB"] ) {
        if (partNumberToCompute == 5) {
             flagInputDataOutOfRange = 0;
        }
       
    }
    
    if ([[infoPartArray objectAtIndex:10] isEqualToString:@"YandXH145Hoist"] ) {
        flagInputDataOutOfRange = 0;
       
    }
    
    //NSLog(@"flagInputDataOutOfRange %d", flagInputDataOutOfRange);
   
    return;
    
    
    
}







- (void) calcComputation {
    
    
    arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@", chartNameForThisInfoFile, partNumberToCompute, @"curves" ];
    availableCurvesArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
    
    //NSLog(@"availableCurvesArray %@ ", availableCurvesArray);
    //NSLog(@"partNumberToCompute %d ", partNumberToCompute);
    //givenCurveInputValue = 70;
    //givenAxisInputValue = 2500;
    
    
    
    if (flagCeilingComputation == 2) {
        //NSLog(@"eigentlich ceilingInputYAxis%.1f ", ceilingInputYAxis);        
        //NSLog(@"eigentlich ceilingInputCurve %.1f ", ceilingInputCurve);
        givenCurveInputValue = ceilingInputCurve;
        givenAxisInputValue = ceilingInputYAxis;
    }
    
   
    
    //NSLog(@"givenCurveInputValue %.1f ", givenCurveInputValue);
    //NSLog(@"givenAxisInputValue %.1f ", givenAxisInputValue);
    //if (nChart == 0 & partNumberToCompute == 3) {
    //NSLog(@"availableCurvesArray %@ ", availableCurvesArray);
    //}
    
    //NSLog(@"availableCurvesArray %@ ", availableCurvesArray);
    
    int foundAvailableCurve = 0, availableCurve = 0, availableAxis = 0; float resultY1 = 0, resultY2 = 0, curveVal1 = 0, curveVal2 = 0;;
    resultComputation = 0;
    
    // begin search for given value in curve array (i.e. is -25 in array -40, -30, -20, 10 ...
    for(availableCurve=0; availableCurve<availableCurvesArray.count-1; availableCurve++) {
        
        // check if given value is in between array values
        //NSLog(@"givenCurveInputValue %.0f ", givenCurveInputValue);
        //NSLog(@"givenAxisInputValue %.0f ", givenAxisInputValue);
        //NSLog(@"[availableCurvesArray objectAtIndex:availableCurve] floatValue] %.0f ", [[availableCurvesArray objectAtIndex:availableCurve] floatValue]);
        //NSLog(@"[availableCurvesArray objectAtIndex:availableCurve+1] floatValue] %.0f ", [[availableCurvesArray objectAtIndex:availableCurve+1] floatValue]);
        
        if (givenCurveInputValue >=  [[availableCurvesArray objectAtIndex:availableCurve] floatValue] &  givenCurveInputValue <=  [[availableCurvesArray objectAtIndex:availableCurve+1] floatValue]   ) {
            foundAvailableCurve = 1; break;
        }else if (givenCurveInputValue <=  [[availableCurvesArray objectAtIndex:availableCurve] floatValue] &  givenCurveInputValue >=  [[availableCurvesArray objectAtIndex:availableCurve+1] floatValue] ){
            foundAvailableCurve = 1; break;
        }
    }
    if (foundAvailableCurve == 1) {
        
        curveVal1 = [[availableCurvesArray objectAtIndex:availableCurve] floatValue];
        curveVal2 = [[availableCurvesArray objectAtIndex:availableCurve+1] floatValue];
        /*
         if (nChart == 0 & partNumberToCompute == 3) {
         //NSLog(@"OK found availableCurve between %.1f and %.1f ", curveVal1, curveVal2 );
         //NSLog(@"OK curve index found between %d and %d ", availableCurve+1, availableCurve+2 );
         }
         */
        
    }else{
        //NSLog(@"foundAvailableCurve  0");
        /*
         if (nChart == 2 & partNumberToCompute == 1) {
         //NSLog(@"1 !!!! %@  part %d  no available curve", chartNameForThisInfoFile, partNumberToCompute);        }
         */
        
        return;
        
    }
    
    
    // ****************************************************************************************************************************
    // X ans Y axis from first set
    
    
    NSArray* curveValuesX1;
    NSArray* curveValuesY1;
    
    //NSLog(@"yToX %d", yToX);
    
    if (yToX == 0) {
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@",  chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve], @"xAxis" ];
        curveValuesX1 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        //NSLog(@"arrayKey %@ ", arrayKey );
        //NSLog(@"curveValuesX1 %@ ", curveValuesX1 );
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@", chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve], @"yAxis" ];
        curveValuesY1 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        //NSLog(@"curveValuesY1 %@ ", curveValuesY1 );
        
    }else{
        // reverse axis
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@",  chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve], @"yAxis" ];
        //NSLog(@"reversed arrayKey x %@ ", arrayKey );
        
        curveValuesX1 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        //NSLog(@"reversed curveValuesX1 %@ ", curveValuesX1 );
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@",  chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve], @"xAxis" ];
        //NSLog(@"reversed arrayKey y %@ ", arrayKey );
        curveValuesY1 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        //NSLog(@"reversed curveValuesY1 %@ ", curveValuesY1 );
    }
    
    
    //NSLog(@" curveValuesX1 %@ ", curveValuesX1 );
    //NSLog(@" curveValuesY1 %@ ", curveValuesY1 );
    
    
    /*
     if (nChart == 2 & partNumberToCompute == 1) {
     
     //NSLog(@" curveValuesX1 %@ ", curveValuesX1 );
     //NSLog(@" curveValuesY1 %@ ", curveValuesY1 );
     }
     */
    
    foundAvailableCurve = 0;
    float foundavailableAxis = 0;    
    
    
    
    for(availableAxis=0; availableAxis<curveValuesX1.count; availableAxis++) {
        
        //NSLog(@"givenAxisInputValue %.0f ", givenAxisInputValue);        
        // check if given value is in between array values
        /*
         if (nChart == 2 & partNumberToCompute == 1) {
         //NSLog(@"givenAxisInputValue %.0f ", givenAxisInputValue);
         //NSLog(@"[[curveValuesX1 objectAtIndex:availableAxis] floatValue] %.0f ", [[curveValuesX1 objectAtIndex:availableAxis] floatValue]);
         //NSLog(@"[[curveValuesX1 objectAtIndex:availableAxis] floatValue+1] %.0f ", [[curveValuesX1 objectAtIndex:availableAxis+1] floatValue]);
         }
         */        
        //NSLog(@"curveValuesX1 %lu", (unsigned long)curveValuesX1.count);
        //NSLog(@"availableAxis %d", availableAxis);
        
        
        if (availableAxis+1 >= curveValuesX1.count ) {              
            computationErrorDisplay = [[NSString alloc] initWithFormat:@"Error C1-P%d",  partNumberToCompute ];
            NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@ in Chart: %@%@%d  ...",  computationErrorDisplay, chartNameForThisInfoFile, @", in part: ", partNumberToCompute ];
            computationErrorMessage = [computationErrorMessage stringByAppendingString:errorMsg];           
            //NSLog(@"!!! computationErrorMessage:  %@", computationErrorMessage);
            return;
        }
        
        
        if (givenAxisInputValue >=  [[curveValuesX1 objectAtIndex:availableAxis] floatValue] &  givenAxisInputValue <=  [[curveValuesX1 objectAtIndex:availableAxis+1] floatValue]   ) {
            foundavailableAxis = 1; break;
        }else if (givenAxisInputValue <=  [[curveValuesX1 objectAtIndex:availableAxis] floatValue] &  givenAxisInputValue >=  [[curveValuesX1 objectAtIndex:availableAxis+1] floatValue] ){
            foundavailableAxis = 1; break;
        }
        
    }
    
    
    if (foundavailableAxis == 1) {
        
        //NSLog(@"foundavailableAxis  1");
        
        float x1 = [[curveValuesX1 objectAtIndex:availableAxis] floatValue];
        float x2 = [[curveValuesX1 objectAtIndex:availableAxis+1] floatValue];        
        float y1 = [[curveValuesY1 objectAtIndex:availableAxis] floatValue];
        float y2 = [[curveValuesY1 objectAtIndex:availableAxis+1] floatValue];
        
        resultY1 = y1  + ( (y2-y1) / (x2-x1) * (givenAxisInputValue - x1));
        
        
    }else{           
        //NSLog(@"foundavailableAxis  0");        
        //NSLog(@"2 !!!! %@  part %d  no available axis data", chartNameForThisInfoFile, partNumberToCompute);        
        //NSLog(@"givenCurveInputValue %.0f ", givenCurveInputValue);        
        //NSLog(@"givenAxisInputValue %.0f ", givenAxisInputValue);        
        return;
    }
    
    
    
    
    // ****************************************************************************************************************************
    // X ans Y axis from second set
    
    NSArray* curveValuesX2;
    NSArray* curveValuesY2;
    
    if (yToX == 0) {
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@", chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve+1], @"xAxis" ];
        curveValuesX2 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        //NSLog(@"curveValuesX2 %@ ", curveValuesX2 );
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@",  chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve+1], @"yAxis" ];
        curveValuesY2 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        //NSLog(@"curveValuesY2 %@ ", curveValuesY2 );
        
        
    }else{
        // reverse axis
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@",  chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve+1], @"yAxis" ];
        curveValuesX2 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        //NSLog(@"reversed arrayKey %@ ", arrayKey );
        //NSLog(@"reversed curveValuesX2 %@ ", curveValuesX2 );
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@", chartNameForThisInfoFile, partNumberToCompute, [availableCurvesArray objectAtIndex:availableCurve+1], @"xAxis" ];
        curveValuesY2 = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        
        //NSLog(@"reversed arrayKey %@ ", arrayKey );
        //NSLog(@"reversed curveValuesY2 %@ ", curveValuesY2 );
        
        
        
    }
    
    /*
     
     if (nChart == 2 & partNumberToCompute == 1) {
     
     //NSLog(@"curveValuesX2 %@ ", curveValuesX2 );
     //NSLog(@"curveValuesY2 %@ ", curveValuesY2 );
     }
     */
    
    
    
    foundAvailableCurve = 0;
    foundavailableAxis = 0;
    
    //NSLog(@"[curveValuesX2 %@", curveValuesX2);
    
    //NSLog(@"curveValuesX2.count %lu " , (unsigned long)curveValuesX2.count);
    
    
    for(availableAxis=0; availableAxis < curveValuesX2.count; availableAxis++) {
        
        //NSLog(@"availableAxis %d " , availableAxis);        
        //NSLog(@"[givenAxisInputValue %f " , givenAxisInputValue);        
        //NSLog(@"[curveValuesX2 objectAtIndex:availableAxis] floatValue]  %f ", [[curveValuesX2 objectAtIndex:availableAxis] floatValue] );        
        //NSLog(@"[[curveValuesX2 objectAtIndex:availableAxis+1] floatValue]   %f ",[[curveValuesX2 objectAtIndex:availableAxis+1] floatValue]  );
        
        
        if (availableAxis+1 >= curveValuesX2.count ) {              
            computationErrorDisplay = [[NSString alloc] initWithFormat:@"Error C2-P%d",  partNumberToCompute ];
            NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@ in Chart: %@%@%d  ...",  computationErrorDisplay, chartNameForThisInfoFile, @", in part: ", partNumberToCompute ];
            computationErrorMessage = [computationErrorMessage stringByAppendingString:errorMsg];           
            //NSLog(@"!!! computationErrorMessage:  %@", computationErrorMessage);
            return;
        }
        
        
        
        // check if given value is in between array values
        if (givenAxisInputValue >=  [[curveValuesX2 objectAtIndex:availableAxis] floatValue] &  givenAxisInputValue <=  [[curveValuesX2 objectAtIndex:availableAxis+1] floatValue]   ) {
            foundavailableAxis = 1;
            //NSLog(@"> < foundavailableAxis ");
            break;
        }else if (givenAxisInputValue <=  [[curveValuesX2 objectAtIndex:availableAxis] floatValue] &  givenAxisInputValue >=  [[curveValuesX2 objectAtIndex:availableAxis+1] floatValue] ){
            foundavailableAxis = 1;
            //NSLog(@"< > foundavailableAxis ");
            break;
        }
    }
    
    
    if (foundavailableAxis == 1) {
        
        //NSLog(@"2 foundavailableAxis ");
        
        float x1 = [[curveValuesX2 objectAtIndex:availableAxis] floatValue];
        float x2 = [[curveValuesX2 objectAtIndex:availableAxis+1] floatValue];
        
        float y1 = [[curveValuesY2 objectAtIndex:availableAxis] floatValue];
        float y2 = [[curveValuesY2 objectAtIndex:availableAxis+1] floatValue];
        
        //NSLog(@"X axis data x %.3f y %.3f ", x1, x2 );
        resultY2 = y1  + ( (y2-y1) / (x2-x1) * (givenAxisInputValue - x1));
        //NSLog(@"resultY2 %.2f ", resultY2);        
        
        /*
         if (nChart == 2 & partNumberToCompute == 1) {         
         //NSLog(@"X axis data x %.3f y %.3f ", x1, x2 );
         //NSLog(@"resultY2 %.2f ", resultY2);
         }
         */
        
    }else{        
        //NSLog(@"3  NO foundavailableAxis ");
        //NSLog(@"curveValuesX2 %@", curveV"exaluesX2);
        //NSLog(@"3 !!!! %@  part %d  no available axis data", chartNameForThisInfoFile, partNumberToCompute);        
        return;
    }
    
    // interpolate for curve
    resultComputation = resultY1  + ( (resultY2-resultY1) / (curveVal2 - curveVal1) * (givenCurveInputValue - curveVal1));
    
    
    //NSLog(@"givenCurveInputValue %.3f ", givenCurveInputValue);    
    //NSLog(@"resultY2 %.3f ", resultY2);
    //NSLog(@"resultY1 %.3f ", resultY1);    
    //NSLog(@"curveVal2 %.3f ", curveVal2);
    //NSLog(@"curveVal1 %.3f ", curveVal1);
    //NSLog(@"resultComputation %.3f ", resultComputation);
    
    
}

- (void) limitResultValues {
    
    
    // limit the result values
    
    flagOutputDataOutOfRange = 0;
    
    
    if (resultComputation < minResult) {
        resultComputation = minResult; flagOutputDataOutOfRange = 1;
    }
    
    if (resultComputation > maxResultWithRestriction) {
        resultComputation = maxResultWithRestriction; flagOutputDataOutOfRange = 2;
    }
    
    if (flagOutputDataOutOfRange > 0) {
        //NSLog(@"flagOutputDataOutOfRange %@ %d ", chartNameForThisInfoFile, flagOutputDataOutOfRange);
    }
    
    
    //NSLog(@"partNumberToCompute %d", partNumberToCompute);
    
    if (partNumberToCompute == 1) {
        if (yToX == 0) { // wenn X to Y, then cross1ValueY = resultComputation;
            cross1ValueX = givenAxisInputValue;
            cross1ValueY = resultComputation;
        }else{
            cross1ValueX = resultComputation;
            cross1ValueY = givenAxisInputValue;
        }
        
        
    }
    
    
    if (partNumberToCompute == 2) {
        if (yToX == 0) { // wenn X to Y, then cross1ValueY = resultComputation;
            cross2ValueX = givenAxisInputValue;
            cross2ValueY = resultComputation;
            
            //NSLog(@"1 setting cross2ValueX %f", cross2ValueX);
                  
        }else{
            cross2ValueX = resultComputation;
            cross2ValueY = givenAxisInputValue;
            
            //NSLog(@"2 setting cross2ValueX %f", cross2ValueX);
        }
        
    }
    
    if (partNumberToCompute == 3) {
        if (yToX == 0) { // wenn X to Y, then cross1ValueY = resultComputation;
            cross3ValueX = givenAxisInputValue;
            cross3ValueY = resultComputation;
        }else{
            cross3ValueX = resultComputation;
            cross3ValueY = givenAxisInputValue;
        }
        
    }
    //NSLog(@"2 cross3ValueX %f", cross3ValueX);
    
    if (partNumberToCompute == 4) {
        if (yToX == 0) { // wenn X to Y, then cross1ValueY = resultComputation;
            cross4ValueX = givenAxisInputValue;
            cross4ValueY = resultComputation;
        }else{
            cross4ValueX = resultComputation;
            cross4ValueY = givenAxisInputValue;
        }
        
    }
    
    
    if (partNumberToCompute == 5) {
        if (yToX == 0) { // wenn X to Y, then cross1ValueY = resultComputation;
            cross5ValueX = givenAxisInputValue;
            cross5ValueY = resultComputation;
        }else{
            cross5ValueX = resultComputation;
            cross5ValueY = givenAxisInputValue;
        }
        
    }
    if ([chartNameForThisInfoFile isEqualToString:@"Heli_MBB_BO105_NONE_HIGE_TorqueTOT_byMTOWCold"] && partNumberToCompute == 5) {
        resultTOT = cross5ValueY;
        //NSLog(@"resultTOT %f", resultTOT);        
        
    }
    
    if ([chartNameForThisInfoFile isEqualToString:@"Heli_MBB_BO105_NONE_HOGE_TorqueTOT_byMTOWCold"] && partNumberToCompute == 5) {
        resultTOT = cross5ValueY;
        //NSLog(@"resultTOT %f", resultTOT);        
        
    }
    
    return;
    
    
    
}

// perf chart zoom

- (void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer {
    
     //NSLog(@"twoFingerPinch");
    
    if (_viewCATAOverview1.hidden == NO || _viewCATAOverview2.hidden == NO || _viewCATAOverview3.hidden == NO || _viewPC2OverviewAS365.hidden == NO) {
        return;
    }
    
    if (flagCustomPageIsOn ==1 ) {
        return;
    }
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  || [[infoArray objectAtIndex: 3  ] rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound          ) {
        //NSLog(@"returning drawCrossesAndLines");
        return;
    }
  
    
    pinchScale =  ((recognizer.scale-1) * 2) + pinchScaleEnded;
    
     //NSLog(@"twoFingerPinch pinchScale %.0f", pinchScale);
    
    if (pinchScale <= 1.1) {
        
        // reset view
        
        pinchScale= 1.0;
        moveupDown = 0; moveLeftRight = 0;
        
        CGAffineTransform transform = CGAffineTransformMakeScale(1, 1);
        self.viewChartsUniversal.transform = transform;
        
        [self computeChartSizeInApp];
        
    }else{
        
        if (pinchScale > 3.0) {
            pinchScale = 3.0;
        }
        
        CGAffineTransform transform = CGAffineTransformMakeScale(pinchScale, pinchScale);
        self.viewChartsUniversal.transform = transform;
        
        [self computeChartSizeInApp];
        
    }
    
    
    if(recognizer.state == UIGestureRecognizerStateEnded)
    {
        pinchScaleEnded = pinchScale;
        
    }
    
    
}

- (void)panRecognizer:(UIPanGestureRecognizer *)recognizer {
    
     //NSLog(@"panRecognizer");
    
    if (flagCustomPageIsOn ==1 ) {
        return;
    }
    
    if (_viewCATAOverview1.hidden == NO || _viewCATAOverview2.hidden == NO || _viewCATAOverview3.hidden == NO || _viewPC2OverviewAS365.hidden == NO) {
        return;
    }
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  || [[infoArray objectAtIndex: 3  ] rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound          ) {
        //NSLog(@"returning drawCrossesAndLines");
        return;
    }
    
    //NSLog(@"panRecognizer");
    
    CGPoint translation = [recognizer translationInView:self.view];
    
    moveupDown =  moveupDown + (translation.y / 1);
    
    moveLeftRight = moveLeftRight + (translation.x / 1);
    
    //NSLog(@"panRecognizer moveupDown %.0f", moveupDown);
    
    
    [self computeChartSizeInApp];
    
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
    
}


- (void)handleSingleTapOnView:(UIPanGestureRecognizer *)recognizer {

    
    if (flagCustomPageIsOn == 1 ) {
        return;
    }
    
    if ([[infoArray objectAtIndex: 0  ] rangeOfString:@"FXX"].location != NSNotFound  || [[infoArray objectAtIndex: 3  ] rangeOfString:@"CustomFixedWingOLD"].location != NSNotFound          ) {
        //NSLog(@"returning drawCrossesAndLines");
        return;
    }
    
    if (_viewCATAOverview1.hidden == NO || _viewCATAOverview2.hidden == NO || _viewCATAOverview3.hidden == NO || _viewPC2OverviewAS365.hidden == NO) {
        return;
    }
    
    
    //NSLog(@"handleSingleTapOnView");
   
    moveLeftRight = 0; moveupDown = 0;
    
    
    if (fullScreenPerfCharts == 0) {
        fullScreenPerfCharts = 1;
    }else{
        
        fullScreenPerfCharts = 0;
    }
    
    
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent actionFullScreenPerfChart: fullScreenPerfCharts];
    
     //NSLog(@"2 handleSingleTapOnView");
    
    [self calcPerformance];
    
   
 
    
}

- (void) interpolationMethod: (float)receivedBaseValue lowVal:(float)receivedLowVal highVal:(float)receivedHighVal lowSearch:(float)receivedLowSearch highSearch:(float)receivedHighSearch {

     interpolationResult = receivedLowSearch + ((receivedHighSearch - receivedLowSearch) * (((receivedBaseValue - receivedLowVal) * (100 / (receivedHighVal - receivedLowVal))) / 100 )) ;
    
    
    //float interpolationResult = 100 + ((receivedValHigh - receivedValLow) * (((receivedCriteria1 - receivedVal2Low) * (100 / (receivedVal2High - receivedVal2Low))) / 100 )) ;
    
    //NSLog(@"interpolatedRC1eng %.0f", interpolationResult);
    
 
    
}



- (IBAction)actionSwitchCATAVTOL:(id)sender {
    
    if (_viewVTOL.hidden == YES) {
        _viewVTOL.hidden = NO;
        _viewCATACH.hidden = YES;
    }else{
        _viewVTOL.hidden = YES;
        _viewCATACH.hidden = NO;
    }
    
}

- (void) resetInputObstacleHeight {
    
    
    _inputObstacleHeightMeter.text = @"0";
}


- (IBAction)closeKeyboard:(id)sender {
    
    
    [self.view endEditing:TRUE];
    
    [self calcModifiedTOPath];

    
}

- (void) calcModifiedTOPath {
    
    
    
    
    
    TDPheight = 0;
    RearwardTODist = 0;
    MinHeight = 0;
    HeightAchievedVTOSS = 0;
    contTODist = 0;
    
    MinHeight =  35 + ([_inputObstacleHeightMeter.text floatValue] * 3.28084 );
                         
                         
    
    if (MinHeight >=35 & MinHeight < 45) {  TDPheight = 130; RearwardTODist = 50; HeightAchievedVTOSS = 40; contTODist = 190; }
    if (MinHeight >=45 & MinHeight < 55) {  TDPheight = 140; RearwardTODist = 54; HeightAchievedVTOSS = 50; contTODist = 186; }
    if (MinHeight >=55 & MinHeight < 65) {  TDPheight = 150; RearwardTODist = 58; HeightAchievedVTOSS = 60; contTODist = 182; }
    if (MinHeight >=65 & MinHeight < 75) {  TDPheight = 160; RearwardTODist = 62; HeightAchievedVTOSS = 70; contTODist = 178; }
    if (MinHeight >=75 & MinHeight < 85) {  TDPheight = 170; RearwardTODist = 66; HeightAchievedVTOSS = 80; contTODist = 174; }
    if (MinHeight >=85 & MinHeight < 95) {  TDPheight = 180; RearwardTODist = 70; HeightAchievedVTOSS = 90; contTODist = 170; }
    if (MinHeight >=95 & MinHeight < 105) {  TDPheight = 190; RearwardTODist = 74; HeightAchievedVTOSS = 100; contTODist = 166; }
    if (MinHeight >=105 & MinHeight < 115) {  TDPheight = 200; RearwardTODist = 78; HeightAchievedVTOSS = 110; contTODist = 162; }
    if (MinHeight >=115 & MinHeight < 120) {  TDPheight = 210; RearwardTODist = 82; HeightAchievedVTOSS = 120; contTODist = 158; }
    
    
    _labelMinHeight.text = [[NSString alloc] initWithFormat:@"%.0f ft", MinHeight ];
    
    _labelTDPHeight.text = [[NSString alloc] initWithFormat:@"%.0f ft", TDPheight ];
    
    _labelRearwardTODist.text = [[NSString alloc] initWithFormat:@"%.0f m", RearwardTODist ];
    
    _labelHeightAchieved.text = [[NSString alloc] initWithFormat:@"%.0f ft", HeightAchievedVTOSS ];
    
    _labelContinuedTODist.text = [[NSString alloc] initWithFormat:@"%.0f m", contTODist ];
    
    
    
    
    
    
}



- (void) makeOverviewPages {
    
    
    // get results for H145:
    
    float AEO_HIGE_TOP = 0;
    
    float AEO_HIGE_TOP_CX = 0;
    
    
    //float Seg1Vtoss_3700kg = 0;
    //float Seg1Vtoss_3200kg = 0;
    
    float Seg2Vtoss_3700kg = 0;
    float Seg2Vtoss_3200kg = 0;
    
    float addGain2Vy = 0;
    
    float CATAenRouteOEIMCP = 0;
    //NSLog(@"resultsAllChartNames %@", resultsAllChartNames);
    
    
    
    for (int i = 1; i < resultsAllChartNames.count; i++) {
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"axMass_VTOL_Sup911_FigC4"].location != NSNotFound & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound   ) {
            _VTOLMaxMass.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"axMass_VTOL_Sup911_FigC4_CX"].location != NSNotFound   ) {
            _VTOLMaxMassCeiling.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Acc_Vtoss_Vy_VTOL_Sup911_FigC18"].location != NSNotFound   ) {
            _VTOLAccelerationDistance.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"MaxMass_VTOL_Training_Sup911_FigD1"].location != NSNotFound   ) {
            _VTOLMaxMassTraining.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        
        
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"AEO_HIGE_TOP_Sec5_Fig5_15"].location != NSNotFound & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound   ) {
            _AEOHIGETOP.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"AEO_HOGE_TOP_Sec5_Fig5_19"].location != NSNotFound & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound   ) {
            _AEOHOGETOP.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"OEI_HIGE_2min_Sec5_Fig5_24"].location != NSNotFound & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound   ) {
            _AEOHIGE2min.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"OEI_HOGE_2min_Sec5_Fig5_26"].location != NSNotFound & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound   ) {
            _AEOHOGE2min.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"OEI_HOGE_30sec_Sec5_Fig5_27"].location != NSNotFound & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound   ) {
            _AEOHOGE30sec.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"MaxMass_Sup911_FigB1"].location != NSNotFound & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound   ) {
            _chMaxMass.text = [[NSString alloc] initWithFormat:@"%.0f kg", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"MaxMass_Sup911_FigB1_CX"].location != NSNotFound  ) {
            _chMaxMassCeiling.text = [[NSString alloc] initWithFormat:@"%.0f ft", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Rejected_TO_Sup911_FigB10"].location != NSNotFound  ) {
            _chRejectedTOdist.text = [[NSString alloc] initWithFormat:@"%.0f m", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Continued_TO_Sup911_FigB12"].location != NSNotFound  ) {
            _chContTOdist.text = [[NSString alloc] initWithFormat:@"%.0f m", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Acc_Vtoss_Vy_Sup911_FigB14"].location != NSNotFound  ) {
            _chAccelDist.text = [[NSString alloc] initWithFormat:@"%.0f m", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Ldg_50ft_Sup911_FigB15"].location != NSNotFound  ) {
            _chLandingDist.text = [[NSString alloc] initWithFormat:@"%.0f m", [[resultsAllChartValues objectAtIndex: i  ] floatValue] ];
        }
        
        
        
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"EnRoute_OEI_MCP_Sup911_FigA25_CX"].location != NSNotFound  ) {
            CATAenRouteOEIMCP = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
            //NSLog(@"********** AEO_HIGE_TOP %.0f", AEO_HIGE_TOP);
        }
        
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"HeightGainVy_Sup911_FigA23"].location != NSNotFound  ) {
            addGain2Vy = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
            //NSLog(@"********** AEO_HIGE_TOP %.0f", AEO_HIGE_TOP);
        }
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"AEO_HIGE_TOP"].location != NSNotFound  & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location == NSNotFound ) {
            AEO_HIGE_TOP = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
            //NSLog(@"********** AEO_HIGE_TOP %.0f", AEO_HIGE_TOP);
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"AEO_HIGE_TOP"].location != NSNotFound  & [[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"CX"].location != NSNotFound ) {
            AEO_HIGE_TOP_CX = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
            //NSLog(@"********** AEO_HIGE_TOP_CX  %.0f", AEO_HIGE_TOP_CX);
        }
        
        
        
        /*
         if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Seg1Vtoss_3700kg"].location != NSNotFound  ) {
         Seg1Vtoss_3700kg = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
         //NSLog(@"********** Seg1Vtoss_3700kg  %.1f", Seg1Vtoss_3700kg);
         }
         
         if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Seg1Vtoss_3200kg"].location != NSNotFound   ) {
         Seg1Vtoss_3200kg = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
         //NSLog(@"********** Seg1Vtoss_3200kg  %.1f", Seg1Vtoss_3200kg);
         }
         */
        
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Seg2Vtoss_3700kg"].location != NSNotFound  ) {
            Seg2Vtoss_3700kg = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
            //NSLog(@"********** Seg2Vtoss_3700kg  %.1f", Seg2Vtoss_3700kg);
        }
        
        if ([[resultsAllChartNames objectAtIndex: i  ] rangeOfString:@"Seg2Vtoss_3200kg"].location != NSNotFound   ) {
            Seg2Vtoss_3200kg = [[resultsAllChartValues objectAtIndex: i  ] floatValue];
            //NSLog(@"********** Seg2Vtoss_3200kg  %.1f", Seg2Vtoss_3200kg);
        }
        
        
    }
    
    
    
    
    _labelCurrentACweight.text = [[NSString alloc] initWithFormat:@"%.0f kg", unchangedACWeight ];
    
    _labelFuelWeight.text = [[NSString alloc] initWithFormat:@"%.0f kg", fuelWeight ];
    
    _labelDensityAlt.text = [[NSString alloc] initWithFormat:@"%.0f ft", DensityAlt ];
    
    
    _MTOWcorrectionPenalty.text = [[NSString alloc] initWithFormat:@"%.0f kg", penaltyWeight ];
    
    
    
    _addGain2Vy.text = [[NSString alloc] initWithFormat:@"%.1f %%", addGain2Vy ];
    
    _catAEnRouteOEIMCPCeiling.text = [[NSString alloc] initWithFormat:@"%.0f ft", CATAenRouteOEIMCP ];
    
    // do interpolations
    
    float acWeightForInterpolation = acWeight;
    if (acWeightForInterpolation < 3200) {
        acWeightForInterpolation = 3200;
    }
    
    if (acWeightForInterpolation > 3700) {
        acWeightForInterpolation = 3700;
    }
    
    /*
     // Segment I OEi MCp Grad
     [self interpolationMethod: acWeightForInterpolation lowVal:3200  highVal:3700  lowSearch:Seg1Vtoss_3200kg highSearch:Seg1Vtoss_3700kg  ];
     float seg1VtossInterpolated = interpolationResult;
     _interpolatedSeg1OEIMCPGrad.text = [[NSString alloc] initWithFormat:@"%.1f %%", seg1VtossInterpolated ];
     //NSLog(@"+++++++ Interpolated Seg1Vtoss  %.1f", seg1VtossInterpolated);
     */
    
    // Segment II OEi MCp Grad
    [self interpolationMethod: acWeightForInterpolation lowVal:3200  highVal:3700  lowSearch:Seg2Vtoss_3200kg highSearch:Seg2Vtoss_3700kg  ];
    float seg2VtossInterpolated = interpolationResult;
    _interpolatedSeg2OEIMCPGrad.text = [[NSString alloc] initWithFormat:@"%.1f %%", seg2VtossInterpolated ];
    //NSLog(@"+++++++ Interpolated Seg2Vtoss  %.1f", seg2VtossInterpolated);
    
    
    
    
    
    
    
}
- (IBAction)sliderActionEngineTorque1:(id)sender {
    
    int dummy = _sliderEngineTorque1.value/1;
    _sliderEngineTorque1.value = dummy * 1;
    [self calcPerformance];
    
}
- (IBAction)sliderActionEngineTorque2:(id)sender {
    
    int dummy = _sliderEngineTorque2.value/1;
    _sliderEngineTorque2.value = dummy * 1;
    [self calcPerformance];
}


- (IBAction)sliderActionITT1:(id)sender {
    
    int dummy = _sliderITT1.value/10;
    _sliderITT1.value = dummy * 10;
    [self calcPerformance];
}
- (IBAction)sliderActionITT2:(id)sender {
    
    int dummy = _sliderITT2.value/10;
    _sliderITT2.value = dummy * 10;
    [self calcPerformance];
}






- (IBAction)actionSegmentCheckType:(id)sender {
    
    [self calcPerformance];
}


- (IBAction)actionSendPowerCheckViaEmail:(id)sender {
    
    
    ViewController *parent = (ViewController *)self.parentViewController;
    
    if (_segentCheckType.selectedSegmentIndex == 0) {
        powerCheckType = @"Hover";
    }else{        
         powerCheckType = @"In-Flight";
    }
    
    [parent actionSendPowerCheckEmail: [_inputEngineTorque1.text floatValue]  sendTorque2:[_inputEngineTorque2.text floatValue]  sendITT1:[_inputITT1.text floatValue]  sendITT2:[_inputITT2.text floatValue] sendMaxITT1:[_labelMaxAllowableITTEngine1.text floatValue] sendMaxITT2:[_labelMaxAllowableITTEngine1.text floatValue] sendMargin1:[_labelMargineEngine1.text floatValue]  sendMargin2:[_labelMargineEngine2.text floatValue] sendResult1:_labelPowerCheckResult1.text sendResult2:_labelPowerCheckResult2.text sendCheckType:powerCheckType];
    
    
    
    
    
}
- (IBAction)sliderActionRunwayHeadingTO:(id)sender {
    int dummy = _sliderRundwayHeadingTO.value/10;
    _sliderRundwayHeadingTO.value = dummy * 10;
    [self calcPerformance];
}



- (IBAction)sliderActionRunwayHeadingLD:(id)sender {
    int dummy = _sliderRundwayHeadingLD.value/10;
    _sliderRundwayHeadingLD.value = dummy * 10;
    [self calcPerformance];
}






// ***************************************************



- (IBAction)sliderActionRunwayLengthLD:(id)sender {
    
    int dummy = _sliderRunwayLengthLD.value/frwyIncrement;
    _sliderRunwayLengthLD.value = dummy * frwyIncrement;
    
    [self calcPerformance];
}

- (IBAction)sliderActionACWeightOverrideTO:(id)sender {
    
    int dummy = _sliderAircraftWeightOverrideTO.value/25;
    _sliderAircraftWeightOverrideTO.value = dummy * 25;
    
    [self calcPerformance];
}


- (IBAction)sliderActionRunwayConditionsTO:(id)sender {
    
    int dummy = _sliderRunwayConditionsTO.value/5;
    _sliderRunwayConditionsTO.value = dummy * 5;
    [self calcPerformance];
}

- (IBAction)sliderActionRunwayConditionsLD:(id)sender {
    
    int dummy = _sliderRunwayConditionsLD.value/5;
    _sliderRunwayConditionsLD.value = dummy * 5;
    [self calcPerformance];
}


- (IBAction)sliderActionSlopeTO:(id)sender {
    
    int dummy = _sliderSlopeTO.value/1;
    _sliderSlopeTO.value = dummy * 1;
    [self calcPerformance];
}

- (IBAction)sliderActionSlopeLD:(id)sender {
    
    int dummy = _sliderSlopeLD.value/1;
    _sliderSlopeLD.value = dummy * 1;
    [self calcPerformance];
}


- (IBAction)sliderActionACWeightOverrideLD:(id)sender {
    
    int dummy = _sliderAircraftWeightOverrideLD.value/25;
    _sliderAircraftWeightOverrideLD.value = dummy * 25;
    
    [self calcPerformance];
}






- (IBAction)actionLockACweightOverrideTO:(id)sender {
    
    if (_sliderAircraftWeightOverrideTO.minimumValue == _sliderAircraftWeightOverrideTO.maximumValue) {
        return;
    } 
    
    if (lockACweightOverrideTO == 0) {
        lockACweightOverrideTO = 1;
        UIImage *lock = [UIImage imageNamed:@"lock - locked-01.png"];
        [_lockACweightTO setImage:lock];
        _sliderAircraftWeightOverrideTO.enabled = NO;
    }else{
         lockACweightOverrideTO = 0;
        UIImage *lock = [UIImage imageNamed:@"lock - UNlocked-01.png"];
        [_lockACweightTO setImage:lock];
        _sliderAircraftWeightOverrideTO.enabled = YES;
    }
   
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent MainRoutine];
}


- (IBAction)actionLockACweightOverrideLD:(id)sender {
    
    if (_sliderAircraftWeightOverrideLD.minimumValue == _sliderAircraftWeightOverrideLD.maximumValue) {
        return;
    }
    
    if (lockACweightOverrideLD == 0) {
        lockACweightOverrideLD = 1;
        UIImage *lock = [UIImage imageNamed:@"lock - locked-01.png"];
        [_lockACweightLD setImage:lock];
        _sliderAircraftWeightOverrideLD.enabled = NO;
    }else{
        lockACweightOverrideLD = 0;
        UIImage *lock = [UIImage imageNamed:@"lock - UNlocked-01.png"];
        [_lockACweightLD setImage:lock];
        _sliderAircraftWeightOverrideLD.enabled = YES;
    }
    
   
    
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent MainRoutine];
    
}

- (IBAction)segmentActionFixedWingDistanceUnitsTO:(id)sender {
    //NSLog(@"seg1");
    _segmentMeterFeetLD.selectedSegmentIndex =  _segmentMeterFeet.selectedSegmentIndex;
    _segmentMeterFeetClimb.selectedSegmentIndex =  _segmentMeterFeet.selectedSegmentIndex;
    _segmentMeterFeetCruise.selectedSegmentIndex =  _segmentMeterFeet.selectedSegmentIndex;
    [self saveFixedWingSliders];
    [self calcPerformance];
     [self calcPerformance];
    
}

- (IBAction)segmentActionFixedWingDistanceUnitsLD:(id)sender {
      //NSLog(@"seg2");
    _segmentMeterFeet.selectedSegmentIndex =  _segmentMeterFeetLD.selectedSegmentIndex;
    _segmentMeterFeetClimb.selectedSegmentIndex =  _segmentMeterFeetLD.selectedSegmentIndex;
     _segmentMeterFeetCruise.selectedSegmentIndex =  _segmentMeterFeetLD.selectedSegmentIndex;
     [self saveFixedWingSliders];
    [self calcPerformance];
     [self calcPerformance];
    
}

- (IBAction)segmentActionFixedWingDistanceUnitsClimb:(id)sender {
    //NSLog(@"seg2");
    _segmentMeterFeet.selectedSegmentIndex =  _segmentMeterFeetClimb.selectedSegmentIndex;
    _segmentMeterFeetLD.selectedSegmentIndex =  _segmentMeterFeetClimb.selectedSegmentIndex;
    _segmentMeterFeetCruise.selectedSegmentIndex =  _segmentMeterFeetClimb.selectedSegmentIndex;
    
    [_viewForClimbGrid.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    [self createGraphicsClimb];
    
    
    [self saveFixedWingSliders];
    [self calcPerformance];
     [self calcPerformance];
    
}

- (IBAction)segmentActionFixedWingDistanceUnitsCruise:(id)sender {
    //NSLog(@"seg2");
    _segmentMeterFeet.selectedSegmentIndex =  _segmentMeterFeetCruise.selectedSegmentIndex;
    _segmentMeterFeetLD.selectedSegmentIndex =  _segmentMeterFeetCruise.selectedSegmentIndex;
    _segmentMeterFeetCruise.selectedSegmentIndex =  _segmentMeterFeetCruise.selectedSegmentIndex;
    
    [_viewCruiseGrid.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; // delete old lines and dots
    [self createGraphicsCruise];
    
    
    [self saveFixedWingSliders];
    [self calcPerformance];
    [self calcPerformance];
    
}



- (IBAction)sliderActionRunwayLength:(id)sender {
    
    int dummy = _sliderRunwayLength.value/frwyIncrement;
    _sliderRunwayLength.value = dummy * frwyIncrement;
    [self calcPerformance];
}

- (IBAction)segmentActionFlapsLD:(id)sender {
    [self calcPerformance];
}





- (IBAction)sliderActionEngineRPMcruise:(id)sender {
    int dummy = _sliderEngineRPMcruise.value/sliderEngineRPMincrement;
    _sliderEngineRPMcruise.value = dummy * sliderEngineRPMincrement;    
    [self calcPerformance];
}
- (IBAction)sliderActionTripDistanceNM:(id)sender {
    int dummy = _sliderTripDistanceNM.value/10;
    _sliderTripDistanceNM.value = dummy * 10;    
    [self calcPerformance];
    
}


- (void) calcR44RavenIIMAP {
    
    float OATNorm =  OAT; 
    
    float MAP_1 = 0, MAP_2 = 0, MAPResult = 0;
    
    vPA = Hp;
    
    if (OATNorm >= -40 & OATNorm < -20) {
        MAP_1= (3.39999999999994E-09 * powf(vPA, 2) )   + ( -0.000258999999999999  * vPA ) + 23.65   ; MAP_2 = (5.39999999999996E-09 * powf(vPA, 2) )   + ( -0.000288999999999999  * vPA ) + 24.45   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - -40)  );        
        }
    
    
    
    if (OATNorm >= -20 & OATNorm < 0) {
        MAP_1= (5.39999999999996E-09 * powf(vPA, 2) )   + ( -0.000288999999999999  * vPA ) + 24.45   ; MAP_2 = (5.40000000000005E-09 * powf(vPA, 2) )   + ( -0.000299  * vPA ) + 25.15   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - -20)  );
        }
    
    
    if (OATNorm >= 0 & OATNorm < 20) {
        MAP_1= (5.40000000000005E-09 * powf(vPA, 2) )   + ( -0.000299  * vPA ) + 25.15   ; MAP_2 = (1.20000000000009E-09 * powf(vPA, 2) )   + ( -0.000272000000000001  * vPA ) + 25.7   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - 0)  );
      }
    
    
    
    if (OATNorm >= 20 & OATNorm <= 40) {
        MAP_1= (1.20000000000009E-09 * powf(vPA, 2) )   + ( -0.000272000000000001  * vPA ) + 25.7   ; MAP_2 = (6.63738257720533E-23 * powf(vPA, 2) )   + ( -0.000280000000000001  * vPA ) + 26.3   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - 20)  );
      }
    
    if (MAPResult > 26.5) {
        MAPResult = 26.5;
    }
    
    if (MAPResult < 20.0) {
        MAPResult = 20.0;
    }
    
    maxContinuousPower = MAPResult - 2.8;
    
    fiveMinuteTakeoffPower = MAPResult;
    
    CUT= (1.34492605911426E-08 * powf(vPA, 2) )   + ( -0.001050789648276  * vPA ) + 28.5677167266014 ;
    
    if (CUT < 20.0) {
        CUT = 20.0;
    }    
   
    _labelMCP.textColor = [UIColor whiteColor];
    _labelMAPmax.textColor = [UIColor whiteColor];
    
    
    // maxLine    
    float maxLine = (3.96825396825396E-08 * powf(vPA, 2) )   + ( -0.00157936507936508  * vPA ) + 33.8253968253968    ;
        
    if (fiveMinuteTakeoffPower < CUT) {        
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg", fiveMinuteTakeoffPower - 2.8];
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg", fiveMinuteTakeoffPower];
        redCrossYValue = fiveMinuteTakeoffPower;
        
        maxContinuousPowerResult = fiveMinuteTakeoffPower - 2.8;        
        fiveMinuteTakeoffPowerResult = fiveMinuteTakeoffPower;
    }
    
    if (fiveMinuteTakeoffPower >= CUT) {        
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg", fiveMinuteTakeoffPower - 2.8 ];        
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg (FULL THROTTLE)", CUT];
        _labelMAPmax.textColor = [UIColor orangeColor];        
        redCrossYValue = CUT;
        maxContinuousPowerResult = fiveMinuteTakeoffPower - 2.8;        
        fiveMinuteTakeoffPowerResult = fiveMinuteTakeoffPower;
    }
    
    if (fiveMinuteTakeoffPower > maxLine) {        
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg (FULL THROTTLE)", redCrossYValue ];        
        _labelMCP.textColor = [UIColor orangeColor];
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"NO 5min Max Takeoff Power!!" ];
        _labelMAPmax.textColor = [UIColor orangeColor];  
        
        maxContinuousPowerResult = redCrossYValue;        
        fiveMinuteTakeoffPowerResult = 0;
    }
    
    // NEEDLE MAP
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];    
    float MAPdegree = ((MAPResult-2.8) -20) *0.0174;    
    _graphicMAPneedle.transform =CGAffineTransformMakeRotation(MAPdegree * 8 );  
     [UIView commitAnimations];
    
    [self animateCrossRedMAP];
    
}

- (void) calcR44RavenAstroMAP {
    
    float OATNorm =  OAT; 
    
    float MAP_1 = 0, MAP_2 = 0, MAPResult = 0;
    
    vPA = Hp;
    
    if (OATNorm >= -40 & OATNorm < -20) {
        MAP_1= (0.000000014 * powf(vPA, 2) )   + ( -0.00031  * vPA ) + 23.7   ; MAP_2 = (3.99999999999998E-09 * powf(vPA, 2) )   + ( -0.00022  * vPA ) + 24.5   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - -40)  );
        }
    
    
    
    if (OATNorm >= -20 & OATNorm < 0) {
        MAP_1= (3.99999999999998E-09 * powf(vPA, 2) )   + ( -0.00022  * vPA ) + 24.5   ; MAP_2 = (4.80000000000011E-09 * powf(vPA, 2) )   + ( -0.000228000000000001  * vPA ) + 25.1   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - -20)  );
         }
    
    
    
    if (OATNorm >= 0 & OATNorm < 20) {
        MAP_1= (4.80000000000011E-09 * powf(vPA, 2) )   + ( -0.000228000000000001  * vPA ) + 25.1   ; MAP_2 = (8.00000000000036E-10 * powf(vPA, 2) )   + ( -0.000218  * vPA ) + 25.7   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - 0)  );
        }
    
    
    
    if (OATNorm >= 20 & OATNorm < 40) {
        MAP_1= (8.00000000000036E-10 * powf(vPA, 2) )   + ( -0.000218  * vPA ) + 25.7   ; MAP_2 = (6.00000000000006E-09 * powf(vPA, 2) )   + ( -0.000260000000000001  * vPA ) + 26.3   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - 20)  );
        }
    
    
    
    if (MAPResult > 26.5) {
        MAPResult = 26.5;
    }
    
    if (MAPResult < 21.5) {
        MAPResult = 21.5;
    }
    
    if (_robinsonSwitchCarbHeat.on == YES) {        
        MAPResult = MAPResult + 1.5;        
    }
    
    maxContinuousPower = MAPResult - 2.8;
    
    fiveMinuteTakeoffPower = MAPResult;
    
    CUT= (1.17422128407316E-08 * powf(vPA, 2) )   + ( -0.000979749517878556  * vPA ) + 27.3722633736897   ;
    
    if (CUT < 21.5) {
        CUT = 21.5;
    }    
    
    _labelMCP.textColor = [UIColor whiteColor];
    _labelMAPmax.textColor = [UIColor whiteColor];
    
    
    // maxLine    
    float maxLine = (5.25818267753753E-08 * powf(vPA, 2) )   + ( -0.00139784946236559  * vPA ) + 30.2203119461184   ;
    
    if (fiveMinuteTakeoffPower < CUT) {        
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg", fiveMinuteTakeoffPower - 1.6];
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg", fiveMinuteTakeoffPower];
        redCrossYValue = fiveMinuteTakeoffPower;
        
        maxContinuousPowerResult = fiveMinuteTakeoffPower - 2.8;        
        fiveMinuteTakeoffPowerResult = fiveMinuteTakeoffPower;
    }
    
    if (fiveMinuteTakeoffPower >= CUT) {        
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg", fiveMinuteTakeoffPower - 1.6 ];        
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg (FULL THROTTLE)", CUT];
        _labelMAPmax.textColor = [UIColor orangeColor];        
        redCrossYValue = CUT;
        maxContinuousPowerResult = fiveMinuteTakeoffPower - 2.8;        
        fiveMinuteTakeoffPowerResult = fiveMinuteTakeoffPower;
    }
    
    if (fiveMinuteTakeoffPower > maxLine) {        
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.1f inHg (FULL THROTTLE)", redCrossYValue ];        
        _labelMCP.textColor = [UIColor orangeColor];
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"NO 5min Max Takeoff Power!!" ];
        _labelMAPmax.textColor = [UIColor orangeColor];  
        
        maxContinuousPowerResult = redCrossYValue;        
        fiveMinuteTakeoffPowerResult = 0;
    }
    
    // NEEDLE MAP
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];    
    float MAPdegree = ((MAPResult-2.8) -20) *0.0174;    
    _graphicMAPneedle.transform =CGAffineTransformMakeRotation(MAPdegree * 8 );  
    [UIView commitAnimations];
    
    [self animateCrossRedMAPAstro];
    
}

- (void) animateCrossRedMAPAstro {
    
    float maxPA = Hp;    
    if (maxPA >7000) {
        maxPA = 7000;
    }    
    if (maxPA < 0) {
        maxPA = 0;
    }
    // convert actual values in x y coordinates for display on iPad    
    // X Position
    
    
    float OGEscaleXstartPixel  = 55+35;   //left corner of graphic
    float OGEscaleXendPixel    = 540+35; // right corner        
    float OGEscaleXstartValue  = 0; // left start value
    float OGEscaleXendValue    = 7000;
    
    float OGEpixelDiffx = OGEscaleXendPixel - OGEscaleXstartPixel;
    float OGEvalueDiffx = OGEscaleXendValue - OGEscaleXstartValue;
    float OGEpixStepx = OGEpixelDiffx/OGEvalueDiffx ;    
    float OGExwert = maxPA - OGEscaleXstartValue; // wert ist null wenn ganz links auf Achse 2400-1500 = 900    
    float OGExposition = OGEscaleXstartPixel + (OGEpixStepx* OGExwert) ;
        
    // Y Position
    float OGEscaleYstartPixel  = 352+35; // bottom of graphic
    float OGEscaleYendPixel    = 86+35; // top   
    
    float OGEscaleYstartValue  = 21.5; // bottom start value
    float OGEscaleYendValue    = 26; // top value
    
    float OGEpixelDiffy = OGEscaleYendPixel - OGEscaleYstartPixel;
    float OGEvalueDiffy = OGEscaleYendValue - OGEscaleYstartValue;
    float OGEpixStepy = OGEpixelDiffy/OGEvalueDiffy ; //    
    float OGEywert =   fiveMinuteTakeoffPower - OGEscaleYstartValue;     
    float OGEywertCross =   redCrossYValue - OGEscaleYstartValue;    
    float OGEyposition = OGEscaleYstartPixel + (OGEpixStepy* OGEywert) ;    
    float OGEypositionCross = OGEscaleYstartPixel + (OGEpixStepy* OGEywertCross) ;       
    float OGEywertBlue =   (fiveMinuteTakeoffPower - 1.6) - OGEscaleYstartValue;    
    float OGEypositionCrossBlue = OGEscaleYstartPixel + (OGEpixStepy* OGEywertBlue) ;
    _crossMCP.center = CGPointMake( OGExposition, OGEypositionCross);  
    _barMCPVerticalRED.center = CGPointMake( OGExposition, OGEscaleYstartPixel);     
    _barMCPVerticalRED.layer.anchorPoint = CGPointMake(0.5, 1); 
    float heightRed = (26.7 / 4.5 ) * ( fiveMinuteTakeoffPower - 21.5);    
    _barMCPVerticalRED.layer.transform = CATransform3DMakeScale(1, heightRed, 0); // breit / hoch 20.5 = 800
    
    // QUERBALKEN    
    _barQuerBlue.center = CGPointMake( 97, OGEyposition );    
    _barQuerBlue.layer.anchorPoint = CGPointMake(0, 0.5);    
    float balkenlaenge =  (48.9/7000) * maxPA;    
    _barQuerBlue.layer.transform = CATransform3DMakeScale(balkenlaenge, 1.0, 0.0);
    // BAR BLUE VERTICAL    
    _barMCPVerticalBlue.center = CGPointMake( 97, OGEyposition);
    _barMCPVerticalBlue.layer.anchorPoint = CGPointMake(0.5, 1); 
    float heightBlue = -1 * ((26.7 / 6 ) * 1.6);    
    _barMCPVerticalBlue.layer.transform = CATransform3DMakeScale(1, heightBlue, 0); 
    _crossMCP2.center = CGPointMake( 97, OGEypositionCrossBlue);    
    _labelMinusInches.center = CGPointMake( 156, OGEypositionCrossBlue - 35);
    if (fiveMinuteTakeoffPower > CUT) {        
        _barQuerBlue.hidden = NO;        
    } else {        
        _barQuerBlue.hidden = NO;
       }
    // QUERBALKEN BLUE    
    _barQuerRed.center = CGPointMake( 97, OGEypositionCross );    
    _barQuerRed.layer.anchorPoint = CGPointMake(0, 0.5);    
    float balkenlaengeBlue =  (48.9/7000) * maxPA;    
    _barQuerRed.layer.transform = CATransform3DMakeScale(balkenlaengeBlue, 1.0, 0.0);
    
    
}

- (void) animateCrossRedMAP {
        
    
    float maxPA = Hp;
    
    if (maxPA >10000) {
        maxPA = 10000;
    }
    
    if (maxPA < 0) {
        maxPA = 0;
    }
    
    
    
    
    
    // convert actual values in x y coordinates for display on iPad
    
    // X Position
    
    
    float OGEscaleXstartPixel  = 85;   //left corner of graphic
    float OGEscaleXendPixel    = 612; // right corner
    
    
    float OGEscaleXstartValue  = 0; // left start value
    float OGEscaleXendValue    = 10000;
    
    float OGEpixelDiffx = OGEscaleXendPixel - OGEscaleXstartPixel;
    float OGEvalueDiffx = OGEscaleXendValue - OGEscaleXstartValue;
    float OGEpixStepx = OGEpixelDiffx/OGEvalueDiffx ;
    
    float OGExwert = maxPA - OGEscaleXstartValue; // wert ist null wenn ganz links auf Achse 2400-1500 = 900
    
    float OGExposition = OGEscaleXstartPixel + (OGEpixStepx* OGExwert) ;
    
    
    // Y Position
    
    
    float OGEscaleYstartPixel  = 391; // bottom of graphic
    float OGEscaleYendPixel    = 111; // top
    
    
    float OGEscaleYstartValue  = 20; // bottom start value
    float OGEscaleYendValue    = 26; // top value
    
    
    
    
    
    float OGEpixelDiffy = OGEscaleYendPixel - OGEscaleYstartPixel;
    float OGEvalueDiffy = OGEscaleYendValue - OGEscaleYstartValue;
    float OGEpixStepy = OGEpixelDiffy/OGEvalueDiffy ; //
    
    float OGEywert =   fiveMinuteTakeoffPower - OGEscaleYstartValue; 
    
    float OGEywertCross =   redCrossYValue - OGEscaleYstartValue;
    
    float OGEyposition = OGEscaleYstartPixel + (OGEpixStepy* OGEywert) ;
    
    float OGEypositionCross = OGEscaleYstartPixel + (OGEpixStepy* OGEywertCross) ;
    
    
    float OGEywertBlue =   (fiveMinuteTakeoffPower - 2.8) - OGEscaleYstartValue;
    
    float OGEypositionCrossBlue = OGEscaleYstartPixel + (OGEpixStepy* OGEywertBlue) ;
    
    
    //NSLog (@"OGExposition %@ ", [ [NSString alloc] initWithFormat:@"%.1f lbs", OGExposition]);
    //NSLog (@"OGEyposition %@ ", [ [NSString alloc] initWithFormat:@"%.1f lbs", OGEyposition]);
    
    
    _crossMCP.center = CGPointMake( OGExposition, OGEypositionCross);
    
    //graphicCrossYellow.center = CGPointMake( 50, OGEyposition);
    
    
    
    // BAR vertical
    
    _barMCPVerticalRED.center = CGPointMake( OGExposition, OGEscaleYstartPixel); // BAR Pressue Alt  moving LEFT RIGHT
    
    
    _barMCPVerticalRED.layer.anchorPoint = CGPointMake(0.5, 1); // 0.5 = mitte    -0.5 + unterkante = oberkante // 6.89 = 100%
    
    
    float heightRed = (28.3 / 6 ) * ( fiveMinuteTakeoffPower - 20);
    
    _barMCPVerticalRED.layer.transform = CATransform3DMakeScale(1, heightRed, 0); // breit / hoch 20.5 = 800
    
    
    
    // QUERBALKEN
    
    _barQuerBlue.center = CGPointMake( 85, OGEyposition );
    
    _barQuerBlue.layer.anchorPoint = CGPointMake(0, 0.5);
    
    float balkenlaenge =  (52.8/10000) * maxPA;
    
    _barQuerBlue.layer.transform = CATransform3DMakeScale(balkenlaenge, 1.0, 0.0);
    
    
    
    
    
    // BAR BLUE VERTICAL
    
    _barMCPVerticalBlue.center = CGPointMake( 85, OGEyposition); // BAR Pressue Alt  moving LEFT RIGHT
    
    
    _barMCPVerticalBlue.layer.anchorPoint = CGPointMake(0.5, 1); // 0.5 = mitte    -0.5 + unterkante = oberkante // 6.89 = 100%
    
    
    float heightBlue = -1 * ((30.7 / 6 ) * 2.8);
    
    _barMCPVerticalBlue.layer.transform = CATransform3DMakeScale(1, heightBlue, 0); // breit / hoch 20.5 = 800
    
    
    // cross Blue
    
    _crossMCP2.center = CGPointMake( 85, OGEypositionCrossBlue);
    
    
    // label
    
    _labelMinusInches.center = CGPointMake( 144, OGEypositionCrossBlue - 35);
    
    
    
    if (fiveMinuteTakeoffPower > CUT) {
        
        _barQuerBlue.hidden = NO;
        
    } else {
        
        _barQuerBlue.hidden = NO;
        
    }
    
    
    
    // QUERBALKEN BLUE
    
    _barQuerRed.center = CGPointMake( 85, OGEypositionCross );
    
    _barQuerRed.layer.anchorPoint = CGPointMake(0, 0.5);
    
    float balkenlaengeBlue =  (52.8/10000) * maxPA;
    
    _barQuerRed.layer.transform = CATransform3DMakeScale(balkenlaengeBlue, 1.0, 0.0);
    
    
    
   
    
    
    
    return;
    
    
    
}

- (void) calcR44RavenIIVNE{
    
    // set variables for calculation
    float UL = 0; float UR = 0;  float OL = 0;  float OR = 0; // unten links oben links ....
    float trick =0;  float AltOben = 0;  float AltUnten =0;
    
    float PA = vPA;
    
    // SL - 2000
    
    
    // 2000 - 4000    
    if (PA < 2000  & OAT <=40 )          {trick = 130;}    
    if (PA < 4000  & OAT < 30)          {trick = 130;}    
    if (PA >=2000  & PA < 4000  & OAT >= 30 & OAT < 40)          {OL = 127; OR = 123;  UL = 118; UR = 114; AltOben = 2000; AltUnten = 4000; trick = 30;}
    if (PA >=2000  & PA < 4000  & OAT >= 40 & OAT < 41)          {OL = 123; OR = 123;  UL = 114; UR = 114; AltOben = 2000; AltUnten = 4000; trick = 40;}
    
    
    
    // 4000 - 6000    
    if (PA < 6000  & OAT < 10)          {trick = 130;}    
    if (PA >=4000  & PA < 6000  & OAT >= 10 & OAT < 20)          {OL = 126; OR = 122;  UL = 117; UR = 113; AltOben = 4000; AltUnten = 6000; trick = 10;}
    if (PA >=4000  & PA < 6000  & OAT >= 20 & OAT < 30)          {OL = 122; OR = 118;  UL = 113; UR = 108; AltOben = 4000; AltUnten = 6000; trick = 20;}
    if (PA >=4000  & PA < 6000  & OAT >= 30 & OAT < 40)          {OL = 118; OR = 114;  UL = 108; UR = 103; AltOben = 4000; AltUnten = 6000; trick = 30;}
    if (PA >=4000  & PA < 6000  & OAT >= 40 & OAT < 41)          {OL = 114; OR = 114;  UL = 103; UR = 103; AltOben = 4000; AltUnten = 6000; trick = 40;}
    
    
    
    // 6000 - 8000
    
    if (PA < 8000  & OAT < -10)          {trick = 130;}    
    if (PA >=6000  & PA < 8000  & OAT >= -10 & OAT < 0)          {OL = 126; OR = 122;  UL = 117; UR = 112; AltOben = 6000; AltUnten = 8000; trick = -10;}
    if (PA >=6000  & PA < 8000  & OAT >= 0 & OAT < 10)           {OL = 122; OR = 117;  UL = 112; UR = 107; AltOben = 6000; AltUnten = 8000; trick = 0;}
    if (PA >=6000  & PA < 8000  & OAT >= 10 & OAT < 20)          {OL = 117; OR = 113;  UL = 107; UR = 101; AltOben = 6000; AltUnten = 8000; trick = 10;}
    if (PA >=6000  & PA < 8000  & OAT >= 20 & OAT < 30)          {OL = 113; OR = 108;  UL = 101; UR = 96; AltOben = 6000; AltUnten = 8000; trick = 20;}
    if (PA >=6000  & PA < 8000  & OAT >= 30 & OAT < 40)          {OL = 108; OR = 103;  UL = 96; UR = 91; AltOben = 6000; AltUnten = 8000; trick = 30;}
    if (PA >=6000  & PA < 8000  & OAT >= 40 & OAT < 41)          {OL = 103; OR = 103;  UL = 91; UR = 91; AltOben = 6000; AltUnten = 8000; trick = 40;}
    
    // 8000 - 10000    
    if (PA >=8000  & PA < 10000  & OAT >= -30 & OAT < -20)       {OL = 126; OR = 122;  UL = 117; UR = 112; AltOben = 8000; AltUnten = 10000; trick = -30;}
    if (PA >=8000  & PA < 10000  & OAT >= -20 & OAT < -10)       {OL = 122; OR = 117;  UL = 112; UR = 106; AltOben = 8000; AltUnten = 10000; trick = -20;}
    if (PA >=8000  & PA < 10000  & OAT >= -10 & OAT < 0)         {OL = 117; OR = 112;  UL = 106; UR = 101; AltOben = 8000; AltUnten = 10000; trick = -10;}
    if (PA >=8000  & PA < 10000  & OAT >= 0 & OAT < 10)          {OL = 112; OR = 107;  UL = 101; UR = 95; AltOben = 8000; AltUnten = 10000; trick = 0;}
    if (PA >=8000  & PA < 10000  & OAT >= 10 & OAT < 20)         {OL = 107; OR = 101;  UL = 95; UR = 90; AltOben = 8000; AltUnten = 10000; trick = 10;}
    if (PA >=8000  & PA < 10000  & OAT >= 20 & OAT < 30)         {OL = 101; OR = 96;   UL = 90; UR = 85; AltOben = 8000; AltUnten = 10000; trick = 20;}
    
    // abstufung 8000
    if (PA >=8000  & PA < 8001  & OAT == 30)                     {OL = 96; OR = 96;    UL = 85; UR = 85; AltOben = 8000; AltUnten = 10000; trick = 30;}
    if (PA >=8000  & PA < 8001  & OAT > 30 & OAT < 40)           {OL = 96; OR = 91;    UL = 96; UR = 91; AltOben = 8000; AltUnten = 10000; trick = 30;}
    if (PA >=8000  & PA < 8001  & OAT >= 40 & OAT < 41)          {OL = 91; OR = 91;    UL = 91; UR = 91; AltOben = 8000; AltUnten = 10000; trick = 40;}
    
    if (PA >=8001  & OAT >= 30 )        {trick = 100;}
    
    // 10000 - 12000    
    if (PA >=10000  & PA < 12000  & OAT >= -30 & OAT < -20)      {OL = 117; OR = 112;  UL = 107; UR = 101; AltOben = 10000; AltUnten = 12000; trick = -30;}
    if (PA >=10000  & PA < 12000  & OAT >= -20 & OAT < -10)      {OL = 112; OR = 106;  UL = 101; UR = 95; AltOben = 10000; AltUnten = 12000; trick = -20;}
    if (PA >=10000  & PA < 12000  & OAT >= -10 & OAT < 0)        {OL = 106; OR = 101;  UL = 95; UR = 89; AltOben = 10000; AltUnten = 12000; trick = -10;}
    
    // Abstufung 10000 bei 0 Grad    
    if (PA >=10000  & PA < 12000  & OAT == 0  )                  {OL = 101; OR = 101;  UL =89; UR = 89; AltOben = 10000; AltUnten = 12000; trick = 0;}
    if (PA >=10000  & PA < 10001  & OAT > 0 & OAT < 10)          {OL = 101; OR = 95;  UL =101; UR = 95; AltOben = 10000; AltUnten = 12000; trick = 0;}
    if (PA >=10000  & PA < 10001  & OAT >= 10 & OAT < 20)        {OL = 95; OR = 90;  UL =95; UR = 90; AltOben = 10000; AltUnten = 12000; trick = 10;}
    if (PA >=10000  & PA < 10001  & OAT >= 20 & OAT < 30)        {OL = 90; OR = 85;  UL =90; UR = 85; AltOben = 10000; AltUnten = 12000; trick = 20;}
    if (PA >=10000  & PA < 10001  & OAT ==30)                    {OL = 85; OR = 85;  UL =85; UR = 85; AltOben = 10000; AltUnten = 12000; trick = 30;}
    
    if (PA >=10001  & OAT >= 1 )        {trick = 100;NSLog (@"6");}
    if (PA ==10000  & OAT > 30 )        {trick = 100;NSLog (@"7");}
    
    
    // 12000 - 14000
    
    if (PA >=12000  & PA < 14000  & OAT >= -30 & OAT < -20)          {OL = 107; OR = 101;  UL = 95; UR = 89; AltOben = 12000; AltUnten = 14000; trick = -30;}
    
    // Abstufung 12000
    if (PA >=12000  & PA < 14000  & OAT == -20)                      {OL = 101; OR = 101;  UL = 89; UR = 89; AltOben = 12000; AltUnten = 14000; trick = -20;}
    if (PA >=12000  & PA < 12001  & OAT >= -20 & OAT < -10)          {OL = 101; OR = 95;  UL = 101; UR = 95; AltOben = 12000; AltUnten = 14000; trick = -20;}
    if (PA >=12000  & PA < 12001  & OAT >= -10 & OAT < 0)            {OL = 95; OR = 89;  UL = 95; UR = 89; AltOben = 12000; AltUnten = 14000; trick = -10;}
    if (PA >=12000  & PA < 12001  & OAT == 0)                        {OL = 89; OR = 89;  UL = 89; UR = 89; AltOben = 12000; AltUnten = 14000; trick = 0;}
    
    if (PA >=12001  & OAT > -20 )      {trick = 100;}
    if (PA ==12000  & OAT > 0 )        {trick = 100;}
    
    //14000    
    if (PA == 14000  & OAT >= -30 & OAT < -20)                       {OL = 95; OR = 89;  UL = 95; UR = 89; AltOben = 14000; AltUnten = 16000; trick = -30;}
    if (PA == 14000  & OAT == -20)                                   {OL = 89; OR = 89;  UL = 89; UR = 89; AltOben = 14000; AltUnten = 16000; trick = -30;} 
    if (PA == 14000 & OAT >-20)     {trick = 100;}    
    if (PA > 14000 )                {trick = 100;}  
    
    // interpolation
    float VNEinterpolatedOben = ( ( (OR-OL)/10 ) * (OAT - trick) ) + OL;
    float VNEinterpolatedUnten = ( ( (UR-UL)/10 ) * (OAT - trick) ) + UL;    
    float VNEinterpolAlt = ((VNEinterpolatedOben - VNEinterpolatedUnten)/2000)* (PA-AltOben);    
    VNEinterpolTotal = 0;    
    VNEinterpolTotal = VNEinterpolatedOben - VNEinterpolAlt;  
    
    if (trick == 130) {
        VNEinterpolTotal = 130;
    }
    
    _graphicAirspeedPointer.hidden = NO;  
    _labelIASWarning.text = @"-";
    
    if (trick == 100) {
        VNEinterpolTotal = 0;
        _labelIASWarning.hidden = NO;
        _labelIASWarning.text = @"NO FLIGHT";
        
    }
    
    if (VNEinterpolTotal <10) {
        VNEinterpolTotal = 0;        
        _graphicAirspeedPointer.hidden = YES;
    }
    
    
    if (acWeight > 2200) {        
        VNEinterpolTotal = VNEinterpolTotal -10;
        _labelIASWarning.text = @"Over 2200lb/998kg TOGW VNE = max 120 KIAS";       
    }
    if (acWeight > 2200 & VNEinterpolTotal >120) {
        VNEinterpolTotal = 120;
        _labelIASWarning.text = @"Over 2200lb/998kg TOGW VNE = max 120 KIAS";
        
    }
    
    if (flagOneDoorOff == 1) {        
        //NSLog(@"VNEinterpolTotal %.0f ", VNEinterpolTotal);        
        if (VNEinterpolTotal > 100) {
            VNEinterpolTotal = 100;  
            _labelIASWarning.text = @"100 KIAS limit with any door(s) removed!";
        }        
    }
    

    // NEEDLE AIRSPEED    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];    
    float VNEMAPdegree = (VNEinterpolTotal) *0.0174; 
    _graphicAirspeedPointer.transform =CGAffineTransformMakeRotation(VNEMAPdegree * 2.17); // 2.17 is to adjust for the altimeter 
    [UIView commitAnimations];
    
}

- (void) calcR44RavenAstroVNE{
    
    // set variables for calculation
    float UL = 0; float UR = 0;  float OL = 0;  float OR = 0; // unten links oben links ....
    float trick =0;  float AltOben = 0;  float AltUnten =0;
    
    float PA = vPA;
    
    // SL - 2000
    
    
    if (PA < 2000  & OAT <=40 )          {trick = 130;}
    
    if (PA < 4000  & OAT < 30)          {trick = 130;}
    
    if (PA >=2000  & PA < 4000  & OAT >= 30 & OAT < 40)          {OL = 127; OR = 123;  UL = 118; UR = 114; AltOben = 2000; AltUnten = 4000; trick = 30;}
    if (PA >=2000  & PA < 4000  & OAT >= 40 & OAT < 41)          {OL = 123; OR = 123;  UL = 114; UR = 114; AltOben = 2000; AltUnten = 4000; trick = 40;}
    
    
    
    // 4000 - 6000
    
    if (PA < 6000  & OAT < 10)          {trick = 130;}
    
    if (PA >=4000  & PA < 6000  & OAT >= 10 & OAT < 20)          {OL = 126; OR = 122;  UL = 117; UR = 113; AltOben = 4000; AltUnten = 6000; trick = 10;}
    if (PA >=4000  & PA < 6000  & OAT >= 20 & OAT < 30)          {OL = 122; OR = 118;  UL = 113; UR = 108; AltOben = 4000; AltUnten = 6000; trick = 20;}
    if (PA >=4000  & PA < 6000  & OAT >= 30 & OAT < 40)          {OL = 118; OR = 114;  UL = 108; UR = 103; AltOben = 4000; AltUnten = 6000; trick = 30;}
    if (PA >=4000  & PA < 6000  & OAT >= 40 & OAT < 41)          {OL = 114; OR = 114;  UL = 103; UR = 103; AltOben = 4000; AltUnten = 6000; trick = 40;}
    
    
    
    // 6000 - 8000
    
    if (PA < 8000  & OAT < -10)          {trick = 130;}
    
    if (PA >=6000  & PA < 8000  & OAT >= -10 & OAT < 0)          {OL = 126; OR = 122;  UL = 117; UR = 112; AltOben = 6000; AltUnten = 8000; trick = -10;}
    if (PA >=6000  & PA < 8000  & OAT >= 0 & OAT < 10)           {OL = 122; OR = 117;  UL = 112; UR = 107; AltOben = 6000; AltUnten = 8000; trick = 0;}
    if (PA >=6000  & PA < 8000  & OAT >= 10 & OAT < 20)          {OL = 117; OR = 113;  UL = 107; UR = 101; AltOben = 6000; AltUnten = 8000; trick = 10;}
    if (PA >=6000  & PA < 8000  & OAT >= 20 & OAT < 30)          {OL = 113; OR = 108;  UL = 101; UR = 96; AltOben = 6000; AltUnten = 8000; trick = 20;}
    if (PA >=6000  & PA < 8000  & OAT >= 30 & OAT < 40)          {OL = 108; OR = 103;  UL = 96; UR = 91; AltOben = 6000; AltUnten = 8000; trick = 30;}
    if (PA >=6000  & PA < 8000  & OAT >= 40 & OAT < 41)          {OL = 103; OR = 103;  UL = 91; UR = 91; AltOben = 6000; AltUnten = 8000; trick = 40;}
    
    // 8000 - 10000
    
    if (PA >=8000  & PA < 10000  & OAT >= -30 & OAT < -20)       {OL = 126; OR = 122;  UL = 117; UR = 112; AltOben = 8000; AltUnten = 10000; trick = -30;}
    if (PA >=8000  & PA < 10000  & OAT >= -20 & OAT < -10)       {OL = 122; OR = 117;  UL = 112; UR = 106; AltOben = 8000; AltUnten = 10000; trick = -20;}
    if (PA >=8000  & PA < 10000  & OAT >= -10 & OAT < 0)         {OL = 117; OR = 112;  UL = 106; UR = 101; AltOben = 8000; AltUnten = 10000; trick = -10;}
    if (PA >=8000  & PA < 10000  & OAT >= 0 & OAT < 10)          {OL = 112; OR = 107;  UL = 101; UR = 95; AltOben = 8000; AltUnten = 10000; trick = 0;}
    if (PA >=8000  & PA < 10000  & OAT >= 10 & OAT < 20)         {OL = 107; OR = 101;  UL = 95; UR = 90; AltOben = 8000; AltUnten = 10000; trick = 10;}
    if (PA >=8000  & PA < 10000  & OAT >= 20 & OAT < 30)         {OL = 101; OR = 96;   UL = 90; UR = 85; AltOben = 8000; AltUnten = 10000; trick = 20;}
    
    // abstufung 8000
    if (PA >=8000  & PA < 8001  & OAT == 30)                     {OL = 96; OR = 96;    UL = 85; UR = 85; AltOben = 8000; AltUnten = 10000; trick = 30;}
    if (PA >=8000  & PA < 8001  & OAT > 30 & OAT < 40)           {OL = 96; OR = 91;    UL = 96; UR = 91; AltOben = 8000; AltUnten = 10000; trick = 30;}
    if (PA >=8000  & PA < 8001  & OAT >= 40 & OAT < 41)          {OL = 91; OR = 91;    UL = 91; UR = 91; AltOben = 8000; AltUnten = 10000; trick = 40;}
    
    if (PA >=8001  & OAT >= 30 )        {trick = 100;}
    
    // 10000 - 12000
    
    if (PA >=10000  & PA < 12000  & OAT >= -30 & OAT < -20)      {OL = 117; OR = 112;  UL = 107; UR = 101; AltOben = 10000; AltUnten = 12000; trick = -30;}
    if (PA >=10000  & PA < 12000  & OAT >= -20 & OAT < -10)      {OL = 112; OR = 106;  UL = 101; UR = 95; AltOben = 10000; AltUnten = 12000; trick = -20;}
    if (PA >=10000  & PA < 12000  & OAT >= -10 & OAT < 0)        {OL = 106; OR = 101;  UL = 95; UR = 89; AltOben = 10000; AltUnten = 12000; trick = -10;}
    
    // Abstufung 10000 bei 0 Grad
    
    if (PA >=10000  & PA < 12000  & OAT == 0  )                  {NSLog (@"1"); OL = 101; OR = 101;  UL =89; UR = 89; AltOben = 10000; AltUnten = 12000; trick = 0;}
    if (PA >=10000  & PA < 10001  & OAT > 0 & OAT < 10)          {NSLog (@"2");OL = 101; OR = 95;  UL =101; UR = 95; AltOben = 10000; AltUnten = 12000; trick = 0;}
    if (PA >=10000  & PA < 10001  & OAT >= 10 & OAT < 20)        {NSLog (@"3");OL = 95; OR = 90;  UL =95; UR = 90; AltOben = 10000; AltUnten = 12000; trick = 10;}
    if (PA >=10000  & PA < 10001  & OAT >= 20 & OAT < 30)        {NSLog (@"4");OL = 90; OR = 85;  UL =90; UR = 85; AltOben = 10000; AltUnten = 12000; trick = 20;}
    if (PA >=10000  & PA < 10001  & OAT ==30)                    {NSLog (@"5");OL = 85; OR = 85;  UL =85; UR = 85; AltOben = 10000; AltUnten = 12000; trick = 30;}
    
    if (PA >=10001  & OAT >= 1 )        {trick = 100;NSLog (@"6");}
    if (PA ==10000  & OAT > 30 )        {trick = 100;NSLog (@"7");}
    
    
    // 12000 - 14000
    
    if (PA >=12000  & PA < 14000  & OAT >= -30 & OAT < -20)          {OL = 107; OR = 101;  UL = 95; UR = 89; AltOben = 12000; AltUnten = 14000; trick = -30;}
    
    // Abstufung 12000
    if (PA >=12000  & PA < 14000  & OAT == -20)                      {OL = 101; OR = 101;  UL = 89; UR = 89; AltOben = 12000; AltUnten = 14000; trick = -20;}
    if (PA >=12000  & PA < 12001  & OAT >= -20 & OAT < -10)          {OL = 101; OR = 95;  UL = 101; UR = 95; AltOben = 12000; AltUnten = 14000; trick = -20;}
    if (PA >=12000  & PA < 12001  & OAT >= -10 & OAT < 0)            {OL = 95; OR = 89;  UL = 95; UR = 89; AltOben = 12000; AltUnten = 14000; trick = -10;}
    if (PA >=12000  & PA < 12001  & OAT == 0)                        {OL = 89; OR = 89;  UL = 89; UR = 89; AltOben = 12000; AltUnten = 14000; trick = 0;}
    
    if (PA >=12001  & OAT > -20 )      {trick = 100;}
    if (PA ==12000  & OAT > 0 )        {trick = 100;}
    
    //14000
    
    if (PA == 14000  & OAT >= -30 & OAT < -20)                       {OL = 95; OR = 89;  UL = 95; UR = 89; AltOben = 14000; AltUnten = 16000; trick = -30;}
    if (PA == 14000  & OAT == -20)                                   {OL = 89; OR = 89;  UL = 89; UR = 89; AltOben = 14000; AltUnten = 16000; trick = -30;}
    
    if (PA == 14000 & OAT >-20)     {trick = 100;}
    
    if (PA > 14000 )                {trick = 100;}
    
    
    
    // interpolation
    float VNEinterpolatedOben = ( ( (OR-OL)/10 ) * (OAT - trick) ) + OL;
    float VNEinterpolatedUnten = ( ( (UR-UL)/10 ) * (OAT - trick) ) + UL;    
    float VNEinterpolAlt = ((VNEinterpolatedOben - VNEinterpolatedUnten)/2000)* (PA-AltOben);    
    VNEinterpolTotal = 0;    
    VNEinterpolTotal = VNEinterpolatedOben - VNEinterpolAlt;  
    
    if (trick == 130) {
        VNEinterpolTotal = 130;
    }

    _graphicAirspeedPointer.hidden = NO;  
     _labelIASWarning.text = @"-";
    
    if (trick == 100) {
        VNEinterpolTotal = 0;
        _labelIASWarning.hidden = NO;
        _labelIASWarning.text = @"NO FLIGHT";
        
    }
    
    if (VNEinterpolTotal <10) {
        VNEinterpolTotal = 0;        
        _graphicAirspeedPointer.hidden = YES;
    }
    
   
    if (acWeight > 2200) {        
        VNEinterpolTotal = VNEinterpolTotal -10;
         _labelIASWarning.text = @"Over 2200lb/998kg TOGW VNE = max 120 KIAS";       
    }
    if (acWeight > 2200 & VNEinterpolTotal >120) {
        VNEinterpolTotal = 120;
        _labelIASWarning.text = @"Over 2200lb/998kg TOGW VNE = max 120 KIAS";
        
    }
    
    if (flagOneDoorOff == 1) {        
        //NSLog(@"VNEinterpolTotal %.0f ", VNEinterpolTotal);        
        if (VNEinterpolTotal > 100) {
            VNEinterpolTotal = 100;  
            _labelIASWarning.text = @"100 KIAS limit with any door(s) removed!";
        }        
    }
    
    // NEEDLE AIRSPEED    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];    
    float VNEMAPdegree = (VNEinterpolTotal) *0.0174;
    _graphicAirspeedPointer.transform =CGAffineTransformMakeRotation(VNEMAPdegree * 2.17 ); // 2.17 is to adjust for the altimeter 
    [UIView commitAnimations];
    
}


- (void) calculateNeverExceedSpeedBetaII {
    
    float PA = vPA;
    
    float AltOben = 0;  float AltUnten =0;
    float UL = 0; float UR = 0;  float OL = 0;  float OR = 0;
    float trick =0;
    // SL - 2000
    
    //NSLog (@"PA %@ ", [ [NSString alloc] initWithFormat:@"%.1f ", PA]);
    
    //NSLog (@"OAT %@ ", [ [NSString alloc] initWithFormat:@"%.1f ", OAT]);
    
    
    if (PA < 0) {
        PA = 0;
    }
    
    
    if (PA >=-1000  & PA < 2000  & OAT >= -20 & OAT < -10)        {OL = 102; OR = 102;  UL = 102; UR = 102; AltOben = 0; AltUnten = 2000; trick = -20;}
    if (PA >=0  & PA < 2000  & OAT >= -10 & OAT < 0)          {OL = 102; OR = 102;  UL = 102; UR = 102; AltOben = 0; AltUnten = 2000; trick = -10;}
    if (PA >=0  & PA < 2000  & OAT >= 0 & OAT < 10)           {OL = 102; OR = 102;  UL = 102; UR = 102; AltOben = 0; AltUnten = 2000; trick = 0;}
    if (PA >=0  & PA < 2000  & OAT >= 10 & OAT < 20)          {OL = 102; OR = 102;  UL = 102; UR = 102; AltOben = 0; AltUnten = 2000; trick = 10;}
    if (PA >=0  & PA < 2000  & OAT >= 20 & OAT < 30)          {OL = 102; OR = 102;  UL = 102; UR = 99; AltOben = 0; AltUnten = 2000; trick = 20;}
    if (PA >=0  & PA < 2000  & OAT >= 30 & OAT < 41)          {OL = 102; OR = 102;  UL = 99; UR = 96; AltOben = 0; AltUnten = 2000; trick = 30;}
    if (PA >=0  & PA < 2000  & OAT >= 40 & OAT < 41)          {OL = 102; OR = 102;  UL = 96; UR = 96; AltOben = 0; AltUnten = 2000; trick = 40;}
    
    
    // 2000 - 4000
    
    if (PA >=2000  & PA < 4000  & OAT >= -20 & OAT < -10)        {OL = 102; OR = 102;  UL = 102; UR = 102; AltOben = 2000; AltUnten = 4000; trick = -20;}
    if (PA >=2000  & PA < 4000  & OAT >= -10 & OAT < 0)          {OL = 102; OR = 102;  UL = 102; UR = 102; AltOben = 2000; AltUnten = 4000; trick = -10;}
    if (PA >=2000  & PA < 4000  & OAT >= 0 & OAT < 10)           {OL = 102; OR = 102;  UL = 102; UR = 98; AltOben = 2000; AltUnten = 4000; trick = 0;}
    if (PA >=2000  & PA < 4000  & OAT >= 10 & OAT < 20)          {OL = 102; OR = 102;  UL = 98; UR = 94; AltOben = 2000; AltUnten = 4000; trick = 10;}
    if (PA >=2000  & PA < 4000  & OAT >= 20 & OAT < 30)          {OL = 102; OR = 99;  UL = 94; UR = 91; AltOben = 2000; AltUnten = 4000; trick = 20;}
    if (PA >=2000  & PA < 4000  & OAT >= 30 & OAT < 41)          {OL = 99; OR = 96;  UL = 91; UR = 87; AltOben = 2000; AltUnten = 4000; trick = 30;}
    if (PA >=2000  & PA < 4000  & OAT >= 40 & OAT < 41)          {OL = 96; OR = 96;  UL = 87; UR = 87; AltOben = 2000; AltUnten = 4000; trick = 40;}
    
    
    
    // 4000 - 6000
    
    if (PA >=4000  & PA < 6000  & OAT >= -20 & OAT < -10)        {OL = 102; OR = 102;  UL = 102; UR = 98; AltOben = 4000; AltUnten = 6000; trick = -20;}
    if (PA >=4000  & PA < 6000  & OAT >= -10 & OAT < 0)          {OL = 102; OR = 102;  UL = 98; UR = 94; AltOben = 4000; AltUnten = 6000; trick = -10;}
    if (PA >=4000  & PA < 6000  & OAT >= 0 & OAT < 10)           {OL = 102; OR = 98;  UL = 94; UR = 90; AltOben = 4000; AltUnten = 6000; trick = 0;}
    
    if (PA >=4000  & PA < 6000  & OAT >= 10 & OAT < 20)          {OL = 98; OR = 94;  UL = 90; UR = 87; AltOben = 4000; AltUnten = 6000; trick = 10;}
    if (PA >=4000  & PA < 6000  & OAT >= 20 & OAT < 30)          {OL = 94; OR = 91;  UL = 87; UR = 82; AltOben = 4000; AltUnten = 6000; trick = 20;}
    if (PA >=4000  & PA < 6000  & OAT >= 30 & OAT < 41)          {OL = 91; OR = 87;  UL = 82; UR = 77; AltOben = 4000; AltUnten = 6000; trick = 30;}
    if (PA >=4000  & PA < 6000  & OAT >= 40 & OAT < 41)          {OL = 87; OR = 87;  UL = 77; UR = 77; AltOben = 4000; AltUnten = 6000; trick = 40;}
    
    
    
    // 6000 - 8000
    if (PA >=6000  & PA < 8000  & OAT >= -20 & OAT < -10)        {OL = 102; OR = 98;  UL = 94; UR = 90; AltOben = 6000; AltUnten = 8000; trick = -20;}
    if (PA >=6000  & PA < 8000  & OAT >= -10 & OAT < 0)          {OL = 98; OR = 94;  UL = 90; UR = 86; AltOben = 6000; AltUnten = 8000; trick = -10;}
    if (PA >=6000  & PA < 8000  & OAT >= 0 & OAT < 10)           {OL = 94; OR = 90;  UL = 86; UR = 80; AltOben = 6000; AltUnten = 8000; trick = 0;}
    if (PA >=6000  & PA < 8000  & OAT >= 10 & OAT < 20)          {OL = 90; OR = 87;  UL = 80; UR = 75; AltOben = 6000; AltUnten = 8000; trick = 10;}
    if (PA >=6000  & PA < 8000  & OAT >= 20 & OAT < 30)          {OL = 87; OR = 82;  UL = 75; UR = 69; AltOben = 6000; AltUnten = 8000; trick = 20;}
    if (PA >=6000  & PA < 8000  & OAT >= 30 & OAT < 41)          {OL = 82; OR = 77;  UL = 69; UR = 64; AltOben = 6000; AltUnten = 8000; trick = 30;}
    if (PA >=6000  & PA < 8000  & OAT >= 40 & OAT < 41)          {OL = 77; OR = 77;  UL = 64; UR = 64; AltOben = 6000; AltUnten = 8000; trick = 40;}
    
    // 8000 - 10000
    
    if (PA >=8000  & PA < 10000  & OAT >= -20 & OAT < -10)        {OL = 94; OR = 90;  UL = 86; UR = 80; AltOben = 8000; AltUnten = 10000; trick = -20;}
    if (PA >=8000  & PA < 10000  & OAT >= -10 & OAT < 0)          {OL = 90; OR = 86;  UL = 80; UR = 74; AltOben = 8000; AltUnten = 10000; trick = -10;}
    if (PA >=8000  & PA < 10000  & OAT >= 0 & OAT < 10)           {OL = 86; OR = 80;  UL = 74; UR = 68; AltOben = 8000; AltUnten = 10000; trick = 0;}
    if (PA >=8000  & PA < 10000  & OAT >= 10 & OAT < 20)          {OL = 80; OR = 75;  UL = 68; UR = 62; AltOben = 8000; AltUnten = 10000; trick = 10;}
    if (PA >=8000  & PA < 10000  & OAT >= 20 & OAT < 30)          {OL = 75; OR = 69;  UL = 62; UR = 57; AltOben = 8000; AltUnten = 10000; trick = 20;}
    
    
    // abstufung 8000
    if (PA >=8000  & PA < 8001  & OAT == 30)                     {OL = 69; OR = 69;    UL = 57; UR = 57; AltOben = 8000; AltUnten = 10000; trick = 30;}
    if (PA >=8000  & PA < 8001  & OAT > 30 & OAT < 41)           {OL = 69; OR = 64;    UL = 69; UR = 64; AltOben = 8000; AltUnten = 10000; trick = 30;}
    if (PA >=8000  & PA < 8001  & OAT >= 40 & OAT < 41)          {OL = 64; OR = 64;    UL = 64; UR = 64; AltOben = 8000; AltUnten = 10000; trick = 40;}
    
    if (PA >=8001  & OAT >= 30 )        {trick = 100;}
    
    // 10000 - 12000
    
    
    if (PA >=10000  & PA < 12000  & OAT >= -20 & OAT < -10)      {OL = 86; OR = 80;  UL = 74; UR = 67; AltOben = 10000; AltUnten = 12000; trick = -20;}
    if (PA >=10000  & PA < 12000  & OAT >= -10 & OAT < 0)        {OL = 80; OR = 74;  UL = 67; UR = 61; AltOben = 10000; AltUnten = 12000; trick = -10;}
    
    
    // Abstufung 10000 bei 0 Grad
    
    if (PA >=10000  & PA < 12000  & OAT == 0  )                  {OL = 74; OR = 74;  UL =61; UR = 61; AltOben = 10000; AltUnten = 12000; trick = 0;}
    
    if (PA >=10000  & PA < 10001  & OAT >= 0 & OAT < 10)          {OL = 74; OR = 68;  UL = 74; UR = 68; AltOben = 10000; AltUnten = 12000; trick = 0;}
    if (PA >=10000  & PA < 10001  & OAT >= 10 & OAT < 20)          {OL = 68; OR = 62;  UL = 68; UR = 62; AltOben = 10000; AltUnten = 12000; trick = 10;}
    if (PA >=10000  & PA < 10001  & OAT >= 20 & OAT < 30)          {OL = 62; OR = 57;  UL = 62; UR = 57; AltOben = 10000; AltUnten = 12000; trick = 20;}
    
    if (PA >=10000  & PA < 10001  & OAT ==30)                    {OL = 57; OR = 57;  UL =57; UR = 57; AltOben = 10000; AltUnten = 12000; trick = 30;}
    
    if (PA >=10001  & OAT >= 1 )        {trick = 100;}
    if (PA ==10000  & OAT > 30 )        {trick = 100;}
    
    
    // 12000 - 14000
    
    
    // Abstufung 12000
    if (PA >=12000  & PA < 14000  & OAT == -20)                      {OL = 74; OR = 74;  UL = 61; UR = 61; AltOben = 12000; AltUnten = 14000; trick = -20;}
    if (PA >=12000  & PA < 12001  & OAT >= -20 & OAT < -10)          {OL = 74; OR = 67;  UL = 74; UR = 67; AltOben = 12000; AltUnten = 14000; trick = -20;}
    if (PA >=12000  & PA < 12001  & OAT >= -10 & OAT < 0)            {OL = 67; OR = 61;  UL = 67; UR = 61; AltOben = 12000; AltUnten = 14000; trick = -10;}
    if (PA >=12000  & PA < 12001  & OAT == 0)                        {OL = 61; OR = 61;  UL = 61; UR = 61; AltOben = 12000; AltUnten = 14000; trick = 0;}
    
    if (PA >=12001  & OAT > -20 )      {trick = 100;}
    if (PA ==12000  & OAT > 0 )        {trick = 100;}
    
    //14000
    
    
    if (PA == 14000  & OAT == -20)                                   {OL = 61; OR = 61;  UL = 61; UR = 61; AltOben = 14000; AltUnten = 16000; trick = -30;}
    
    if (PA == 14000 & OAT >-20)     {trick = 100;}
    
    if (PA > 14000 )                {trick = 100;}                                 
    
    
    
    
    
    // interpolation
    float VNEBetaIIOben = ( ( (OR-OL)/10 ) * (OAT - trick) ) + OL;
    float VNEBetaIIUnten = ( ( (UR-UL)/10 ) * (OAT - trick) ) + UL;
    
    float VNEBetaIIAlt = ((VNEBetaIIOben - VNEBetaIIUnten)/2000)* (PA-AltOben);
    
    
    //NSLog (@"VNEBetaIItotal %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", VNEBetaIItotal]);
    
    
    float VNEBetaIItotal = VNEBetaIIOben - VNEBetaIIAlt;
    
    //NSLog (@"VNEBetaIItotal %@ ", [ [NSString alloc] initWithFormat:@"%.0f ", VNEBetaIItotal]);
    
    if (trick == 130) {
        VNEBetaIItotal = 102;
    }
    
    VNEinterpolTotal =  VNEBetaIItotal;
     
    
    // NEEDLE AIRSPEED    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5]; 
     float airspeedGrad = ( ((VNEinterpolTotal - 60) *4.5 ) + 129.5 ) *0.0174;
    
    if (trick == 100) {
        airspeedGrad = 0;
        
        _labelIASWarning.hidden = NO;
        _labelIASWarning.text = @"NO FLIGHT";
        
        
    }else{
        _labelIASWarning.text = @"-";
        
    }
    
    _graphicAirspeedPointer.transform =CGAffineTransformMakeRotation(airspeedGrad );    
    [UIView commitAnimations];
    
 
    
}


- (void) calcMAP_BetaII {
    
    vPA = Hp;
    
    subtractInches = 0.9;
    
    _labelMinusInches.text = @"-0.9\"";
    
    // calc MCP  ********************************************************************************************************************************************
    
    
    [self calcMAP_Chart_BetaII];
    
    
    
    if (MAPResult > 24.5) {
        MAPResult = 24.5;
    }
    
    if (MAPResult < 20.6) {
        MAPResult = 20.6;
    }
    
    
    // hier wurde gerade MCP berechnet!    
    // Achtung: Wenn MCP auf die FULL THROTTLE LINE stoesst, dann ist die FULL THROTTLE LINE = MCP!!
    
    
    maxContinuousPower = MAPResult - subtractInches;    
    fiveMinuteTakeoffPower = MAPResult;    
    float maxContinuousPower_forLabel = maxContinuousPower;    
    float fiveMinuteTakeoffPower_forLabel = fiveMinuteTakeoffPower;
    
    
  
    
    
    
    fiveMinuteTakeoffPowerResult = fiveMinuteTakeoffPower;
    
    maxContinuousPowerResult = maxContinuousPower;
    
    // full throttle line
    
    CUT= (6.70619615053682E-22 * powf(vPA, 2) )   + ( -0.000800000000000009  * vPA ) + 27.3   ;
        
    
    if (CUT < 20.6) {
        CUT = 20.6;
    }
    
    float CUT_forLabel  = CUT;
    
    
    if (_robinsonSwitchCarbHeat.on == YES) {
        
        maxContinuousPower_forLabel = maxContinuousPower + 1.5;
        maxContinuousPowerResult  = maxContinuousPower + 1.5;
        
        fiveMinuteTakeoffPower_forLabel = fiveMinuteTakeoffPower + 1.5;
        fiveMinuteTakeoffPowerResult  = fiveMinuteTakeoffPower + 1.5 ;
        
        CUT_forLabel  = CUT + 1.5;
        
        
    }
    
    _labelMCP.textColor = [UIColor whiteColor];
    _labelMAPmax.textColor = [UIColor whiteColor];
    
    
    // maxLine    
    
    float maxLine = (-2.06332533013206E-08 * powf(vPA, 2) )   + ( -0.000525397659063624  * vPA ) + 27.3534288715486   ;
    
    
    
    if (fiveMinuteTakeoffPower < CUT) {    
       
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.2f inHg", maxContinuousPower_forLabel];        
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"%.2f inHg", fiveMinuteTakeoffPower_forLabel];        
        redCrossYValue = fiveMinuteTakeoffPower;
    }
    
    if (fiveMinuteTakeoffPower >= CUT) {
       
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.2f inHg", maxContinuousPower_forLabel ];  
        _labelMAPmax.text =  [ [NSString alloc] initWithFormat:@"%.2f inHg (FULL THROTTLE)", CUT_forLabel];
        _labelMAPmax.textColor = [UIColor orangeColor];
        redCrossYValue = CUT;
        
    }
    
    
    if (fiveMinuteTakeoffPower > maxLine) {        
        _labelMCP.text =  [ [NSString alloc] initWithFormat:@"%.2f inHg (FULL THROTTLE)", maxContinuousPower_forLabel ];        
        _labelMCP.textColor = [UIColor orangeColor];
    }
    
    [self animateCrossRed_BetaII];    
    
    
    
    
    // NEEDLE MAP
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    
    float MAPdegree = ((maxContinuousPower_forLabel) -20) *0.0174;
    
    _graphicMAPneedle.transform =CGAffineTransformMakeRotation(MAPdegree * 8 );
    
    
    
    
    
    
    [UIView commitAnimations];
    
    
    
}


- (void) animateCrossRed_BetaII {
    
    
    float maxPA = vPA;
    
    //NSLog(@"maxPA %.0f", maxPA);
    
    if (maxPA >10000) {
        maxPA = 10000;
    }
    
    if (maxPA < 0) {
        maxPA = 0;
    }
    
    // convert actual values in x y coordinates for display on iPad    
    // X Position
    
    
    float OGEscaleXstartPixel  = 105;   //left corner of graphic
    float OGEscaleXendPixel    = 605; // right corner    
    
    float OGEscaleXstartValue  = 0; // left start value
    float OGEscaleXendValue    = 10000;
    
    float OGEpixelDiffx = OGEscaleXendPixel - OGEscaleXstartPixel;
    float OGEvalueDiffx = OGEscaleXendValue - OGEscaleXstartValue;
    float OGEpixStepx = OGEpixelDiffx/OGEvalueDiffx ;    
    float OGExwert = maxPA - OGEscaleXstartValue; // wert ist null wenn ganz links auf Achse 2400-1500 = 900    
    float OGExposition = OGEscaleXstartPixel + (OGEpixStepx* OGExwert) ;
    
    
    // Y Position
    float OGEscaleYstartPixel  = 360; // bottom of graphic
    float OGEscaleYendPixel    = 91; // top
    
    
    float OGEscaleYstartValue  = 20.6; // bottom start value
    float OGEscaleYendValue    = 24.5; // top value
    
    float diffY = OGEscaleYendValue - OGEscaleYstartValue;
    
    float OGEpixelDiffy = OGEscaleYendPixel - OGEscaleYstartPixel;
    float OGEvalueDiffy = OGEscaleYendValue - OGEscaleYstartValue;
    float OGEpixStepy = OGEpixelDiffy/OGEvalueDiffy ; //
    
    float OGEywert =   fiveMinuteTakeoffPower - OGEscaleYstartValue;    
    float OGEywertCross =   redCrossYValue - OGEscaleYstartValue;    
    float OGEyposition = OGEscaleYstartPixel + (OGEpixStepy* OGEywert) ;    
    float OGEypositionCross = OGEscaleYstartPixel + (OGEpixStepy* OGEywertCross);  
    float OGEywertBlue =   (fiveMinuteTakeoffPower - subtractInches) - OGEscaleYstartValue;    
    float OGEypositionCrossBlue = OGEscaleYstartPixel + (OGEpixStepy* OGEywertBlue) ;
    
    
    _crossMCP.center = CGPointMake( OGExposition, OGEypositionCross);
    
    
    
    // BAR vertical    
    _barMCPVerticalRED.center = CGPointMake( OGExposition, OGEscaleYstartPixel); // BAR Pressue Alt  moving LEFT RIGHT   
    _barMCPVerticalRED.layer.anchorPoint = CGPointMake(0.5, 1); // 0.5 = mitte    -0.5 + unterkante = oberkante // 6.89 = 100%
    
    float heightRed = (27.1 / diffY ) * ( fiveMinuteTakeoffPower - OGEscaleYstartValue);    
    _barMCPVerticalRED.layer.transform = CATransform3DMakeScale(1, heightRed, 0); // breit / hoch 20.5 = 800
    
    
    // QUERBALKEN    
    _barQuerBlue.center = CGPointMake( OGEscaleXstartPixel, OGEyposition );    
    _barQuerBlue.layer.anchorPoint = CGPointMake(0, 0.5);    
    float balkenlaenge =  (50.1/OGEscaleXendValue) * maxPA;    
    _barQuerBlue.layer.transform = CATransform3DMakeScale(balkenlaenge, 1.0, 0.0);    
    
    
    
    
    // BAR BLUE VERTICAL    
    _barMCPVerticalBlue.center = CGPointMake( OGEscaleXstartPixel, OGEyposition); // BAR Pressue Alt  moving LEFT RIGHT 
    _barMCPVerticalBlue.layer.anchorPoint = CGPointMake(0.5, 1); // 0.5 = mitte    -0.5 + unterkante = oberkante // 6.89 = 100%
    float heightBlue = -1 * ((27.1 / diffY ) * subtractInches);    
    _barMCPVerticalBlue.layer.transform = CATransform3DMakeScale(1, heightBlue, 0); // breit / hoch 20.5 = 800
    
    // cross Blue    
    _crossMCP2.center = CGPointMake( OGEscaleXstartPixel, OGEypositionCrossBlue);    
    
    // label    
    _labelMinusInches.center = CGPointMake( OGEscaleXstartPixel + 40, OGEypositionCrossBlue - 35);
    
    
    
    if (fiveMinuteTakeoffPower > CUT) {
        
        _barQuerBlue.hidden = NO;
        
    } else {
        
        _barQuerBlue.hidden = NO;
        
    }
    
    
    
    // QUERBALKEN BLUE
    
    _barQuerRed.center = CGPointMake( OGEscaleXstartPixel, OGEypositionCross );
    
    _barQuerRed.layer.anchorPoint = CGPointMake(0, 0.5);
    
    float balkenlaengeBlue =  (50.1/OGEscaleXendValue) * maxPA;
    
    _barQuerRed.layer.transform = CATransform3DMakeScale(balkenlaengeBlue, 1.0, 0.0);
    
    
    
    
    return;
    
    
    
}




- (void) calcMAP_Chart_BetaII {
    
     float OATNorm =  OAT; 
    
    
    
    float MAP_1 = 0, MAP_2 = 0;
    
    
    if (OATNorm >= -22 & OATNorm < 0) {
        MAP_1= (-1.87499999999997E-09 * powf(vPA, 2) )   + ( -0.000185  * vPA ) + 22.4   ; MAP_2 = (-3.12500000000052E-10 * powf(vPA, 2) )   + ( -0.00021375  * vPA ) + 22.98   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - -20)  );
        return; }    
    
    
    if (OATNorm >= 0 & OATNorm < 20) {
        MAP_1= (-3.12500000000052E-10 * powf(vPA, 2) )   + ( -0.00021375  * vPA ) + 22.98   ; MAP_2 = (3.1250000000016E-10 * powf(vPA, 2) )   + ( -0.000216250000000001  * vPA ) + 23.51   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - 0)  );
        return; }
    
    
    
    if (OATNorm >= 20 & OATNorm < 42) {
        MAP_1= (3.1250000000016E-10 * powf(vPA, 2) )   + ( -0.000216250000000001  * vPA ) + 23.51   ; MAP_2 = (1.56250000000002E-09 * powf(vPA, 2) )   + ( -0.00024375  * vPA ) + 24.15   ;
        MAPResult   = MAP_1 -   (  (MAP_1 - MAP_2) / 20  * ( OATNorm - 20)  );
        return; }
    return;
    
    
    
}






- (IBAction)robinsonActionSwitchCarbHeat:(id)sender {    
    NSString *vFlightID   = [[NSUserDefaults standardUserDefaults]  stringForKey:@"InternalFlightID"]; 
    [[NSUserDefaults standardUserDefaults]  setBool:[_robinsonSwitchCarbHeat isOn] forKey:[ [NSString alloc] initWithFormat:@"%@%@", vFlightID, @"_robinsonSwitchCarbHeat" ]];    
    ViewController *parent = (ViewController *)self.parentViewController;
    [parent MainRoutine];
}

- (IBAction)actionSwitchOverrideCruiseInput:(id)sender {
    [self computeCruiseUniversal];

}
@end
