//
//  importPerformanceData.m
//  Golem
//
//  Created by Claus Richter on 4/10/18.
//
//

#import "importPerformanceData.h"

#import "ViewController.h"

#import "NSURLSession+SynchronousTask.h"

//#define NSLog(...)

@interface importPerformanceData ()

@end

@implementation importPerformanceData {
    
    ViewController* mainControllerClass_;
}



/*
- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];
}
 */


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
     mainControllerClass_ = [[ViewController alloc] init];
     [self addChildViewController:mainControllerClass_]; 
     [mainControllerClass_ didMoveToParentViewController:self];
    
    
    
    
    
    
}

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


// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                       @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                       @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@       NEVER  NSLOG  our URLs          @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                       @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                       @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@



- (void) loadACThumbsAndData {

 
    NSLog(@"loadACThumbsAndData in performance class");
    
  
        
        //NSString *previousListVersion = [[NSUserDefaults standardUserDefaults]  stringForKey:@"listVersion"];
        int flagLoadThumbnails = 1;
        
        NSURL *URL;
        NSStringEncoding encoding;
        NSError *error;
                
        NSString *imageDataUrl;
        NSData *imageData;
        UIImage *image;
        NSData *imageDataPNG;
        
        // get list of all available aircraft from backend
       
        
        NSString *baseDataURL = @"https://www.gyronimo.online/0aaGyroData/allAvailableAircraft/";        
        NSString *urlWithConfigID =  @"https://www.gyronimoserver.com/api/flightpadaircraftlist/";
        NSURL *url = [NSURL URLWithString:urlWithConfigID];
        //NSError *error = nil;
        NSURLResponse *response = nil;
        NSData *data = [[NSURLSession sharedSession] sendSynchronousDataTaskWithURL:url returningResponse:&response error:&error];
        NSDictionary *dictionaryAll = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 
        
        NSArray *dictArray = [dictionaryAll valueForKey:@"data"];
        //NSLog(@"dictArray: %@", dictArray);  
        
        
        NSString *allText = @"";
        allText = [allText stringByAppendingString: @"All Available Aircraft"];
        allText = [allText stringByAppendingString: @"|version =^8"];
        
        for(int i =0; i<dictArray.count; i++) {  
            
            NSDictionary *dictHeader = [dictArray objectAtIndex:i];
            //NSLog(@"dictHeader: %@", dictHeader);  
            
            allText = [allText stringByAppendingString: @"|"];
            
            NSString *addString = [ [NSString alloc] initWithFormat:@"%@^",  [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"type"]] ];  
            
            allText = [allText stringByAppendingString: addString];
            
            NSString *headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"manufacturer"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];                
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"model"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"variant"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"callsign"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"unit"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"BEW"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];        
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"moment_long"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];        
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"moment_lat"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"MTOW"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];        
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"max_fuel"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];        
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"description_line1"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"description_line2"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"category"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];        
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"version"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ]; 
            allText = [allText stringByAppendingString: addString];            
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"image_name"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];         
            allText = [allText stringByAppendingString: addString];
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"id_backend"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"display_manufacturer"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];
            allText = [allText stringByAppendingString: addString];
            
            
            headerString = [[NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"display_name"]];
            if ([headerString isEqualToString:@"<null>"]) { headerString = @"";}
            addString = [ [NSString alloc] initWithFormat:@"%@^",  headerString ];
            allText = [allText stringByAppendingString: addString];
            
            
        }
        
        NSString *importedText = allText;
        [[NSUserDefaults standardUserDefaults]  setObject:importedText  forKey:@"allAvailableAircraftText"];         
        //NSLog(@"allText: %@", allText);  
        //make array to load aircraft images:  
        NSMutableDictionary *ACthumbnailDictionary = [[NSMutableDictionary alloc] init];
        NSMutableArray *ACimages = [[NSMutableArray alloc] init];         
        NSString *allAvailText = importedText;
        NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
        NSArray *components = [allAvailText componentsSeparatedByCharactersInSet:charSet];
        //NSLog(@"components %@", components);     
        
        
        for(int i =0; i<components.count; i++) {        
            NSArray* componentItems  = [[components objectAtIndex:i] componentsSeparatedByString:@"^"];        
            if (componentItems.count > 1) {  
                
                if ([[componentItems objectAtIndex:0] isEqualToString:@"Heli"] || [[componentItems objectAtIndex:0] isEqualToString:@"FixedWing"]) { 
                    
                    if (![ACimages containsObject:[componentItems objectAtIndex:15]  ]) {                         
                        if ([[componentItems objectAtIndex:15] length] > 1 ) {
                            [ACimages addObject: [componentItems objectAtIndex:15] ];    
                            //NSLog(@"loading  ACimage: %@", [componentItems objectAtIndex:15]);                             
                            //gyronimo.online/0aaGyroData/allAvailableAircraft/thumb_DA42.png
                            //gyronimo.online/0aaGyroData/allAvailableAircraft/thumb_C172
                            //load ac images                             
                            NSString *imageName =  [componentItems objectAtIndex:15];
                            //NSLog(@"1 imageName: %@", imageName);  
                            imageName  = [ imageName stringByReplacingOccurrencesOfString:@" " withString:@""];
                            imageName  = [ imageName stringByReplacingOccurrencesOfString:@"\n" withString:@""];   
                            //NSLog(@"2 imageName: %@", imageName);
                            NSString *imageDiskName = [ [NSString alloc] initWithFormat:@"thumb_%@.jpg", imageName]; 
                            NSString *imageDiskName2 = [ [NSString alloc] initWithFormat:@"thumb_%@", imageName];
                            //NSLog(@"3 imageName: %@", imageDiskName);
                            UIImage *tempImage;
                            NSString* myImagePath = [[NSBundle mainBundle] pathForResource:imageDiskName2 ofType:@"jpg"];                            
                            if (myImagePath != nil) {
                                tempImage = [UIImage imageNamed:imageDiskName];                                
                                //NSLog(@"i have this image on file %@", imageDiskName );                                 
                                ACthumbnailDictionary[imageDiskName] = @"onFile";
                            }else{
                                imageDataUrl = [ [NSString alloc] initWithFormat:@"%@thumb_%@.jpg", baseDataURL, imageName];                             
                                //NSLog(@"need to load imageDataUrl %@", imageDataUrl );
                                //NSLog(@"pic not on file: %@", imageName );
                                NSURL *imageURL = [NSURL URLWithString: imageDataUrl ];
                                //NSLog(@"imageURL %@", imageURL );                                
                                imageData = [NSData dataWithContentsOfURL:imageURL];
                                image = [UIImage imageWithData:imageData];
                                imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];                                
                                if (image) {
                                    NSString *imageToSave = [NSString stringWithFormat:@"thumb_%@", imageName ];
                                    ACthumbnailDictionary[imageToSave] = imageData ;
                                    //NSLog(@"saving image -%@-", imageToSave);
                                }else{
                                    NSString *imageToSave = [NSString stringWithFormat:@"thumb_%@", imageName ];
                                    ACthumbnailDictionary[imageToSave] = imageData ;
                                    //NSLog(@"!!!! NO PERF IMAGE for -%@- ", imageToSave);
                                }                                
                            }
                        }                           
                    }
                }//end            
            }
        }
        
        if (flagLoadThumbnails == 1) {
            [[NSUserDefaults standardUserDefaults]  setObject: ACthumbnailDictionary  forKey:@"ACthumbnailDictionary"];
        }        
        //NSLog(@"ACthumbnailDictionary %@", ACthumbnailDictionary);
        
}



- (void) loadAvailableACTypesArrayFromDisk {
    NSMutableArray *availableACTypesArray = [[NSMutableArray alloc] init];
    customerDataURL = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerDataURL"]; // includes customer name
    baseDataURL = [[NSUserDefaults standardUserDefaults]  stringForKey: @"baseDataURL"]; // is root URL to all data perfPool and customer folders
    NSString *availableACTypesURL = @"customerData";
    NSString *path = [[NSBundle mainBundle] pathForResource:availableACTypesURL ofType:@"txt"];
    importedText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@" " withString:@""];
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *components = [importedText componentsSeparatedByCharactersInSet:charSet];
    
    for(int i =0; i<components.count; i++) {
        NSArray* componentItems  = [[components objectAtIndex:i] componentsSeparatedByString:@","];
        if (componentItems.count > 1) {
            if (componentItems.count >=4) {
                ACCategory = [componentItems objectAtIndex:0];
                ACmanufacturer = [componentItems objectAtIndex:1];
                AC_Type = [componentItems objectAtIndex:2];
                ACVariant = [componentItems objectAtIndex:3];
                [availableACTypesArray addObject:AC_Type];
            } 
        }
    }
    
    [[NSUserDefaults standardUserDefaults]  setObject:availableACTypesArray  forKey:@"availableACTypesArray" ];
    
    [[NSUserDefaults standardUserDefaults]  setObject:importedText  forKey:@"importedTextCustomerData" ];
    
    NSLog(@"writing importedTextCustomerData from disk %@", importedText);
    
}

- (void) loadAvailableACTypesArrayFromFleetControl {
    
    
  
    
    
    
     NSMutableArray *availableACTypesArray = [[NSMutableArray alloc] init];
    customerDataURL = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerDataURL"]; // includes customer name
    baseDataURL = [[NSUserDefaults standardUserDefaults]  stringForKey: @"baseDataURL"]; // is root URL to all data perfPool and customer folders
    NSURL *URL;
    NSStringEncoding encoding;
    NSError *error;
    NSString *availableACTypesURL = [ [NSString alloc] initWithFormat:@"%@%@", customerDataURL,  @"customerData.txt" ];
    URL = [NSURL URLWithString: availableACTypesURL];
    
    NSLog(@"11availableACTypesURL  %@", availableACTypesURL);
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
    importedText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@" " withString:@""];
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *components = [importedText componentsSeparatedByCharactersInSet:charSet];
   
   
    NSLog(@"11ccomponents  %@", components);
    
    for(int i =0; i<components.count; i++) {
        
        NSArray* componentItems  = [[components objectAtIndex:i] componentsSeparatedByString:@","];
        
        if (i == 0) {
            [[NSUserDefaults standardUserDefaults]  setObject:[componentItems objectAtIndex:0]  forKey:@"dedicatedCustomerData" ];
            NSLog(@"saving dedicatedCustomerData  %@", [componentItems objectAtIndex:0]);
        }
      
        
        if (componentItems.count > 1) {
            if (componentItems.count >=4) {
                ACCategory = [componentItems objectAtIndex:0];
                ACmanufacturer = [componentItems objectAtIndex:1];
                AC_Type = [componentItems objectAtIndex:2];
                ACVariant = [componentItems objectAtIndex:3];
                [availableACTypesArray addObject:AC_Type];
            } 
        }
        
        
    }
    
    [[NSUserDefaults standardUserDefaults]  setObject:availableACTypesArray  forKey:@"availableACTypesArray" ];
    
    [[NSUserDefaults standardUserDefaults]  setObject:importedText  forKey:@"importedTextCustomerData" ];
    
    NSLog(@"writing importedTextCustomerData from FC %@", importedText);
    
}





- (void) loadPerformanceData: (NSString*)dataLocation {
    
    int flagLoadOnlyFleetACs = 0;
    
    if ([dataLocation isEqualToString:@"loadDataFromFleetControl"] ) {
        flagLoadFromFleetControl = 1;
    }else if ([dataLocation isEqualToString:@"loadDataFromFleetControl_myFleetOnly"] ) {
        flagLoadFromFleetControl = 1; flagLoadOnlyFleetACs = 1;
    }else{
        flagLoadFromFleetControl = 0;
    }
    
    NSLog(@"loadPerformanceData dataLocation: %@", dataLocation);    
    //NSLog(@"flagLoadOnlyFleetACs %d", flagLoadOnlyFleetACs);
    
    _labelLoadingData.text = @"test";
    
    customerDataURL = [[NSUserDefaults standardUserDefaults]  stringForKey: @"customerDataURL"]; // includes customer name
    baseDataURL = [[NSUserDefaults standardUserDefaults]  stringForKey: @"baseDataURL"]; // is root URL to all data perfPool and customer folders
    
    chartImagesDictionary = [[NSMutableDictionary alloc] init];
    chartImagesDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"chartImagesDictionary"] mutableCopy];
    if (chartImagesDictionary.count < 1) {
        chartImagesDictionary = [[NSMutableDictionary alloc] init];
    }
    
    
    ACimagesDictionary = [[NSMutableDictionary alloc] init];      
    ACimagesDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"ACimagesDictionary"] mutableCopy];
    if (ACimagesDictionary.count < 1) {
        ACimagesDictionary = [[NSMutableDictionary alloc] init];
    }
    
    
    // get customer data    
 
    flagWeHaveAbackendID = 0;    
    arrayDictAllAircraft = [[NSMutableArray alloc] init]; 
    arrayDictAllAircraft = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayDictAllAircraft"] mutableCopy];
    if (arrayDictAllAircraft.count < 1) {
        arrayDictAllAircraft = [[NSMutableArray alloc] init];
    }
    
   
 
    //NSLog(@"arrayDictAllAircraft %@", arrayDictAllAircraft);    
    // save availableACTypesArray    
    int flagSetDefaultAC = 0;    
    arrayACtypesToLoad = [[NSMutableArray alloc] init];  
    if (arrayACtypesToLoad.count < 1) {
        arrayACtypesToLoad = [[NSMutableArray alloc] init];
    }
    
   
    
   //NSLog(@"1performance  arrayDictAllAircraft %@", arrayDictAllAircraft);  
    
   backendDictionaryAircraftData = [[NSDictionary alloc] init];
    
   for (int i=0; i<arrayDictAllAircraft.count; i++) {
       
       flagWeHaveAbackendID = 0;
       backendID = @"";
       
       NSString *downloadStatus = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"downloadStatus"];
                
       customFilesArray = [[NSMutableArray alloc] init];
       ACCategory = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetACCategory"];       
       ACmanufacturer = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Manufacturer"];
       AC_Type = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"fleetAC_Type"];
       NSLog(@"download status for %@  = %@", AC_Type, downloadStatus);
       //NSLog(@"making  %@", AC_Type);       
       //NSLog(@"ACCategory  %@", ACCategory);       
       //NSLog(@"ACmanufacturer  %@", ACmanufacturer);
       ACVariant = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"Variant"]; 
       
       
       if ([downloadStatus isEqualToString:@"acdownloaded"] || [arrayACtypesToLoad containsObject: AC_Type]) { 
           NSLog(@"already downloaded"); 
       }else{
           if ( [[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"ACdataSource"] isEqualToString: @"backend"] ) {                   
               NSLog(@"backendid for %@ = %@", AC_Type, [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"backendID"]);     
               
               backendID = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"backendID"];           
               if (backendID.length > 0) {
                   flagWeHaveAbackendID = 1;
                   NSString *urlWithConfigID =  [ [NSString alloc] initWithFormat:@"https://www.gyronimoserver.com/api/aircraft/%@", backendID];
                   NSURL *url = [NSURL URLWithString:urlWithConfigID];
                   NSError *error = nil;
                   NSURLResponse *response = nil;
                   NSData *data = [[NSURLSession sharedSession] sendSynchronousDataTaskWithURL:url returningResponse:&response error:&error];        
                   
                   NSDictionary *dictionaryAll = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 
                   //NSLog(@"dictionaryAll: %@", dictionaryAll);  
                   backendDictionaryAircraftData = [dictionaryAll valueForKey:@"aircraft"];
                   //NSLog(@"backendDictionaryAircraftData: %@", backendDictionaryAircraftData);   
               }
           }
           
       }
       
       
       
       
       NSString *customFiles = [[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"loadedCustomFiles"];
       NSLog(@"1 customFiles  %@", customFiles);
       if (customFiles.length > 1) {
           customFiles  = [ customFiles stringByReplacingOccurrencesOfString:@" " withString:@""];
           customFiles  = [ customFiles stringByReplacingOccurrencesOfString:@"\n" withString:@""];
           NSArray* componentItemsCustomFiles  = [customFiles componentsSeparatedByString:@"+"];
           for(int i =0; i<componentItemsCustomFiles.count; i++) {
               [customFilesArray addObject:[componentItemsCustomFiles objectAtIndex:i]];
           }
           //NSLog(@"creating customFilesArray: %@", customFilesArray);
           arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@", AC_Type, @"customFilesArray" ];
           [[NSUserDefaults standardUserDefaults]  setObject:customFilesArray  forKey:arrayKey];
       }
       
      
            
       if ([downloadStatus isEqualToString:@"acdownloaded"] || [arrayACtypesToLoad containsObject: AC_Type]) { 
           NSLog(@"already downloaded"); 
       }else{
           
           if ( [[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"ACdataSource"] isEqualToString: @"FleetControl"] ) {                   
               NSLog(@"yees load this Fleet Control %@", AC_Type);               
               [arrayACtypesToLoad addObject:AC_Type];
               //NSLog(@"arrayACtypesToLoad adding %@", AC_Type);
               [self loadDataPerACtype];
               [self loadCGenvelopesPerACtype];                
           } 
           
           if ( [[[arrayDictAllAircraft objectAtIndex:i] objectForKey:@"ACdataSource"] isEqualToString: @"backend"] ) {                   
               NSLog(@"yees load this Backend %@", AC_Type);               
               [arrayACtypesToLoad addObject:AC_Type];
               //NSLog(@"arrayACtypesToLoad adding %@", AC_Type);
               [self loadDataPerACtype];
               [self loadCGenvelopesPerACtype];
               
           }
                 
           // set default aircraft
           if (flagSetDefaultAC == 0) {
               flagSetDefaultAC = 1;
               [[NSUserDefaults standardUserDefaults]  setObject:ACCategory                    forKey:@"ACCategory"];
               [[NSUserDefaults standardUserDefaults]  setObject:ACmanufacturer                forKey:@"ACmanufacturer"];
               [[NSUserDefaults standardUserDefaults]  setObject:AC_Type                       forKey:@"AC_Type"];
               [[NSUserDefaults standardUserDefaults]  setObject:ACVariant                     forKey:@"ACVariant"];               
               //NSLog(@"set default aircraft %@", AC_Type);
           }
       }
      
      
   }
    
  
    //NSLog(@"1 arrayDictAllAircraft %@", arrayDictAllAircraft);  
    
}


- (void) loadDataPerACtype {
    
    NSLog( @"loadDataPerACtype ...... %@", AC_Type );
  
    //mainControllerClass_ = [[ViewController alloc] init];
    //[mainControllerClass_ hideLoadDataFM];
    
    // !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **
    // trying to show progress but this does not change on xib and in child view
    _labelLoadingData.text = [ [NSString alloc] initWithFormat:@"loading data for aircraft: %@", AC_Type];
    // !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **   !!! ** !!! **
    
    // ****************************************************************************************************************
    //get available charts for this aircraft variant
    
    NSStringEncoding encoding;
    NSError *error;
    
    if (flagLoadFromFleetControl == 1) {        
        NSLog( @"flagLoadFromFleetControl ");              
        // load customer specific data
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@", AC_Type, @"customFilesArray" ];
        customFilesArray = [[NSMutableArray alloc] init];
        customFilesArray = [[[NSUserDefaults standardUserDefaults] objectForKey:arrayKey] mutableCopy];
        
        NSLog( @"customFilesArray %@", customFilesArray);
               
        // check if we need to load the generic file or the custom file from the customer folder
        if ([customFilesArray containsObject: @"availableCharts"]) {
            NSLog( @"loading from customerDataURL : availableCharts");
            availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@%@_%@_%@_%@_availableCharts.txt", customerDataURL, ACCategory, ACmanufacturer, AC_Type, ACVariant];
        }else{
            NSLog( @"loading from baseDataURL : availableCharts");
            availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@%@%@_%@/%@_%@_%@_%@_availableCharts.txt", baseDataURL, @"perfPool/", ACmanufacturer, AC_Type,  ACCategory, ACmanufacturer, AC_Type, ACVariant];
        }
        
        NSLog( @"availableChartsNameUrl %@", availableChartsNameUrl);
        
        
        NSURL *URL = [NSURL URLWithString: availableChartsNameUrl];
        [[NSURLCache sharedURLCache] removeAllCachedResponses];
        [[NSURLCache sharedURLCache] setDiskCapacity:0];
        [[NSURLCache sharedURLCache] setMemoryCapacity:0];
        
        if (flagWeHaveAbackendID == 1) {            
            importedText =  [ [NSString alloc] initWithFormat:@"%@", [backendDictionaryAircraftData valueForKey: @"available_charts"]];
            if (importedText.length < 2) {
                importedText = @"***";
            }
        }else{
           importedText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error]; 
        }
        
      
        if ([customFilesArray containsObject: @"penaltyData"]) {          
            availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@%@_%@_%@_%@_penaltyData.txt", customerDataURL, ACCategory, ACmanufacturer, AC_Type, ACVariant];
            NSLog( @"penaltyUrl %@", availableChartsNameUrl);
            NSURL *URL = [NSURL URLWithString: availableChartsNameUrl];
            [[NSURLCache sharedURLCache] removeAllCachedResponses];
            [[NSURLCache sharedURLCache] setDiskCapacity:0];
            [[NSURLCache sharedURLCache] setMemoryCapacity:0];
            NSString *penaltyText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error]; 
            NSLog( @"penaltyText %@", penaltyText);
            arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"penaltyData" ]; //fixedWingSetupText
            NSLog( @"saving array key penaltyText %@", arrayKey);
            [[NSUserDefaults standardUserDefaults]  setObject:penaltyText forKey:arrayKey ];
            
        }
        
        
        //NSLog( @"availableChartsNameUrl %@", availableChartsNameUrl);
        //NSLog( @"importedText %@", importedText);
        
        
    }else{
        availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_availableCharts", ACCategory, ACmanufacturer, AC_Type, ACVariant];        
        
         //NSLog( @"availableChartsNameUrl %@", availableChartsNameUrl);
        NSString *path = [[NSBundle mainBundle] pathForResource:availableChartsNameUrl ofType:@"txt"];
        //NSLog( @"path %@", path);
        importedText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    }
    
    NSLog( @"importedText _availableCharts %@", importedText);
    if (importedText.length < 1) {        
        NSLog( @"!!!! missing availableCharts URL: for %@ ",availableChartsNameUrl);        
    }
    
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@" " withString:@""];
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    NSCharacterSet* charSet0 = [NSCharacterSet characterSetWithCharactersInString:@"{"];
    NSArray *components0 = [importedText componentsSeparatedByCharactersInSet:charSet0];
    NSLog( @"components0 %@", components0);
    NSLog( @"omponents0.count %lu", (unsigned long)components0.count);
    NSString *fixedWingSetupText = @"";
    if (components0.count > 1) {
        fixedWingSetupText = [components0 objectAtIndex:1];
    }
    
    arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"fixedWingSetupText" ];
    [[NSUserDefaults standardUserDefaults]  setObject:fixedWingSetupText       forKey:arrayKey ];
    NSLog( @"saving  fixedWingSetupText -%@- ", fixedWingSetupText);
    
    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *components = [importedText componentsSeparatedByCharactersInSet:charSet];
    
    NSLog( @"components %@", components);
    availableCharts = [[NSMutableArray alloc] init];
    
    // write only chart names in array availableCharts
    for(int i =0; i<components.count; i++) {
        if ([ [components objectAtIndex:i] rangeOfString:@"***"].location != NSNotFound    ) {
            //NSLog( @"1 components  breaking %@", [components objectAtIndex:i]);
            break;
        }
        if ([ [components objectAtIndex:i] rangeOfString:@"setupIfo"].location != NSNotFound    ) {
            NSLog( @"setupIfo %@", [components objectAtIndex:i]);
            
        }else{
            NSArray* componentItems  = [[components objectAtIndex:i] componentsSeparatedByString:@","];
            //NSLog( @"componentItems %@", componentItems);
            if (componentItems.count > 1) {
                //NSLog( @"availableChart: %@", [componentItems objectAtIndex:0] );
                [availableCharts addObject: [componentItems objectAtIndex:0] ];
            }
            
        }
        
        
    }
    //NSLog( @"availableCharts  %@", availableCharts);
    //save array available Charts
    arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@_%@_%@_%@", ACCategory, ACmanufacturer, AC_Type, ACVariant, @"availableCharts" ];
    [[NSUserDefaults standardUserDefaults]  setObject:availableCharts       forKey:arrayKey ];
    NSLog( @"save array available Charts %@", availableCharts);
    NSLog( @"1arrayKey %@", arrayKey);
    
    // ****************************************************************************************************************
    // *******************f*********************************************************************************************
    // ****************************************************************************************************************
    
    //save infoFilesGeneral for each chart
    
    infoFilesGeneral = [[NSMutableArray alloc] init];
    //NSLog(@"components.count %lu ", (unsigned long)components.count);
    
    NSString *acManufacturerForPerfPool;
    NSString *acTypeorPerfPool;

    
    for(int i =0; i<components.count; i++) {
        
        if ([ [components objectAtIndex:i] rangeOfString:@"***"].location != NSNotFound    ) {
            //NSLog( @"2 components  breaking %@", [components objectAtIndex:i]);
            break;
        }
        
       
        NSLog(@"save infoFilesGeneral for each chart %d ", i);
        [infoFilesGeneral removeAllObjects];
        NSArray* componentItems  = [[components objectAtIndex:i] componentsSeparatedByString:@","];
        if (componentItems.count > 1) {
            for(int i2 =0; i2<componentItems.count; i2++) {
                NSString *testString = [componentItems objectAtIndex:i2];
                if ([ testString rangeOfString:@"_part1"].location != NSNotFound    ) {
                    testString =  [ testString stringByReplacingOccurrencesOfString:@"_part1" withString:@""];
                }
                [infoFilesGeneral addObject: testString ];
                chartNameForThisInfoFile = [infoFilesGeneral objectAtIndex:0];
                //NSLog( @"infoFilesGeneral: %@", [infoFilesGeneral objectAtIndex:0] );
            }
            
            //NSLog( @"infoFilesGeneral: %@", infoFilesGeneral );
            //NSLog( @"[infoFilesGeneral objectAtIndex:0]: %@", [infoFilesGeneral objectAtIndex:0] );
            //NSLog( @"chartNameForThisInfoFile: %@", chartNameForThisInfoFile );
            
            
            componentItems  = [[infoFilesGeneral objectAtIndex:0]  componentsSeparatedByString:@"_"];
            if (componentItems.count > 1) {
                acManufacturerForPerfPool = [componentItems objectAtIndex:1];
                acTypeorPerfPool = [componentItems objectAtIndex:2];
                
            }
            
            //NSLog( @"acManufacturerForPerfPool: %@", acManufacturerForPerfPool );
            //NSLog( @"acTypeorPerfPool: %@", acTypeorPerfPool );
            
            // import chart images
            if ([chartNameForThisInfoFile rangeOfString:@"noChart"].location == NSNotFound) {
                NSString *imageDataUrl;
                NSData *imageData;
                UIImage *image;
                NSData *imageDataPNG;
                
                if (flagLoadFromFleetControl == 1) {
                    // import from Fleet Control
                    imageDataUrl = [ [NSString alloc] initWithFormat:@"%@%@%@_%@/%@.png", baseDataURL, @"perfPool/", acManufacturerForPerfPool, acTypeorPerfPool,  chartNameForThisInfoFile ];
                    NSURL *imageURL = [NSURL URLWithString: imageDataUrl ];
                    imageData = [NSData dataWithContentsOfURL:imageURL];
                    image = [UIImage imageWithData:imageData];
                    imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];
                    //NSLog(@"imageDataUrl %@", imageDataUrl);
                }else{
                    // load from disk
                    NSString *imageDataPath;
                    imageDataPath = [ [NSString alloc] initWithFormat:@"%@",  chartNameForThisInfoFile  ];
                    NSString *path = [[NSBundle mainBundle] pathForResource:imageDataPath ofType:@"png"];
                    imageData = [NSData dataWithContentsOfFile:path];
                    image = [UIImage imageWithData:imageData];
                    imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];
                    
                    acManufacturerForPerfPool = ACmanufacturer;
                    acTypeorPerfPool = AC_Type;
                    
                }
                // save image
                if (image) {
                    NSString *imageToSave = [NSString stringWithFormat:@"image_%@", chartNameForThisInfoFile ];
                    //chartImagesDictionary[imageToSave] = imageDataPNG ;
                   NSLog(@"222saving chartimage -%@-", imageToSave);
                   [imageDataPNG writeToFile:[imageToSave stringByAppendingPathComponent:@".png"] atomically:YES];
                    NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString  *documentsDirectory = [paths objectAtIndex:0];
                    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,imageToSave];
                    [imageDataPNG writeToFile:filePath atomically:YES];

                    
                }else{            
                    NSLog(@"NO PERF IMAGE for -%@- ", chartNameForThisInfoFile);
                }
            }
            
            
      }
        
        
        // create and save arrays for each chart computation part 1..2..3..4...
        
       
        NSLog(@"1111infoFilesGeneral %@", infoFilesGeneral);
        
        //NSLog(@"chartNameForThisInfoFilel %@", chartNameForThisInfoFile);
        
        if (chartNameForThisInfoFile.length > 1) {
            arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@", chartNameForThisInfoFile, @"infoGeneral" ];
            //NSLog( @"saving infoFilesGeneral:  %@",  arrayKey);
            [[NSUserDefaults standardUserDefaults]  setObject:infoFilesGeneral       forKey:arrayKey ];
            
            //NSLog(@"saving infoFilesGeneral for  arrayKey %@  %@", infoFilesGeneral, arrayKey);
            
          
            // get number of compuation Parts
            int maxPartNumbers = [[infoFilesGeneral objectAtIndex:2] intValue];
            NSLog(@"maxPartNumbers = %d", maxPartNumbers);
            
            if (maxPartNumbers <1) {
                 NSLog(@"!!!! critical - will crash !!! No part numbers for chart  >%@<", availableChartsNameUrl);
                           
            }
           
            
            
            // for each part, save info, curves, datasetX, datasetY
            
            NSLog(@"1check");
                  
            for(int partNumber =0; partNumber<maxPartNumbers; partNumber++) {
                
                //NSLog(@"2");
                NSString *availableChartsFileOriginal;
                
                if (flagLoadFromFleetControl == 1) {
                    
                    if ([chartNameForThisInfoFile rangeOfString:@"noChart"].location != NSNotFound) {
                        
                    }else{
                        availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@%@%@_%@/%@_part%d%@", baseDataURL, @"perfPool/", acManufacturerForPerfPool, acTypeorPerfPool, chartNameForThisInfoFile, partNumber+1, @".txt"   ];                    
                        //NSLog(@"availableChartsNameUrl:  %@", availableChartsNameUrl);
                        NSURL *availableChartsUrl = [NSURL URLWithString: availableChartsNameUrl];
                        NSStringEncoding encoding;
                        NSError *error;
                        availableChartsFileOriginal = [NSString stringWithContentsOfURL:availableChartsUrl usedEncoding:&encoding error:&error];   
                        
                    }
                    
                    
                }else{             
                    availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@_part%d", chartNameForThisInfoFile, partNumber+1  ];                    
                    NSLog(@"availableChartsNameUrl %@", availableChartsNameUrl);                         
                          
                    NSString *path = [[NSBundle mainBundle] pathForResource:availableChartsNameUrl ofType:@"txt"];
                    availableChartsFileOriginal = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
                    
                    NSLog(@"path  %@", path);

                }
                
                NSLog(@"2check");
                
                if (availableChartsFileOriginal.length < 1 & [chartNameForThisInfoFile rangeOfString:@"noChart"].location == NSNotFound) {
                   NSLog(@"!!!! critical - will crash !!! NO chart data for chart  >%@<", availableChartsNameUrl);
                    NSString *alertMessage = [ [NSString alloc] initWithFormat:@"No chart data for chart: %@", chartNameForThisInfoFile ]; 
                    
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle:@"Critcal Error"
                                          message:alertMessage
                                          delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
                    [alert show];
                   
                     
                    
                }
                NSLog(@"3check");
                
                
                availableChartsFileOriginal  = [ availableChartsFileOriginal stringByReplacingOccurrencesOfString:@" " withString:@""];
                //NSLog(@"1availableChartsFileOriginal %@", availableChartsFileOriginal);
                // info array
                NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"|"];
                NSArray* components = [availableChartsFileOriginal componentsSeparatedByCharactersInSet:charSet];
                infoArray = [[components objectAtIndex:0] componentsSeparatedByString:@","];
                //NSLog(@"writing infoArray %@", infoArray);
                arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@", chartNameForThisInfoFile, partNumber+1, @"infoFile" ];
                NSLog( @"saving infoArray: %@", arrayKey);
                [[NSUserDefaults standardUserDefaults]  setObject:infoArray       forKey:arrayKey ];
                NSLog( @"saving infoArray array %@", infoArray);
                
                int triggerLoadCurves = 1;
                
                if  ([ chartNameForThisInfoFile rangeOfString:@"FXX"].location != NSNotFound && [chartNameForThisInfoFile rangeOfString:@"ClimbComp"].location != NSNotFound ) {
                    triggerLoadCurves = 0;
                    
                    arrayKey = [ [NSString alloc] initWithFormat:@"%@",  chartNameForThisInfoFile];
                    [[NSUserDefaults standardUserDefaults]  setObject:availableChartsFileOriginal       forKey:arrayKey ];                    
                    NSLog( @"saving availableChartsFileOriginal %@", availableChartsFileOriginal);
                    NSLog( @"for arrayKey %@", arrayKey);
                     
                }
                if  ([ chartNameForThisInfoFile rangeOfString:@"FXX"].location != NSNotFound && [chartNameForThisInfoFile rangeOfString:@"CruiseComp"].location != NSNotFound ) {
                    triggerLoadCurves = 0;
                    
                    arrayKey = [ [NSString alloc] initWithFormat:@"%@",  chartNameForThisInfoFile];
                    [[NSUserDefaults standardUserDefaults]  setObject:availableChartsFileOriginal       forKey:arrayKey ];                    
                    NSLog( @"saving availableChartsFileOriginal %@", availableChartsFileOriginal);
                    NSLog( @"for arrayKey %@", arrayKey);
                    
                }
                
                if (triggerLoadCurves == 1) {                    
                    
                    // curves array
                    curvesArray = [[components objectAtIndex:1] componentsSeparatedByString:@","];
                    arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@",  chartNameForThisInfoFile, partNumber+1, @"curves" ];
                    //NSLog( @"saving curvesArray: %@", curvesArray);
                    [[NSUserDefaults standardUserDefaults]  setObject:curvesArray       forKey:arrayKey ];
                    
                    // save array for each dataset x and y
                    axisDataArray = [[NSArray alloc] init];
                    
                    int curvesCounter = 0;
                    int doubler = 0;
                    
                    for(int c =2; c<curvesArray.count*2+2; c++) {
                        if (c% 2) {
                            //odd is Y
                            axisDataArray  = [[components objectAtIndex:c] componentsSeparatedByString:@","];
                            //NSLog( @"1axisDataArray %@  ", axisDataArray );
                            //NSLog( @"odd y %@ %@ %@", chartNameForThisInfoFile, [curvesArray objectAtIndex:curvesCounter],  axisDataArray );
                            arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@",  chartNameForThisInfoFile, partNumber+1, [curvesArray objectAtIndex:curvesCounter], @"yAxis" ];
                            [[NSUserDefaults standardUserDefaults]  setObject:axisDataArray       forKey:arrayKey ];
                            //NSLog( @"saving key %@", arrayKey );
                        }else{
                            //even is X
                            axisDataArray  = [[components objectAtIndex:c] componentsSeparatedByString:@","];
                            //NSLog( @"2axisDataArray %@  ", axisDataArray );
                            //NSLog( @"even x %@ %@ %@", chartNameForThisInfoFile, [curvesArray objectAtIndex:curvesCounter], axisDataArray);
                            arrayKey = [ [NSString alloc] initWithFormat:@"%@_part%d_%@_%@",  chartNameForThisInfoFile, partNumber+1, [curvesArray objectAtIndex:curvesCounter], @"xAxis" ];
                            [[NSUserDefaults standardUserDefaults]  setObject:axisDataArray       forKey:arrayKey ];
                            //NSLog( @"saving key %@", arrayKey );
                            if ([[curvesArray objectAtIndex:curvesCounter] isEqualToString: @"0"] ) {
                                //NSLog( @" 0  axisDataArray %@", axisDataArray );
                            }
                        }
                        doubler = doubler + 1; if ( doubler == 2 ) { curvesCounter = curvesCounter + 1;doubler = 0;}
                    }// end for each axis
                    
                    
                }
                
                
               
                
                
                
            }// end for each part number
        }
    }// end for each chart
    
    
     NSLog(@"importing stuff: ac image, logo, fuel data....  ");
    
    
    
    // import AC topViewOK
    
    NSString *imageDataUrl;
    NSData *imageData;
    UIImage *image;
    NSData *imageDataPNG;
    
    if (flagLoadFromFleetControl == 1) {
        
        
        //NSLog( @"flagLoadFromFleetControl customFilesArray for AC %@ = %@", AC_Type, customFilesArray);        
        
        // check if we need to load the generic file or the custom file from the customer folder
        if ([customFilesArray containsObject: @"topViewOK"]) {
            imageDataUrl = [ [NSString alloc] initWithFormat:@"%@%@%@", customerDataURL, AC_Type, @"_topViewOK.png"  ];
            //NSLog( @"loading from customerDataURL : _topViewOK %@", imageDataUrl);
        }else{
            //NSLog( @"loading from baseDataURL : _topViewOK");
            imageDataUrl = [ [NSString alloc] initWithFormat:@"%@%@%@_%@/%@%@", baseDataURL, @"perfPool/", ACmanufacturer, AC_Type,  AC_Type, @"_topViewOK.png" ];            
        }
        
        NSURL *imageURL = [NSURL URLWithString: imageDataUrl ];
        imageData = [NSData dataWithContentsOfURL:imageURL];
        image = [UIImage imageWithData:imageData];
        imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];
        
    }else{
        NSString *imageDataPath = [ [NSString alloc] initWithFormat:@"%@%@",  AC_Type, @"_topViewOK"  ];
        NSString *path = [[NSBundle mainBundle] pathForResource:imageDataPath ofType:@"png"];
        //NSLog(@"path  topViewOK -%@-", path);
        NSData *imageData = [NSData dataWithContentsOfFile:path];
        image = [UIImage imageWithData:imageData];
        imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];
    }
    // save image
    if (image) {
        NSString *imageToSave = [NSString stringWithFormat:@"image_%@%@", AC_Type, @"_topViewOK" ];        //A
        NSLog(@"111saving _topViewOK  -%@-", imageToSave);
        
        [imageDataPNG writeToFile:[imageToSave stringByAppendingPathComponent:@".png"] atomically:YES];         
        NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];
        NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,imageToSave];
        [imageDataPNG writeToFile:filePath atomically:YES];
        
        
    }else{
        NSString *imageToSave = [NSString stringWithFormat:@"image_%@%@", AC_Type, @"_topViewOK.png" ];        
        NSLog(@"!!!! NO _topViewOK  for -%@- ", imageToSave);
    }
    
  
    
 
  
    // import logoManifest
    int flagUseGyronimoLogo = 1;
    if (flagLoadFromFleetControl == 1) {
        
        NSLog( @"2 flagLoadFromFleetControl customFilesArray %@", customFilesArray);
        
        // check if we need to load the generic file or the custom file from the customer folder
        if ([customFilesArray containsObject: @"logoManifest"]) {
            NSLog( @"loading logoManifest from customerDataURL : _logoManifest for AC %@", AC_Type);
            imageDataUrl = [ [NSString alloc] initWithFormat:@"%@%@%@", customerDataURL, AC_Type, @"_logoManifest.png"  ];
            flagUseGyronimoLogo = 0;
        }else{
            
            imageDataUrl = [ [NSString alloc] initWithFormat:@"%@%@%@", baseDataURL, @"perfPool/images/", @"Gyronimo_logoManifest.png" ];
        }
        
        if ([customFilesArray containsObject: @"logoManifestFIXED"]) {
            NSLog( @"logoManifestFIXED.png");
            imageDataUrl = [ [NSString alloc] initWithFormat:@"%@%@", customerDataURL,  @"logoManifestFIXED.png"  ];
            flagUseGyronimoLogo = 0;
        }
        
        NSURL *imageURL;
        if (flagUseGyronimoLogo == 0) {
             NSLog( @"loading Gyronimo logoManifest for AC %@", AC_Type);;
            imageURL = [NSURL URLWithString: imageDataUrl ];
            imageData = [NSData dataWithContentsOfURL:imageURL];
            image = [UIImage imageWithData:imageData];
            imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];
        }
    
        
    }else{
        
        NSString *imageDataPath = [ [NSString alloc] initWithFormat:@"%@%@",  AC_Type, @"_logoManifest"  ];
        NSString *path = [[NSBundle mainBundle] pathForResource:imageDataPath ofType:@"png"];
        NSData *imageData = [NSData dataWithContentsOfFile:path];
        image = [UIImage imageWithData:imageData];
        imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];  
        
        if (image) {            
        }else{            
            NSString *imageDataPath = [ [NSString alloc] initWithFormat:@"%@",   @"Gyronimo_logoManifest"  ];
            NSString *path = [[NSBundle mainBundle] pathForResource:imageDataPath ofType:@"png"];
            NSData *imageData = [NSData dataWithContentsOfFile:path];
            image = [UIImage imageWithData:imageData];
            imageDataPNG = [NSData dataWithData:UIImagePNGRepresentation(image)];                        
        }
    }
    // save image
    if (flagUseGyronimoLogo == 0) {
        if (image) {
            NSString *imageToSave = [NSString stringWithFormat:@"image_%@%@", AC_Type, @"_logoManifest.png" ];
            ACimagesDictionary[imageToSave] = imageDataPNG ;
            NSLog(@"saving _logoManifest  -%@-", imageToSave);
            [[NSUserDefaults standardUserDefaults]  setObject: ACimagesDictionary  forKey:@"ACimagesDictionary"];
        }else{
            NSString *imageToSave = [NSString stringWithFormat:@"image_%@%@", AC_Type, @"_logoManifest.png" ];           
            NSLog(@"!!!! NO _logoManifest for -%@- ", imageToSave);           
        }
    }
    
 
    
    //NSLog(@"ACimagesDictionary  %@", ACimagesDictionary);
    [[NSUserDefaults standardUserDefaults]  setObject: chartImagesDictionary  forKey:@"chartImagesDictionary"];
    
    NSLog(@"setting ACimagesDictionary ");
    
    
    
    
    
    
    
    
    // import fuelInterpolation
    
    NSString *fuelInterpolationURL;
    NSString *loadedText;
    
    if (flagWeHaveAbackendID == 0) {
        
        if (flagLoadFromFleetControl == 1 ) {
            
            // check if we need to load the generic file or the custom file from the customer folder
            if ([customFilesArray containsObject: @"fuelInterpolation"]   || [customFilesArray containsObject: @"FuelInterpolation"]  ) {
                //NSLog( @"loading from customerDataURL : fuelInterpolation");
                fuelInterpolationURL = [ [NSString alloc] initWithFormat:@"%@/%@%@", customerDataURL, AC_Type, @"_FuelInterpolation.txt"   ];
                
            }else{
                //NSLog( @"loading from baseDataURL : fuelInterpolation");
                fuelInterpolationURL = [ [NSString alloc] initWithFormat:@"%@%@%@_%@/%@%@", baseDataURL, @"perfPool/", ACmanufacturer, AC_Type,  AC_Type,  @"_FuelInterpolation.txt" ];
                
            }
            
            NSLog( @"fuelInterpolationURL %@", fuelInterpolationURL);
            
            NSURL *URL = [NSURL URLWithString: fuelInterpolationURL];
            [[NSURLCache sharedURLCache] removeAllCachedResponses];
            [[NSURLCache sharedURLCache] setDiskCapacity:0];
            [[NSURLCache sharedURLCache] setMemoryCapacity:0];
            loadedText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
        }else{
            
            fuelInterpolationURL = [ [NSString alloc] initWithFormat:@"%@%@",  AC_Type, @"_FuelInterpolation"];
            NSString *path = [[NSBundle mainBundle] pathForResource:fuelInterpolationURL ofType:@"txt"];
            loadedText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        }
        
    }
    
    
    if (flagWeHaveAbackendID == 1) {
        loadedText =  [ [NSString alloc] initWithFormat:@"%@", [backendDictionaryAircraftData valueForKey: @"fuel_interpolation"]];
        NSLog(@"loadedText for Fuel Interpolation %@", loadedText);
    }
    
    
    
    fuelInterpolationDictionary = [[NSMutableDictionary alloc] init];
    
    NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *arrayComponents = [loadedText componentsSeparatedByCharactersInSet:charSet1];
    NSArray *componentItems  = [[arrayComponents objectAtIndex:0] componentsSeparatedByString:@","];

    NSLog( @"arrayComponents  %@", arrayComponents);
    
    
    NSLog( @"loadedText _FuelInterpolation %@", loadedText);
    if (loadedText.length < 1) {
        NSLog(@"!!!! NO _FuelInterpolation for -%@- ", AC_Type);
    }
   
    NSLog(@"s1 componentItems %@", componentItems);
    if (componentItems.count > 1) {
        NSLog(@"s2");
        NSMutableArray *arrayFuelVolumeLONG = [[NSMutableArray alloc] init];
        NSMutableArray *arrayFuelMomentLONG = [[NSMutableArray alloc] init];
        NSMutableArray *arrayFuelVolumeLAT = [[NSMutableArray alloc] init];
        NSMutableArray *arrayFuelMomentLAT = [[NSMutableArray alloc] init];
        int numberOfTanksTimesTwo = 0;
        
        for (int numberOfTanks = 0; numberOfTanks<arrayComponents.count/2; numberOfTanks++) {
            NSLog(@"s3");
            numberOfTanksTimesTwo = numberOfTanks * 2;
            // longitudinal
            NSArray *componentItems  = [[arrayComponents objectAtIndex:numberOfTanksTimesTwo] componentsSeparatedByString:@","];
            for (int i = 0; i<componentItems.count/2; i++) {
                [arrayFuelVolumeLONG addObject:[componentItems objectAtIndex: i*2 ] ];
                [arrayFuelMomentLONG addObject:[componentItems objectAtIndex: i*2 + 1 ] ];
            }
            if (numberOfTanksTimesTwo < arrayComponents.count/2 ) {
                [arrayFuelVolumeLONG addObject:@"|" ];
                [arrayFuelMomentLONG addObject:@"|" ];
            }
            
            // lateral
            componentItems  = [[arrayComponents objectAtIndex:numberOfTanksTimesTwo+1] componentsSeparatedByString:@","];
            for (int i = 0; i<componentItems.count/2; i++) {
                [arrayFuelVolumeLAT addObject:[componentItems objectAtIndex: i*2 ] ];
                [arrayFuelMomentLAT addObject:[componentItems objectAtIndex: i*2 + 1 ] ];
            }
            
            if (numberOfTanksTimesTwo < arrayComponents.count/2 ) {
                [arrayFuelVolumeLAT addObject:@"|" ];
                [arrayFuelMomentLAT addObject:@"|" ];
            }
            
            //NSLog(@"numberOfTanks %d", numberOfTanks);
        }
        
        
        NSLog(@"s4");
        fuelInterpolationDictionary[@"arrayFuelVolumeLONG"] = arrayFuelVolumeLONG ;
        fuelInterpolationDictionary[@"arrayFuelMomentLONG"] = arrayFuelMomentLONG ;
        fuelInterpolationDictionary[@"arrayFuelVolumeLAT"] = arrayFuelVolumeLAT;
        fuelInterpolationDictionary[@"arrayFuelMomentLAT"] = arrayFuelMomentLAT;
    }else{
        NSLog(@"s5");
        NSMutableArray *arrayFuelMomentLONG = [[NSMutableArray alloc] init];
        NSMutableArray *arrayFuelMomentLAT  = [[NSMutableArray alloc] init];
        
        // longitudinal
        NSArray *componentItems  = [[arrayComponents objectAtIndex:0] componentsSeparatedByString:@","];
        [arrayFuelMomentLONG addObject:[componentItems objectAtIndex: 0 ] ];
        // lateral
        componentItems  = [[arrayComponents objectAtIndex:1] componentsSeparatedByString:@","];
        [arrayFuelMomentLAT addObject:[componentItems objectAtIndex: 0 ] ];
        
        fuelInterpolationDictionary[@"arrayFuelMomentLONG"] = arrayFuelMomentLONG;
        fuelInterpolationDictionary[@"arrayFuelMomentLAT"] = arrayFuelMomentLAT;
    }
    
    
   
    NSLog( @"fuelInterpolationDictionary %@ %@", AC_Type,  fuelInterpolationDictionary[@"arrayFuelVolumeLONG"]);
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_FuelInterpolation" ];
    [[NSUserDefaults standardUserDefaults]  setObject:fuelInterpolationDictionary       forKey:arrayKey ];
    
        
    
}






- (void) loadCGenvelopesPerACtype {
    
    NSLog( @"loadCGenvelopesPerACtype");
    
    int flagLoadMultiple = 0 ;
    NSURL *URL;
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
    NSStringEncoding encoding;
    NSError *error;
    
    if (flagLoadFromFleetControl == 1) {
        
         NSLog( @"1");
        
        if (flagWeHaveAbackendID == 0) {
             NSLog( @"2");
            
            // check if we need to load the generic file or the custom file from the customer folder
            if ([customFilesArray containsObject: @"CGenvelope"]) {
                 NSLog( @"3");
                //NSLog( @"loading from customerDataURL : CGenvelope");
                availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@/%@%@", customerDataURL, AC_Type, @"_CGenvelope.txt"   ];
                
                NSLog( @"customerDataURL %@",  customerDataURL);
                NSLog( @"AC_Type URL %@",  AC_Type);
                
                
                NSLog( @"load CGenvelope from FC URL %@",  availableChartsNameUrl);
                
            }else if ([customFilesArray containsObject: @"CGmultiple"]) {
                 NSLog( @"4");
                flagLoadMultiple = 1;
                NSLog( @"load CGmultiple from fleet control for %@", AC_Type);
                availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@/%@%@", customerDataURL, AC_Type, @"_CGmultiple.txt"   ];
            } else{
                //NSLog( @"loading from baseDataURL : CGenvelope");            
                //check if data is in frontend:            
                availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@%@%@_%@/%@%@", baseDataURL, @"perfPool/", ACmanufacturer, AC_Type,  AC_Type,  @"_CGenvelope.txt" ];
            }
            
            URL = [NSURL URLWithString: availableChartsNameUrl];
            importedText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
            NSLog( @"imported text from FC  %@", importedText);            
        }else{
            
            importedText =  [ [NSString alloc] initWithFormat:@"%@", [backendDictionaryAircraftData valueForKey: @"cg_envelope"]];
            NSLog(@"loadedText for  cg_envelope %@", importedText);
            
            
        }
        
       
        

        
        
        
        
       if ([importedText rangeOfString:@"CGdatabase"].location != NSNotFound     ) {           
           NSLog( @"need to load from CGdatabase, importedText =  %@", importedText);
           flagLoadMultiple = 2;
       }
        
        
        
    }else{
        
        availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@_CGmultiple",  AC_Type];
        NSString *path = [[NSBundle mainBundle] pathForResource:availableChartsNameUrl ofType:@"txt"];
        importedText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        flagLoadMultiple = 1;
        if (importedText.length < 3) {
            flagLoadMultiple = 0;
            NSLog( @"could not find multiple so try to load single CGenvelope from disk");
            availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@_CGenvelope",  AC_Type];
            path = [[NSBundle mainBundle] pathForResource:availableChartsNameUrl ofType:@"txt"];
            importedText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        }
    }
    
    if (flagLoadMultiple == 0) {
         [self loadSingleCGenvelopes];
    }
    
    if (flagLoadMultiple == 1) {
        [self loadMultipleCGenvelopes];
    }
    
    if (flagLoadMultiple == 2) {
        [self loadMultipleCGenvelopesFromDatabase];
    }
    
    
}

- (void) loadMultipleCGenvelopes {
    
    NSLog( @"load CGmultiple AC_Type %@", AC_Type);    
    
    NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"^"];
    NSArray *arrayCGenvelopes = [importedText componentsSeparatedByCharactersInSet:charSet1];
    
    //NSLog( @"arrayCGenvelopes %@", arrayCGenvelopes);
    
    for (int iCGs = 0; iCGs <arrayCGenvelopes.count; iCGs++) {
        
        NSString *cgText = [arrayCGenvelopes objectAtIndex:iCGs];
       
        charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"|"];
        NSArray *arrayComponents = [cgText componentsSeparatedByCharactersInSet:charSet1];
        if (arrayComponents.count < 1) {
            return;
        }
        
        //NSLog (@"arrayComponents _CGenvelope %@", arrayComponents);
        _arrayCG1 = [[NSMutableArray alloc] init];
        _arrayCG2 = [[NSMutableArray alloc] init];
        _arrayCG1_LAT = [[NSMutableArray alloc] init];
        _arrayCG1MarginLine = [[NSMutableArray alloc] init];
        
        NSString *CGenvelopeName = [arrayComponents objectAtIndex:0] ;
        CGenvelopeName  = [ CGenvelopeName stringByReplacingOccurrencesOfString:@" " withString:@""];
        CGenvelopeName  = [ CGenvelopeName stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        
        NSLog( @"CGenvelopeName %@", CGenvelopeName);
        
        NSArray *componentItems  = [[arrayComponents objectAtIndex:1] componentsSeparatedByString:@","];
        for (int i = 0; i<componentItems.count; i++) {
            [_arrayCG1 addObject:[componentItems objectAtIndex:i] ];
        }
        componentItems  = [[arrayComponents objectAtIndex:2] componentsSeparatedByString:@","];
        for (int i = 0; i<componentItems.count; i++) {
            [_arrayCG1_LAT addObject:[componentItems objectAtIndex:i] ];
        }
        componentItems  = [[arrayComponents objectAtIndex:3] componentsSeparatedByString:@","];
        for (int i = 0; i<componentItems.count; i++) {
            [_arrayCG2 addObject:[componentItems objectAtIndex:i] ];
        }
        componentItems  = [[arrayComponents objectAtIndex:4] componentsSeparatedByString:@","];
        for (int i = 0; i<componentItems.count; i++) {
            [_arrayCG1MarginLine addObject:[componentItems objectAtIndex:i] ];
        }
        //NSLog (@"_arrayCG1 %@", _arrayCG1);
        //NSLog (@"_arrayCG2 %@", _arrayCG2);
        //NSLog (@"_arrayCG1_LAT %@", _arrayCG1_LAT);
        //NSLog (@"_arrayCG1MarginLine %@", _arrayCG1MarginLine);
        //save array available Charts
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@_arrayCG1", AC_Type, CGenvelopeName ];
        //NSLog( @"arrayKey1 %@", arrayKey);
        [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1       forKey:arrayKey ];
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@_arrayCG1_LAT", AC_Type, CGenvelopeName ];
        //NSLog( @"arrayKey3 %@", arrayKey);
        [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1_LAT       forKey:arrayKey ];
        
        //NSLog (@"saving arrayKey %@", arrayKey);
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@_arrayCG2", AC_Type, CGenvelopeName ];
        //NSLog( @"arrayKey2 %@", arrayKey);
        [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG2       forKey:arrayKey ];
        
        arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@_arrayCG1MarginLine", AC_Type, CGenvelopeName ];
        //NSLog( @"arrayKey4 %@", arrayKey);
        [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1MarginLine       forKey:arrayKey ];
        
        
        
    }
    
    
        
    
}


- (void) loadSingleCGenvelopes {
    
    NSLog( @"loadCGenvelopesPerACtype AC_Type %@", AC_Type);
    
    
    if ([importedText length] < 1) {
        NSLog( @"!!!! imported CGenvelope of %@ is NULL !!  %@", AC_Type, availableChartsNameUrl);
    }
  
    
    NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    NSArray *arrayComponents = [importedText componentsSeparatedByCharactersInSet:charSet1];
    
    if (arrayComponents.count < 1) {
        return;
    }
    
    //NSLog (@"arrayComponents _CGenvelope %@", arrayComponents);
    _arrayCG1 = [[NSMutableArray alloc] init];
    _arrayCG2 = [[NSMutableArray alloc] init];
    _arrayCG1_LAT = [[NSMutableArray alloc] init];
    _arrayCG1MarginLine = [[NSMutableArray alloc] init];
    
    NSArray *componentItems  = [[arrayComponents objectAtIndex:0] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG1 addObject:[componentItems objectAtIndex:i] ];
    }
    componentItems  = [[arrayComponents objectAtIndex:1] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG1_LAT addObject:[componentItems objectAtIndex:i] ];
    }
    componentItems  = [[arrayComponents objectAtIndex:2] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG2 addObject:[componentItems objectAtIndex:i] ];
    }
    componentItems  = [[arrayComponents objectAtIndex:3] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG1MarginLine addObject:[componentItems objectAtIndex:i] ];
    }
    //NSLog (@"_arrayCG1 %@", _arrayCG1);
    //NSLog (@"_arrayCG2 %@", _arrayCG2);
    //NSLog (@"_arrayCG1_LAT %@", _arrayCG1_LAT);
    //NSLog (@"_arrayCG1MarginLine %@", _arrayCG1MarginLine);
    //save array available Charts
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGenvelope_arrayCG1" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1       forKey:arrayKey ];
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGenvelope_arrayCG2" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG2       forKey:arrayKey ];
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGenvelope_arrayCG1_LAT" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1_LAT       forKey:arrayKey ];
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGenvelope_arrayCG1MarginLine" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1MarginLine       forKey:arrayKey ];
    
    
    
    //***************************************************************************************************************
    //***************************************************************************************************************
    //***************************************************************************************************************
    
    //NSLog( @"get CGexternal ");
    // get CGexternal
    
    if (flagLoadFromFleetControl == 1) {
        // check if we need to load the generic file or the custom file from the customer folder
        if ([customFilesArray containsObject: @"CGexternal"]) {
            //NSLog( @"loading from customerDataURL : CGexternal");
            availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@%@_%@", customerDataURL, AC_Type, @"CGexternal.txt"   ];
            //NSLog( @"1 loadCGenvelopesPerACtype AC_Type %@", AC_Type);
            //NSLog( @"1 availableChartsNameUrl %@", availableChartsNameUrl);
        }else{
            //NSLog( @"loading from baseDataURL : CGexternal");
            availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@%@%@_%@/%@_%@", baseDataURL, @"perfPool/", ACmanufacturer, AC_Type,  AC_Type,  @"CGexternal.txt" ];
            //NSLog( @"2 availableChartsNameUrl %@", availableChartsNameUrl);
        }
        NSURL *URL = [NSURL URLWithString: availableChartsNameUrl];
        [[NSURLCache sharedURLCache] removeAllCachedResponses];
        [[NSURLCache sharedURLCache] setDiskCapacity:0];
        [[NSURLCache sharedURLCache] setMemoryCapacity:0];
        NSStringEncoding encoding;
        NSError *error;
        importedText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
    }else{
        availableChartsNameUrl = [ [NSString alloc] initWithFormat:@"%@_CGexternal",  AC_Type];
        //NSLog( @"3 availableChartsNameUrl %@", availableChartsNameUrl);
        NSString *path = [[NSBundle mainBundle] pathForResource:availableChartsNameUrl ofType:@"txt"];
        importedText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    }
    
    
    //NSLog( @"CGexternal importedText %@", importedText);
    charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"|"];
    arrayComponents = [importedText componentsSeparatedByCharactersInSet:charSet1];
    if (arrayComponents.count < 1) {
        NSLog( @"no CGexternal for %@", AC_Type);
        return;
    }
    
    if ([importedText length] < 1) {
        NSLog( @"!!!! imported CGexternal of %@ is NULL !!  %@", AC_Type, importedText);
    }
    
    [_arrayCG1 removeAllObjects];
    [_arrayCG2 removeAllObjects];
    [_arrayCG1_LAT removeAllObjects];
    [_arrayCG1MarginLine removeAllObjects];
    
    componentItems  = [[arrayComponents objectAtIndex:0] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG1 addObject:[componentItems objectAtIndex:i] ];
    }
    componentItems  = [[arrayComponents objectAtIndex:1] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG1_LAT addObject:[componentItems objectAtIndex:i] ];
    }
    componentItems  = [[arrayComponents objectAtIndex:2] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG2 addObject:[componentItems objectAtIndex:i] ];
    }
    componentItems  = [[arrayComponents objectAtIndex:3] componentsSeparatedByString:@","];
    for (int i = 0; i<componentItems.count; i++) {
        [_arrayCG1MarginLine addObject:[componentItems objectAtIndex:i] ];
    }
    
    //NSLog (@"_arrayCG1 %@", _arrayCG1);
    //NSLog (@"_arrayCG2 %@", _arrayCG2);
    //NSLog (@"_arrayCG1_LAT %@", _arrayCG1_LAT);
    //NSLog (@"_arrayCG1MarginLine %@", _arrayCG1MarginLine);
    
    //save array available Charts
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGexternal_arrayCG1" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1       forKey:arrayKey ];
    
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGexternal_arrayCG2" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG2       forKey:arrayKey ];
    
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGexternal_arrayCG1_LAT" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1_LAT       forKey:arrayKey ];
    
    arrayKey = [ [NSString alloc] initWithFormat:@"%@%@", AC_Type, @"_CGexternal_arrayCG1MarginLine" ];
    [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1MarginLine       forKey:arrayKey ];
    
    
    
}

- (void) loadMultipleCGenvelopesFromDatabase {
    
    NSLog( @"loadMultipleCGenvelopesFromDatabase ...");
    
    
    NSCharacterSet* charSet1 = [NSCharacterSet characterSetWithCharactersInString:@"^"];
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSArray *arrayDatabase = [importedText componentsSeparatedByCharactersInSet:charSet1];
    
    NSLog( @"arrayDatabase %@", arrayDatabase);
    
    
    
    for (int i = 1; i <arrayDatabase.count; i++) {
       
        // structure in frontend:
        // CGdatabase^50|52
        
       NSString *CGenvelopeSet = [arrayDatabase objectAtIndex:i] ;      
       //NSLog( @"CGenvelopeSet %@", CGenvelopeSet);
        
       NSCharacterSet* charSet2 = [NSCharacterSet characterSetWithCharactersInString:@"|"];
       NSArray *arrayCGenvelopes = [CGenvelopeSet componentsSeparatedByCharactersInSet:charSet2];
        
        
       NSString *envelopeName = @"";
        
        if (arrayCGenvelopes.count >0) {
            NSLog( @"[arrayCGenvelopes objectAtIndex:0] %@", [arrayCGenvelopes objectAtIndex:0]);            
            NSString *configID  = [arrayCGenvelopes objectAtIndex:0];            
            NSString *urlWithConfigID =  [ [NSString alloc] initWithFormat:@"https://www.gyronimoserver.com/api/cgEnvelope/%@", configID];
            NSURL *url = [NSURL URLWithString:urlWithConfigID];
            NSLog(@"urlWithConfigID: %@", urlWithConfigID);  
            NSError *error = nil;
            NSURLResponse *response = nil;
            NSData *data = [[NSURLSession sharedSession] sendSynchronousDataTaskWithURL:url returningResponse:&response error:&error];         
            
            NSDictionary *dictionaryAll = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 
            NSLog(@"dictionaryAll: %@", dictionaryAll);  
            NSDictionary *dictHeader = [dictionaryAll valueForKey:@"cg_envelope"];
            NSLog(@"dictHeader: %@", dictHeader);            
            envelopeName =  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"envelope_name"]];
            NSLog(@"envelopeName: %@", envelopeName);            
            
            
            int xline = [[dictHeader valueForKey: @"x_line"] intValue];
            //xline = xline + 1;
            NSString *xLineCorrected = [[NSString alloc] initWithFormat:@"%d", xline];
            NSLog(@"xLineCorrected %@", xLineCorrected);
            int yline = [[dictHeader valueForKey: @"y_line"] intValue];
            //yline = yline + 1;
            NSString *yLineCorrected = [[NSString alloc] initWithFormat:@"%d", yline];
            
            _arrayCG1 = [[NSMutableArray alloc] init];            
            //xAxisLeft
            [_arrayCG1 addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"x_min"] ] ];
            //xAxisRight
            [_arrayCG1 addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"x_max"] ] ];
            //xIncements
            [_arrayCG1 addObject:  xLineCorrected ];    
            //yAxisBottom
            [_arrayCG1 addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"y_min"] ] ];
            //yAxisTop
            [_arrayCG1 addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"y_max"] ] ];
            //yIncrements
            [_arrayCG1 addObject:  yLineCorrected ];    
            //labelFontSize
            [_arrayCG1 addObject:  @"11" ];
            
            NSArray *itemsArray = [dictionaryAll valueForKey:@"points"];    
            //NSLog(@"itemsArray: %@", itemsArray);
            //NSLog(@"itemsArray.count: %lu", (unsigned long)itemsArray.count);          
            for(int i =0; i<itemsArray.count; i++) {        
                NSDictionary *dictionaryItem = [itemsArray objectAtIndex:i];
                //NSLog(@"dictionaryItem: %@", dictionaryItem);        
                [_arrayCG1 addObject:  [ [NSString alloc] initWithFormat:@"%@/%@", [dictionaryItem valueForKey: @"x_value"] , [dictionaryItem valueForKey: @"y_value"] ] ];       
            }           
            //NSLog(@"arrayCG1 %@", _arrayCG1 );           
            
            arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@_arrayCG1", AC_Type, envelopeName ];
            NSLog( @"arrayKey1 %@", arrayKey);
            [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1       forKey:arrayKey ];            
            
            
            //arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@%@", AC_Type, CGenvelopeName,  @"_arrayCG1" ];
            
            
            NSLog(@"arrayCGenvelopes.count %lu", arrayCGenvelopes.count );   
            
            
            if (arrayCGenvelopes.count <2) {                
                NSLog( @"saving einen extra fuer LONG");
                arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@%@", AC_Type, @"CGenvelope", @"_arrayCG1" ];
                NSLog( @"arrayKey1 %@", arrayKey);
                [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1       forKey:arrayKey ];    
            }
            
        }
        
        if (arrayCGenvelopes.count >1) {
            //NSLog( @"[arrayCGenvelopes objectAtIndex:0] %@", [arrayCGenvelopes objectAtIndex:1]);            
            NSString *configID  = [arrayCGenvelopes objectAtIndex:1];            
            NSString *urlWithConfigID =  [ [NSString alloc] initWithFormat:@"https://www.gyronimoserver.com/api/cgEnvelope/%@", configID];
            NSURL *url = [NSURL URLWithString:urlWithConfigID];
            NSError *error = nil;
            NSURLResponse *response = nil;
            NSData *data = [[NSURLSession sharedSession] sendSynchronousDataTaskWithURL:url returningResponse:&response error:&error];         
            
            NSDictionary *dictionaryAll = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];    
            NSDictionary *dictHeader = [dictionaryAll valueForKey:@"cg_envelope"];
            //NSLog(@"2dictHeader: %@", dictHeader);            
                     
            int xline = [[dictHeader valueForKey: @"x_line"] intValue];
            //xline = xline + 1;
            NSString *xLineCorrected = [[NSString alloc] initWithFormat:@"%d", xline];
            //NSLog(@"xLineCorrected %@", xLineCorrected);
            int yline = [[dictHeader valueForKey: @"y_line"] intValue];
            //yline = yline + 1;
            NSString *yLineCorrected = [[NSString alloc] initWithFormat:@"%d", yline];
            
            
            _arrayCG1_LAT = [[NSMutableArray alloc] init];            
            //xAxisLeft
            [_arrayCG1_LAT addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"x_min"] ] ];
            //xAxisRight
            [_arrayCG1_LAT addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"x_max"] ] ];
            //xIncements
            [_arrayCG1_LAT addObject: xLineCorrected ];    
            //yAxisBottom
            [_arrayCG1_LAT addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"y_min"] ] ];
            //yAxisTop
            [_arrayCG1_LAT addObject:  [ [NSString alloc] initWithFormat:@"%@", [dictHeader valueForKey: @"y_max"] ] ];
            //yIncrements
            [_arrayCG1_LAT addObject:  yLineCorrected];    
            //labelFontSize
            [_arrayCG1_LAT addObject:  @"11" ];
            
            NSArray *itemsArray = [dictionaryAll valueForKey:@"points"];    
            //NSLog(@"itemsArray: %@", itemsArray);
            //NSLog(@"itemsArray.count: %lu", (unsigned long)itemsArray.count);          
            for(int i =0; i<itemsArray.count; i++) {        
                NSDictionary *dictionaryItem = [itemsArray objectAtIndex:i];
                //NSLog(@"dictionaryItem: %@", dictionaryItem);        
                [_arrayCG1_LAT addObject:  [ [NSString alloc] initWithFormat:@"%@/%@", [dictionaryItem valueForKey: @"x_value"] , [dictionaryItem valueForKey: @"y_value"] ] ];       
            }           
            NSLog(@"_arrayCG1_LAT %@", _arrayCG1_LAT );          
            arrayKey = [ [NSString alloc] initWithFormat:@"%@_CGmulti_%@_arrayCG1_LAT", AC_Type, envelopeName ];
            NSLog( @"arrayKey2 %@", arrayKey);
            [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1_LAT       forKey:arrayKey ];
            
            if (arrayCGenvelopes.count <2) {                
                NSLog( @"saving einen extra fuer LAT");
                arrayKey = [ [NSString alloc] initWithFormat:@"%@_%@%@", AC_Type, @"CGenvelope", @"_arrayCG1_LAT" ];
                NSLog( @"_arrayCG1_LAT %@", arrayKey);
                [[NSUserDefaults standardUserDefaults]  setObject:_arrayCG1_LAT       forKey:arrayKey ];    
            }
            
            
        }
        
        
    }
    
    
}



@end
