//
//  ViewController.m
//  DemoiSt01
//
//  Created by Xinhu Li on 12-6-12.
//  Copyright (c) 2012年 IDTECH. All rights reserved.
//

#import "ViewController.h"
#import "BTmsr.h"

@implementation ViewController
@synthesize resultsTextView;
@synthesize connectedLabel;
@synthesize pageControl = _pageControl;

@synthesize view1;
@synthesize view2;
@synthesize view3;
Byte bt1;
Byte bt2;
int flag=0;
int flagerror=0;
static NSTimer *myTimer;
UIAlertView *subPreAuth;

-(void)FunOnTimer
{
    if (myTimer.isValid)
    {
        NSLog(@"---delete timer");
        [myTimer invalidate];
        myTimer = nil;
         
        if(flag) {[subPreAuth dismissWithClickedButtonIndex:0 animated:YES]; }
     
        flag=0;//Delete the show
       
        return;
        
    }
}

-(void) appendMessageToResults:(NSString*) message{
    [self.resultsTextView setText:[NSString stringWithFormat:@"%@\n%@", self.resultsTextView.text, message]];
    [self.resultsTextView scrollRangeToVisible:NSMakeRange([self.resultsTextView.text length], 0)];
}

- (IBAction) DoClearLog:(id)sender{
    [self.resultsTextView setText: @""];
    [self.resultsTextView scrollRangeToVisible:NSMakeRange([self.resultsTextView.text length], 0)];
}

- (IBAction) DoKeyboardOff:(id)sender{
    [sender resignFirstResponder];
}

-(BOOL) isValidChar:(Byte)byChar{
    if ( ((byChar>(Byte)0x2F) && (byChar<(Byte)0x3A)) //'0' - '9'
        || ((byChar>(Byte)0x40) && (byChar<(Byte)0x47)) //'A' - 'F'
        || ((byChar>(Byte)0x60) && (byChar<(Byte)0x67)) //'a' - 'f'
        )
    {
        return YES;
    }
    return NO;
}
-(NSData*) StringToBytes:(NSString*)hexString{
    if (hexString.length<1) {
        return nil;
     }
    NSMutableData *result = [[NSMutableData alloc] init];  
    unsigned char byte;
    for (int k=0; k<hexString.length;k++) {
        char c = [hexString characterAtIndex:k];
        if (c == (char)0x20) {
            continue;
        }
        byte = c;
         [result appendBytes:&byte length:1];
    }
    return [NSData dataWithData:result];
}
-(NSData*) hexStringToBytes:(NSString*)hexString{
    if (hexString.length<1) {
        return nil;
    }
        
    char tmpCh[1024] = {0};
    int count = 0;
    for (int k=0; k<hexString.length;k++) {
        char c = [hexString characterAtIndex:k];
        if (c == (char)0x20) {
            continue;
        }
        tmpCh[count] = c;
        count++;
    }
    tmpCh[count] = 0;

     if(count%2)
         return nil;
    
    NSString *temp = [[NSString alloc] initWithUTF8String:tmpCh];
    int m = temp.length % 2;
    if (m>0) {
        return nil;
    }
    
    NSMutableData *result = [[NSMutableData alloc] init];
    unsigned char byte;
    char hexChars[3] = {0};
    for (int i=0; i < (temp.length/2); i++) {
        hexChars[0] = [temp characterAtIndex:i*2];
        hexChars[1] = [temp characterAtIndex:i*2+1];
        
        if (![self isValidChar:hexChars[0]] || ![self isValidChar:hexChars[1]]) {
            return nil;
        }
        byte = strtol(hexChars, NULL, 16);
        [result appendBytes:&byte length:1]; 
    }
    return [NSData dataWithData:result];
}
-(NSString*) bytesToHexString:(NSData*)nsData{
    if(nsData == nil){
        return nil;
    }
    //Byte* bData = (Byte*)[nsData bytes];
    NSMutableString* hexString =[NSMutableString string];
    const unsigned char *p = [nsData bytes];
    for(int i=0;i<nsData.length;i++)
    {
        [hexString appendFormat:@"/x%02X",*p++];
    }
    return hexString;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    //pageControl.numberOfPages = 1;
    //pageControl.currentPage = 0;
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) BTmsrDidDisconnect{
    connectedLabel.text = @"DISCONNECT";
    [self appendMessageToResults:@"[BTmsr DidDisconnect]"];
}

- (IBAction) Do_Open:(id)sender{
    if (!BTmsrDevice) {
        BTmsrDevice = [[BTmsr alloc] init];
    }
    BOOL b = [BTmsrDevice open];
    if(b){
        connectedLabel.text = @"CONNECTED";
        [self appendMessageToResults:@"[BTmsr Open Success]"];
        BTmsrDevice.delegate = self;
    }
    else
    {
        [self appendMessageToResults:@"[BTmsr Open Failed]"];
    }
}

- (IBAction) Do_Close:(id)sender{
    [BTmsrDevice close];
    [BTmsrDevice release];
    BTmsrDevice = nil;
    [self appendMessageToResults:@"[BTmsr Do_Close]"];
    
}

- (IBAction) Do_CloseView:(id)sender{
    [view1 removeFromSuperview];  
    /*[view3 removeFromSuperview];  
    [[self view] addSubview:view2];  
    pageControl.currentPage = 0;
    */
}

- (void)viewWillAppear:(BOOL)animated
{
    /*
    if (!BTmsrDevice) {
        BTmsrDevice = [[BTmsr alloc] init];
    }
    BOOL b = [BTmsrDevice open];
    if(b){
        connectedLabel.text = @"CONNECTED";
        [self appendMessageToResults:@"[BTmsr Open Success]"];
        BTmsrDevice.delegate = self;
    }
    else
    {
        [self appendMessageToResults:@"[BTmsr Open Failed]"];
    }
*/
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    //return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    return NO;
}

#pragma mark - iSmartDelegate methods

-(void) cardDataReceived:(NSData *)CardData: (Byte)TracksStatus;
{
    if(flagerror==0)
    {
    Byte * temp=(Byte*)[CardData bytes];
    NSLog(CardData.description);
    
    if(flag) [subPreAuth dismissWithClickedButtonIndex:0 animated:YES];
    flag=0;
     myTimer = [NSTimer scheduledTimerWithTimeInterval: 5 target:self selector:@selector(FunOnTimer) userInfo:nil repeats:NO];
    if(temp[0]==0x48){
        
        subPreAuth = [[UIAlertView alloc] initWithTitle:@"Message"
                                                message:@"Card Data Receiving!"
                                               delegate:self
                                      cancelButtonTitle:nil
                                      otherButtonTitles:nil];
        [subPreAuth show];
        [subPreAuth release];
         flag=1;
        
       // myTimer = [NSTimer scheduledTimerWithTimeInterval: 5 target:self selector:@selector(FunOnTimer) userInfo:nil repeats:NO];
    }
    else if(temp[0]==0x49){
        
     
        if(!subPreAutherror){
            subPreAutherror = [[UIAlertView alloc] initWithTitle:@"Message"
                                                         message:@"Card Data Error! Please swipe card agian"
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
            subPreAutherror.tag=1;
            flagerror=1;
            [subPreAutherror show];
            [subPreAutherror release];
        }
    }
    else if(temp[0]==0x01&&temp[1]==0x01&&temp[2]==0x1a&&temp[3]==0x02&&temp[4]==0x00&&CardData.length==285)
    {
       
        [self appendMessageToResults: @"---Event: received card data ---"];
        
        [self appendMessageToResults: [NSString stringWithFormat:@"whole card data Hex Format: %@", CardData.description]];
        [self appendMessageToResults: @"---Event: end ---"];
    }
    
    else
    {
       
        NSString *strresult=[[[NSString alloc] initWithBytes:temp length: CardData.length  encoding:NSASCIIStringEncoding] autorelease];
        [self appendMessageToResults: @"---Event: received card data ---"];
        
        [self appendMessageToResults: [NSString stringWithFormat:@"whole card data Hex Format: %@", CardData.description]];
        
        NSLog(@"String len %d",strresult.length);
        [self appendMessageToResults: [NSString stringWithFormat:@"whole card data ASCII Format: %@", strresult]];
        
        
        [self appendMessageToResults: @"---Event: end ---"];
     }
    }
    

    
}

- (IBAction) f_getLevel:(id)sender{
    Byte bt = [BTmsrDevice GetSecurityLevel];
    [self appendMessageToResults: [NSString stringWithFormat:@"Level: 0x%02X", bt]];
    NSLog(@"Level: 0x%02X", bt);
}

- (IBAction) f_getEptType:(id)sender{
    Byte bt = [BTmsrDevice GetEncryptionType];
    //[self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X", bt]];
    NSLog(@"EptType: 0x%02X", bt);
    switch (bt) {
        case EPT_NOKEY:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X", bt]];
        }
            break;
            
        case EPT_TDES:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X", bt]];
        }
            break;
            
        case EPT_AES:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X", bt]];
        }
            break;
            
        default:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X, Failed", bt]];
        }
            break;
    }
}

- (IBAction) f_getKeyManagement:(id)sender;
{
    Byte bt = [BTmsrDevice GetKeyManagementType];
    //[self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X", bt]];
    NSLog(@"EptType: 0x%02X", bt);
    switch (bt) {
        case KEY_DUKPT:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X, DUKPT key", bt]];
        }
            break;
        case KEY_FIXED:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X, Fixed Key", bt]];
        }
            break;
            
        default:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X, failed", bt]];
        }
            break;
    }
}

- (IBAction) f_getEssentialInfo:(id)sender{
    //GetFirmwareVersion
    NSString* result = [BTmsrDevice GetFirmwareVersion];
    
    if(result){
        [self appendMessageToResults:@"Get Firmware Version:"];
        [self appendMessageToResults:result];
    }else{
        [self appendMessageToResults:@"Get Firmware Version Failed"];
        return;
    }
    
    //GetSecurityLevel
     bt1= [BTmsrDevice GetSecurityLevel];
    [self appendMessageToResults: [NSString stringWithFormat:@"Level: 0x%02X", bt1]];
    NSLog(@"Level: 0x%02X", bt1);
    
    //GetEncryptionType
   Byte  bt = [BTmsrDevice GetEncryptionType];
    //[self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X", bt]];
    NSLog(@"EptType: 0x%02X", bt);
    switch (bt) {
        case EPT_NOKEY:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X", bt]];
        }
            break;
            
        case EPT_TDES:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02x", bt]];
        }
            break;
            
        case EPT_AES:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X", bt]];
        }
            break;
            
        default:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"EptType: 0x%02X, Failed", bt]];
            return;
        }
            break;
    }
    bt2 =[BTmsrDevice GetDecodingMethod];
    [self appendMessageToResults: [NSString stringWithFormat:@"DecodingMethod: 0x%02X", bt2]];
    NSLog(@"DecodingMethod: 0x%02X", bt2);    //GetKeyManagementType
    bt = [BTmsrDevice GetKeyManagementType];
    //[self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X", bt]];
    NSLog(@"EptType: 0x%02X", bt);
    switch (bt) {
        case KEY_DUKPT:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X, DUKPT key", bt]];
        }
            break;
        case KEY_FIXED:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X, Fixed Key", bt]];
        }
            break;
            
        default:
        {
            [self appendMessageToResults: [NSString stringWithFormat:@"KeyManagementType: 0x%02X, failed", bt]];
            return;
        }
            break;
    }
}


#pragma mark - custom action

- (IBAction) DoTest:(id)sender{
        
    switch ([pageControl currentPage]) {  
            
        case 0:  
            //pageControl.currentPage = 1;
            [view1 removeFromSuperview];  
            [[self view] addSubview:view2];  
            //_b = YES;
            connectedLabel.text = @"test 0";
            break;  
            
        case 1:  
            [view2 removeFromSuperview];  
            [[self view] addSubview:view1];
            //pageControl.currentPage = 0;
            //_b = NO;
            connectedLabel.text = @"test 1";
            break;  
            
        default:  
            break;  
    }
}

- (IBAction) ShowViewSettings:(id)sender{
    [view2 removeFromSuperview];  
    [view3 removeFromSuperview];  
    [[self view] addSubview:view1];  
    pageControl.currentPage = 0;
}

- (IBAction) ShowViewMemory:(id)sender{
    [view1 removeFromSuperview];  
    [view3 removeFromSuperview];  
    [[self view] addSubview:view2];  
    pageControl.currentPage = 0;
}

- (IBAction) ShowViewCup:(id)sender{
    [view1 removeFromSuperview];  
    [view2 removeFromSuperview];  
    [[self view] addSubview:view3];  
    pageControl.currentPage = 0;
}

#pragma mark - custom methods

- (IBAction) f_getFirm:(id)sender
{
    NSString* result = [BTmsrDevice GetFirmwareVersion];
    
    if(result){
        [self appendMessageToResults:@"Get Firmware Version:"];
        [self appendMessageToResults:result];
    }else{
        [self appendMessageToResults:@"Get Firmware Version Failed"];
    }
}
- (IBAction) f_getEnzyModuleFWVersion:(id)sender:(id)sender
{
    NSString* result = [BTmsrDevice GetEnzyModuleFWVersion];
    
    if(result){
        [self appendMessageToResults:@"Get Enzy Module FW  Version:"];
        [self appendMessageToResults:result];
    }else{
        [self appendMessageToResults:@"Get Enzy Module FW  Version Failed"];
    }
}
- (IBAction) f_getEnzyBDAddress:(id)sender:(id)sender
{
    NSString* result = [BTmsrDevice GetEnzyBDAddress];
    
    if(result){
        [self appendMessageToResults:@"Get Enzy BD Address Version:"];
        [self appendMessageToResults:result];
    }else{
        [self appendMessageToResults:@"Get Enzy BD Address Version Failed"];
    }
}- (IBAction) f_getSerialNumber:(id)sender
{
    NSString* result = [BTmsrDevice GetSerialNumber];
    
    if(result.length>0){
        [self appendMessageToResults:[NSString stringWithFormat:@"Serial Number: %@", result]];
    }else{
        [self appendMessageToResults:@"Get Serial Number Failed"];
    }
}

- (IBAction) f_getAllSettings:(id)sender
{
    [self appendMessageToResults:@"Get Reader Settings:"];
    NSData* rawResult = [BTmsrDevice GetAllSettings];
    [self appendMessageToResults:rawResult.description];
}

- (IBAction) f_SetOperationMode:(id)sender{
    [txtOptMode resignFirstResponder];

    NSString *str = txtOptMode.text;
    if (str.length!=2) {
        //[self appendMessageToResults:@"SetOperationMode: invalid parameter value!"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"Invalid parameter" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    NSData *dataBuffer = nil;
    dataBuffer = [self hexStringToBytes:str];
    if (dataBuffer == nil) {
        //[self appendMessageToResults:@"SetOperationMode: invalid parameter value!"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"Invalid parameter" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    unsigned char mode = ((unsigned char*)dataBuffer.bytes)[0];
    NSString *operation = nil;
    if((mode & 2 )== 2)
        operation = @"[Card Seated Change On]";
    else
        operation = @"[Card Seated Change Off]";
    /* if((mode & 4) == 4)
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[Card Present Change On]"];
     else
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[Card Present Change Off]"];
     if((mode & 8) == 8)
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[MSR Data Envelop On]"];
     else
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[MSR Data Envelop Off]"];*/
    if((mode & 16) == 16)
        operation = [NSString stringWithFormat:@"%@,%@",operation,@"[LED Control By Host]"];
    else
        operation = [NSString stringWithFormat:@"%@,%@",operation,@"[LED Control By Reader]"];
    /*
     if((mode & 32) == 32)
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[Magnetic Data Present On]"];
     else
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[Magnetic Data Present Off]"];
     if((mode & 64) == 64)
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[Raw magnetic data decoder]"];
     else
     operation = [NSString stringWithFormat:@"%@,%@",operation,@"[Standard decoder]"];   */
    [self appendMessageToResults:[NSString stringWithFormat:@"%@:%@",@"Set Opration Mode",operation]];
    
    
    BOOL b = [BTmsrDevice Do_SetOperationMode:((unsigned char*)dataBuffer.bytes)[0]];
    
    NSString* res = nil;
    if(b)
        res = @"Set Operation Mode - Success";
    else 
        res = @"Set Operation Mode -Failed";
    [self appendMessageToResults:[NSString stringWithFormat:res]];
}

- (IBAction) f_SetCardOption:(id)sender{
    [txtCardOpt resignFirstResponder];

    NSString *str = txtCardOpt.text;
    if (str.length!=2) {
        //[self appendMessageToResults:@"SetCardOption: invalid parameter!"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"Invalid parameter" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    NSData *dataBuffer = nil;
    dataBuffer = [self hexStringToBytes:str];
    if (dataBuffer == nil) {
        //[self appendMessageToResults:@"SetCardOption: invalid parameter!"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"Invalid parameter" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    unsigned char cardmode = ((unsigned char*)dataBuffer.bytes)[0];
    
    NSString * ctype = @"Set Card Option:";
    
    if((cardmode & 8 )== 8)
        ctype = [NSString stringWithFormat:@"%@%@",ctype,@"[1.8V on]"];
    else
        ctype = [NSString stringWithFormat:@"%@%@",ctype,@"[1.8V off]"];
    
    if((cardmode & 16 )== 16)
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[ISO Card]"];
    else
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[EMV Card]"]; 
    
    if((cardmode & 32)== 32)
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[3V on]"];
    else
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[3V off]"]; 
    
    if((cardmode & 64)== 64)
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[5V off]"];
    else
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[5V on]"]; 
    
    if((cardmode & 128 )== 128)
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[Memory Card]"];
    else
        ctype = [NSString stringWithFormat:@"%@,%@",ctype,@"[Microprocessor Card]"];
    
    [self appendMessageToResults:ctype];
    
    BOOL b = [BTmsrDevice Do_SetCardOption:cardmode];
    
    NSString* res1 = nil;
    if(b)
        res1 = @"Set Card Option - Success";
    else 
        res1 = @"Set Card Option -Failed";
    
    [self appendMessageToResults:res1];
}

-(void) showSelectTracksActionSheet{
    UIActionSheet *nextActionSheet = [[UIActionSheet alloc] initWithTitle:@"select tracks" 
                                                                 delegate:self 
                                                        cancelButtonTitle:@"Cancel" 
                                                   destructiveButtonTitle:nil 
                                                        otherButtonTitles:
                                      @"Track 1", 
                                      @"Track 2", 
                                      @"Track 3", 
                                      nil];
    nextActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    nextActionSheet.tag = (int)_SELECT_Settings_Set_SHEET_TAG;
    [nextActionSheet showInView:self.view];
    [nextActionSheet release];
}

#pragma mark - custom dlg
typedef enum {
    _Track_1 = 1,
    _Track_2,
    _Track_3,
} TracksSheetTags;

typedef enum {
    EXTENDED_COMMANDS_ACTION_SHEET_TAG = 900,
    SPECIAL_CARD_SHEET_TAG,
    LED_CONTROL_ACTION_SHEET_TAG,
    MEMORY_CARD_TYPE_ACTION_SHEET_TAG,
    _SELECT_Settings_Get_SHEET_TAG,
    _SELECT_Settings_Set_SHEET_TAG,
    SELECT_FILE_COMMAND_TAG,
    WRITE_FILE_COMMAND_TAG,
    READ_FILE_COMMAND_TAG,
    APDU_T0T1_READ_WRITE_TAG,
    APDU_T1Raw_READ_WRITE_TAG,
    VERIFY_COMMAND_TAG,
    BLOCK_MESSAGE_TAG,
    DEFAULT_TAG
} ActionSheetTags;


-(void) showLEDControlActionSheet{
    UIActionSheet *nextActionSheet = [[UIActionSheet alloc] initWithTitle:@"LED Control Options" 
                                                                 delegate:self 
                                                        cancelButtonTitle:@"Cancel" 
                                                   destructiveButtonTitle:nil 
                                                        otherButtonTitles:@"Turn LED Off", 
                                      @"Turn On Green LED", 
                                      @"Turn On Red LED", 
                                      @"Turn On Amber LED", 
                                      @"Flash Red and Amber LED", 
                                      @"Flash Green LED", 
                                      @"Flash Red LED", 
                                      @"Flash Amber LED", 
                                      nil];
    nextActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    nextActionSheet.tag = (int)LED_CONTROL_ACTION_SHEET_TAG;
    [nextActionSheet showInView:self.view];
    [nextActionSheet release];
}

-(void) showMemoryCardTypeActionSheet{
    UIActionSheet *nextActionSheet = [[UIActionSheet alloc] initWithTitle:@"Memory Card Type Options" 
                                                                 delegate:self 
                                                        cancelButtonTitle:@"Cancel" 
                                                   destructiveButtonTitle:nil 
                                                        otherButtonTitles:@"3-Byte I2C", 
                                      @"4-Byte I2C", 
                                      @"SLE44*8", 
                                      @"SLE44*2", 
                                      @"GPM276", 
                                      @"GPM271", 
                                      @"SLE4404 and AT88SC101", 
                                      @"SLE4406", 
                                      nil];
    nextActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    nextActionSheet.tag = (int)MEMORY_CARD_TYPE_ACTION_SHEET_TAG;
    [nextActionSheet showInView:self.view];
    [nextActionSheet release];
}

static unsigned char  ckbyte = 0x00;

-(BOOL)checkLEDcontroltype{
    
    NSData * setting = [[NSData alloc] init];
    setting = [BTmsrDevice readerSettings];
    unsigned char * bsetting = nil;
    bsetting = (Byte *)[setting bytes]; 
    ckbyte = 0x00;
    int len =setting.length;
    for(int i = 0;i < len ;i++)
    {
        if ((bsetting [i] == 0x11) && (bsetting [1+i] == 0x01))
        {
            ckbyte = bsetting [i+2];
            continue;
        }
    }
    if((ckbyte & 16) == 16)
        return TRUE;
    else
        return FALSE;
    
}


-(void) showSelectSettingsType_Get_ActionSheet{
    UIActionSheet *nextActionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Settings" 
                                                                 delegate:self 
                                                        cancelButtonTitle:@"Cancel" 
                                                   destructiveButtonTitle:nil 
                                                        otherButtonTitles:
                                      @"GetFirmwareVersion", 
                                      @"GetSerialNumber", 
                                      @"GetAllSettings", 
                                      @"GetSecurityLevel", 
                                      @"GetEncryptionType", 
                                      @"GetDecodingMethod", 
                                      @"GetKeyManagementType", 
                                      @"GetTracksSelection",
                                      @"GetTrackSeparator", 
                                      @"GetTerminator", 
                                      @"GetTrack1Prefix", 
                                      @"GetTrack2Prefix", 
                                      @"GetTrack3Prefix", 
                                      @"GetTrack1Suffix", 
                                      @"GetTrack2Suffix", 
                                      @"GetTrack3Suffix",
                                      @"GetEnzyModuleFWVersion",
                                      @"GetEnzyBDAddress",
                                      @"GetKSN",
                                      nil];
    nextActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    nextActionSheet.tag = (int)_SELECT_Settings_Get_SHEET_TAG;
    [nextActionSheet showInView:self.view];
    [nextActionSheet release];
}
- (IBAction) f_SelectSettingsType_Get:(id)sender{
    [self showSelectSettingsType_Get_ActionSheet];
}

typedef enum {
    _I_GetFirmwareVersion = 0, 
    _I_GetSerialNumber, 
    _I_GetAllSettings, 
    _I_GetSecurityLevel, 
    _I_GetEncryptionType, 
    _I_GetDecodingMethod, 
    _I_GetKeyManagementType, 
    _I_GetTracksSelection, 
    _I_GetTrackSeparator, 
    _I_GetTerminator, 
    _I_GetTrack1Prefix, 
    _I_GetTrack2Prefix, 
    _I_GetTrack3Prefix, 
    _I_GetTrack1Suffix, 
    _I_GetTrack2Suffix, 
    _I_GetTrack3Suffix,
    _I_GetEnzyModuleFWversion,
    _I_GetEnzyBDAddress,
    _I_GetKSN
} SelectSettingsGet_List;

-(BOOL)GetSomeSettings: (int)index
{
    BOOL ret = NO;
    switch (index) {
        case _I_GetFirmwareVersion:
        {
            NSString *str = [BTmsrDevice GetFirmwareVersion];
            [self appendMessageToResults: [NSString stringWithFormat:@"GetFirmwareVersion: %@", str]];
        }
            break;
        case _I_GetSerialNumber:
        {
            NSString *str = [BTmsrDevice GetSerialNumber];
            [self appendMessageToResults: [NSString stringWithFormat:@"GetSerialNumber: %@", str]];
        }
            break;
        case _I_GetAllSettings:
        {
            NSData* rawResult = [BTmsrDevice GetAllSettings];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetAllSettings: %@", rawResult.description]];
        }
            break;
        case _I_GetSecurityLevel:
        {
            Byte byResult = [BTmsrDevice GetSecurityLevel];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetSecurityLevel: 0x%02X", byResult]];
        }
            break;
        case _I_GetEncryptionType:
        {
            Byte byResult = [BTmsrDevice GetEncryptionType];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetEncryptionType: 0x%02X", byResult]];
        }
            break;
        case _I_GetDecodingMethod:
        {
            Byte byResult = [BTmsrDevice GetDecodingMethod];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetDecodingMethod: 0x%02X", byResult]];
        }
            break;
        case _I_GetKeyManagementType:
        {
            Byte byResult = [BTmsrDevice GetKeyManagementType];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetKeyManagementType: 0x%02X", byResult]];
        }
            break;
        case _I_GetTracksSelection:
        {
            Byte byResult = [BTmsrDevice GetTracksSelection];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTracksSelection: 0x%02X", byResult]];
        }
            break;
        case _I_GetTrackSeparator:
        {
            Byte byResult = [BTmsrDevice GetTrackSeparator];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTrackSeparator: 0x%02X", byResult]];
        }
            break;
        case _I_GetTerminator:
        {
            Byte byResult = [BTmsrDevice GetTerminator];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTerminator: 0x%02X", byResult]];
        }
            break;
        case _I_GetTrack1Prefix:
        {
           NSString *str = [BTmsrDevice GetTrackPrefix: 1];
       
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTrack1Prefix: %@", str]];
        }
            break;
        case _I_GetTrack2Prefix:
        {
            NSString *str = [BTmsrDevice GetTrackPrefix: 2];
            
            
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTrack2Prefix: %@", str]];
        }
            break;
        case _I_GetTrack3Prefix:
        {
           NSString *str = [BTmsrDevice GetTrackPrefix: 3];
            
            
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTrack3Prefix: %@", str]];
        }
            break;
        case _I_GetTrack1Suffix:
        {
            NSString *str = [BTmsrDevice GetTrackSuffix: 1];
         
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTrack1Suffix: %@", str]];
        }
            break;
        case _I_GetTrack2Suffix:
        {
            NSString *str = [BTmsrDevice GetTrackSuffix: 2];
            
            
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTrack2Suffix: %@", str]];
        }
            break;
        case _I_GetTrack3Suffix:
        {
           NSString *str = [BTmsrDevice GetTrackSuffix: 3];
            
            
            [self appendMessageToResults:[NSString stringWithFormat:@"GetTrack3Suffix: %@", str]];
        }
            break;
        case _I_GetEnzyModuleFWversion:
        {
             NSString *str = [BTmsrDevice GetEnzyModuleFWVersion];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetEnzyModuleFWversion: %@", str]];
        }
            break;
        case _I_GetEnzyBDAddress:
        {
             NSString *str = [BTmsrDevice GetEnzyBDAddress];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetEnzyBDAddress: %@", str]];
        }
            break;
        case _I_GetKSN:
        {
            NSData* rawResult = [BTmsrDevice GetKSN];
            [self appendMessageToResults:[NSString stringWithFormat:@"GetKSN: %@", rawResult.description]];
        }
            break;
            //......
            
        default:
            ret = NO;
            break;
    }
    return ret;
}

-(void) showSelectSettingsType_Set_ActionSheet{
    UIActionSheet *nextActionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Settings" 
                                                                 delegate:self 
                                                        cancelButtonTitle:@"Cancel" 
                                                   destructiveButtonTitle:nil 
                                                        otherButtonTitles:
                        
                                      @"SetDecodingMethod", 
                                      @"SetEncryptionType", 
                                      @"SetKeyManagementType", 
                                      @"SetTracksSelection", 
                                      @"SetTrackSeparator", 
                                      @"SetTerminator", 
                                      @"SetTrack1Prefix", 
                                      @"SetTrack2Prefix", 
                                      @"SetTrack3Prefix", 
                                      @"SetTrack1Suffix", 
                                      @"SetTrack2Suffix", 
                                      @"SetTrack3Suffix", 
                                      @"SetMSREnable", 
                                      @"SetAllSettingDefault", 
                                      nil];
    nextActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    nextActionSheet.tag = (int)_SELECT_Settings_Set_SHEET_TAG;
    [nextActionSheet showInView:self.view];
    [nextActionSheet release];
}


- (IBAction) f_SelectSettingsType_Set:(id)sender{
    [self showSelectSettingsType_Set_ActionSheet];
}

typedef enum {
    _I_SetDecodingMethod=0,
    _I_SetEncryptionType, 
    _I_SetKeyManagementType, 
    _I_SetTracksSelection, 
    _I_SetTrackSeparator, 
    _I_SetTerminator, 
    _I_SetTrack1Prefix, 
    _I_SetTrack2Prefix, 
    _I_SetTrack3Prefix, 
    _I_SetTrack1Suffix, 
    _I_SetTrack2Suffix, 
    _I_SetTrack3Suffix, 
    _I_SetMSREnable, 
    _I_SetAllSettingDefault, 
} SelectSettingsSet_List;

-(BOOL)SetSomeSettings: (int)index
{
    BOOL ret = YES;
    switch (index) {
        //----
       /* case _I_SetPreamble:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetPreamble;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"Preamble (02 or other)"];
        }
            break;
            
        //----
        case _I_SetPostamble:
            {
                if (userInputAlert) {
                    [userInputAlert release];
                    userInputAlert = nil;
                }
                
                userInputAlert = [[InputAlert alloc] init];
                userInputAlert.tag = _I_SetPostamble;
                userInputAlert.delegate = self;
                [userInputAlert showWithTitle:@"Postamble (03 or other)"];

            }
            break;*/
            
        //----
        case _I_SetDecodingMethod:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetDecodingMethod;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"30 ... 34"];
        }
            break;
            
        //----
        case _I_SetEncryptionType:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetEncryptionType;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"1: TDES; 2: AES"];
        }
            break;
            
        //----
        case _I_SetKeyManagementType:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetKeyManagementType;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"0: Fixed; 1: DUKPT"];
        }
            break;
            
        //----
        case _I_SetTracksSelection:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTracksSelection;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"30 ... 39"];
        }
            break;
            
        //----
        case _I_SetTrackSeparator:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTrackSeparator;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"0D, 00 or others"];
        }
            break;
            
            
        //----
        case _I_SetTerminator:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTerminator;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"0D, 00 or others"];
        }
            break;
            
        //----
        case _I_SetTrack1Prefix:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTrack1Prefix;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"Track1Prefix:"];
        }
            break;
            
        //----
        case _I_SetTrack2Prefix:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTrack2Prefix;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"Track2Prefix:"];
        }
            break;
            
            //----
        case _I_SetTrack3Prefix:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTrack3Prefix;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"Track3Prefix:"];
        }
            break;
            
        //----
        case _I_SetTrack1Suffix:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTrack1Suffix;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"Track1Suffix:"];
        }
            break;

        //----
        case _I_SetTrack2Suffix:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTrack2Suffix;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"Track2Suffix:"];
        }
            break;
            
        //----
        case _I_SetTrack3Suffix:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetTrack3Suffix;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"Track3Suffix:"];
        }
            break;
                        
        //----
        case _I_SetMSREnable:
        {
            if (userInputAlert) {
                [userInputAlert release];
                userInputAlert = nil;
            }
            
            userInputAlert = [[InputAlert alloc] init];
            userInputAlert.tag = _I_SetMSREnable;
            userInputAlert.delegate = self;
            [userInputAlert showWithTitle:@"1: True; 0: False"];
        }
            break;

            //----
        case _I_SetAllSettingDefault:
        {
            UIActionSheet *actionSheet =[[UIActionSheet alloc]
                                         initWithTitle:@"Default" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Ok!" otherButtonTitles: nil];
            [actionSheet showInView:self.view];
            actionSheet.tag= DEFAULT_TAG;
        }
            break;
            
        default:
        {
            ret = NO;
            break;
        }
    }
    return ret;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == alertView.cancelButtonIndex) {
        
        switch (alertView.tag) {
            case 1:
            {  subPreAutherror=nil;
                flagerror=0;
            }
                break;
            default:
                break;
                
        }
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    NSString *result = nil;
    NSData *rawResult = nil;
    //NSData *response = nil;
    int normalizedButtonIdx = buttonIndex - actionSheet.firstOtherButtonIndex;
    
    [actionSheet dismissWithClickedButtonIndex:actionSheet.cancelButtonIndex animated:YES];
    
    switch (actionSheet.tag) {
        case MEMORY_CARD_TYPE_ACTION_SHEET_TAG:
        {
            /*
             BOOL b = [BTmsrDevice Do_SetMemoryCardType:(MemoryCardType)normalizedButtonIdx];
             NSString *  mct = nil;
             if((MemoryCardType)normalizedButtonIdx == 0)
             mct = @"I2c 3B Memory";
             else if((MemoryCardType)normalizedButtonIdx == 1)
             mct = @"I2c 4B Memory";
             else if((MemoryCardType)normalizedButtonIdx == 2)
             mct = @"SLE 44x8";
             else if((MemoryCardType)normalizedButtonIdx == 3)
             mct = @"SLE 44x2";
             else if((MemoryCardType)normalizedButtonIdx == 4)
             mct = @"GPM 276";
             else if((MemoryCardType)normalizedButtonIdx == 5)
             mct = @"GPM 271";
             else if((MemoryCardType)normalizedButtonIdx == 6)
             mct = @"SLE 4404 or AT88SC101";
             else if((MemoryCardType)normalizedButtonIdx == 7)
             mct = @"SLE 4406";
             
             if(b)
             [self appendMessageToResults:[NSString stringWithFormat:@"Set Memory Card Type %@ - Success",mct]];
             else
             [self appendMessageToResults:[NSString stringWithFormat:@"Set Memory Card Type %@ - failed",mct]]; 
             */
        }
            break;
            
        case LED_CONTROL_ACTION_SHEET_TAG:
        {
            /*
             if(![self checkLEDcontroltype])
             {
             if([BTmsrDevice Do_SetOperationMode:16])
             [self appendMessageToResults:@"Set LED Control by host"];
             else
             {
             [self appendMessageToResults:@"Set LED Control by host failed"];
             return;
             }
             }
             [self appendMessageToResults:[NSString stringWithFormat:@"Set LED: 0x%02x", (LEDControlCharacter)(0x30|normalizedButtonIdx)]]; 
             BOOL b = [self setLEDcontroltest:(LEDControlCharacter)(0x30|normalizedButtonIdx)];
             if (b) {
             
             b = [BTmsrDevice Do_SetOperationMode:ckbyte];
             if (b) {
             [self appendMessageToResults:@"Set LED OK."];
             return;
             }
             else{
             [self appendMessageToResults:@"Set LED failed. (set OperationMode back)."];
             return;
             }
             
             [self appendMessageToResults:@"Set LED OK."];
             return;
             }
             [self appendMessageToResults:@"Set LED failed!."];
             */
        }
            break;
        
        case _SELECT_Settings_Get_SHEET_TAG:
        {
            NSLog(@"%d", normalizedButtonIdx);
            [self GetSomeSettings:normalizedButtonIdx];
        }
            break;
        case _SELECT_Settings_Set_SHEET_TAG:
        {
            NSLog(@"%d", normalizedButtonIdx);
            [self SetSomeSettings:normalizedButtonIdx];
        }
            break;
        case  DEFAULT_TAG:
        {
            BOOL b= [BTmsrDevice  SetAllSettingDefault];
            BOOL b1=[BTmsrDevice SetPostamble:0x03];
            BOOL b2=[BTmsrDevice SetPreamble:0x02];
            BOOL b3=[BTmsrDevice SetErrorIndication];
            BOOL b4=[BTmsrDevice SetEnhance];
            if (b&&b1&&b2&&b3&&b4) {
                [self appendMessageToResults: @"SetAllSettingDefault, Success"];
            }
            else {
                [self appendMessageToResults: @"SetAllSettingDefault, Fail"];
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - Memory card

- (IBAction) f_SetMemoryCardType:(id)sender{
    [self showMemoryCardTypeActionSheet];
}

- (IBAction) f_LEDControl:(id)sender
{
    [self showLEDControlActionSheet];
}


- (IBAction) f_directIO:(id)sender
{
    [txtDirtData resignFirstResponder];

    NSData *dataBuffer = nil;
    BOOL bFormat = FALSE;
    int len1= txtDirtData.text.length;
    if (len1<1)
    {
        bFormat = FALSE;
    }
    else
    {
        dataBuffer = [self hexStringToBytes:txtDirtData.text];
        if ([dataBuffer length]>0) 
        {
            bFormat = TRUE;
        }
    }
    if (!bFormat){
        //[self appendMessageToResults:@"directIO command fail. Invalid parameter."];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"Invalid parameter" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }

    [self appendMessageToResults:[NSString stringWithFormat:@"directIO data: %@", dataBuffer.description]];

    NSData *dataResult = nil;
    
    dataResult = [BTmsrDevice directIO: dataBuffer];
    Byte * temp=(Byte*)[dataResult bytes];
    NSString *strresult=[[[NSString alloc] initWithBytes:temp length: dataResult.length encoding:NSASCIIStringEncoding] autorelease];
    [self appendMessageToResults:[NSString stringWithFormat:@"Response data Hex Format: %@", dataResult.description]];
    
    [self appendMessageToResults:[NSString stringWithFormat:@"Response data ASCII Format: %@", strresult]];

   
    return;
}


#pragma mark - CPU Card
-(NSData *)CheckInputString:(NSString *)valueEntered
{
    NSData *dataBuffer = nil;
    if (valueEntered.length < 2) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"input data length must be 1 bytes(1byte length )." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else
    {
        dataBuffer = [self hexStringToBytes:valueEntered];
        if (dataBuffer.length<1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                            message:@"input value is invalid." 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"Dismiss" 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
    }
    return dataBuffer;
}

-(void)inputAlert:(InputAlert *)inputAlert valueEntered:(NSString *)valueEntered{
    if (!valueEntered) {
        return;
    }
    NSData *dataBuffer = nil;
    switch (inputAlert.tag) {
        /*case _I_SetPreamble:
        {
            dataBuffer = [self CheckInputString: valueEntered];
            if (!dataBuffer) {
                return;
            }
            Byte* DBuffer = (Byte*)[dataBuffer bytes];
            BOOL b = [BTmsrDevice SetPreamble:DBuffer[0]]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetPreamble, %@", str]];
            return;
        }
            break;
            
        //-----
        case _I_SetPostamble:
        {
            dataBuffer = [self CheckInputString: valueEntered];
            if (!dataBuffer) {
                return;
            }
            Byte* DBuffer = (Byte*)[dataBuffer bytes];
            BOOL b = [BTmsrDevice SetPostamble:DBuffer[0]]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetPostamble, %@", str]];
            return;
        }
            break;*/
            
        //-----
        case _I_SetDecodingMethod:
        {
            dataBuffer = [self CheckInputString: valueEntered];
            if (!dataBuffer) {
                return;
            }
            Byte* DBuffer = (Byte*)[dataBuffer bytes];
            BOOL b = [BTmsrDevice SetDecodingMethod:DBuffer[0]]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetDecodingMethod, %@", str]];
            return;
        }
            break;
            
        //-----
        case _I_SetEncryptionType:
        {
            /*
            dataBuffer = [self CheckInputString: valueEntered];
            if (!dataBuffer) {
                return;
            }
            */
            Byte tmpBt = 0x00;
            if ([valueEntered isEqualToString:@"1"])
            {
                tmpBt = 0x31;
            }
            else if ([valueEntered isEqualToString:@"2"]) 
            {
                tmpBt = 0x32;
            }
            else {
                [self appendMessageToResults:@"SetEncryptionType fail, parameter error."];
                return;
            }
            BOOL b = [BTmsrDevice SetEncryptionType:tmpBt]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetEncryptionType, %@", str]];
            return;
        }
            break;
            
        //-----
        case _I_SetKeyManagementType:
        {
            Byte tmpBt = 0x00;
            if ([valueEntered isEqualToString:@"0"])
            {
                tmpBt = 0x30;
            }
            else if ([valueEntered isEqualToString:@"1"]) 
            {
                tmpBt = 0x31;
            }
            else {
                [self appendMessageToResults:@"SetKeyManagementType fail, parameter error."];
                return;
            }

            BOOL b = [BTmsrDevice SetKeyManagementType:tmpBt]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetKeyManagementType, %@", str]];
            return;
        }
            break;
            
        //-----
        case _I_SetTracksSelection:
        {
            dataBuffer = [self CheckInputString: valueEntered];
            if (!dataBuffer) {
                return;
            }
            Byte* DBuffer = (Byte*)[dataBuffer bytes];
            BOOL b = [BTmsrDevice SetTracksSelection:DBuffer[0]]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTracksSelection, %@", str]];
            return;
        }
            break;
            
        //-----
        case _I_SetTrackSeparator:
        {
            dataBuffer = [self CheckInputString: valueEntered];
            if (!dataBuffer) {
                return;
            }
            Byte* DBuffer = (Byte*)[dataBuffer bytes];
            BOOL b = [BTmsrDevice SetTrackSeparator:DBuffer[0]]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTrackSeparator, %@", str]];
            return;
        }
            break;
            
        //-----
        case _I_SetTerminator:
        {
            dataBuffer = [self CheckInputString: valueEntered];
            if (!dataBuffer) {
                return;
            }
            Byte* DBuffer = (Byte*)[dataBuffer bytes];
            BOOL b = [BTmsrDevice SetTerminator:DBuffer[0]]; 
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTerminator, %@", str]];
            return;
        }
            break;
           
            //----
        case _I_SetTrack1Prefix:
        {
            
            dataBuffer = [self StringToBytes:valueEntered];
            BOOL bFormat = FALSE;
            int len1= dataBuffer.length;
            if (len1<1||len1>6)
            {
                bFormat = FALSE;
            }
            else
            {
                
                bFormat = TRUE;
                
            }
            if (!bFormat){
                //[self appendMessageToResults:@"directIO command fail. Invalid parameter."];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid"
                                                                message:@"Invalid parameter"
                                                               delegate:nil
                                                      cancelButtonTitle:@"Dismiss"
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
            BOOL b = [BTmsrDevice SetTrackPrefix:TRACK1_ID :dataBuffer];
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTrackPrefix, Track1, %@", str]];
            return;
        }
            break;
            
            //----
        case _I_SetTrack2Prefix:
        {
            dataBuffer = [self StringToBytes:valueEntered];
            BOOL bFormat = FALSE;
            int len1= dataBuffer.length;
            if (len1<1||len1>6)
            {
                bFormat = FALSE;
            }
            else
            {
                
                bFormat = TRUE;
                
            }
            if (!bFormat){
                //[self appendMessageToResults:@"directIO command fail. Invalid parameter."];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid"
                                                                message:@"Invalid parameter"
                                                               delegate:nil
                                                      cancelButtonTitle:@"Dismiss"
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
       
            BOOL b = [BTmsrDevice SetTrackPrefix:TRACK2_ID :dataBuffer];
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTrackPrefix, Track2, %@", str]];
            return;
        }
            break;
            
            //----
        case _I_SetTrack3Prefix:
        {
            
            dataBuffer = [self StringToBytes:valueEntered];
            BOOL bFormat = FALSE;
            int len1= dataBuffer.length;
            if (len1<1||len1>6)
            {
                bFormat = FALSE;
            }
            else
            {
                
                bFormat = TRUE;
                
            }
            if (!bFormat){
                //[self appendMessageToResults:@"directIO command fail. Invalid parameter."];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid"
                                                                message:@"Invalid parameter"
                                                               delegate:nil
                                                      cancelButtonTitle:@"Dismiss"
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
        
            BOOL b = [BTmsrDevice SetTrackPrefix:TRACK3_ID :dataBuffer];
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTrackPrefix, Track3, %@", str]];
            return;
        }
            break;
            
        //----
        case _I_SetTrack1Suffix:
        {
            
            dataBuffer = [self StringToBytes:valueEntered];
            BOOL bFormat = FALSE;
            int len1= dataBuffer.length;
            if (len1<1||len1>6)
            {
                bFormat = FALSE;
            }
            else
            {
                
                bFormat = TRUE;
                
            }
            if (!bFormat){
                //[self appendMessageToResults:@"directIO command fail. Invalid parameter."];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid"
                                                                message:@"Invalid parameter"
                                                               delegate:nil
                                                      cancelButtonTitle:@"Dismiss"
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
            NSLog(@"%@",dataBuffer.description);
            BOOL b = [BTmsrDevice SetTrackSuffix:TRACK1_ID :dataBuffer];
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTrackSuffix, Track1, %@", str]];
            return;
        }
            break;
            
        //----
        case _I_SetTrack2Suffix:
        {
            
            dataBuffer = [self StringToBytes:valueEntered];
            BOOL bFormat = FALSE;
            int len1= dataBuffer.length;
            if (len1<1||len1>6)
            {
                bFormat = FALSE;
            }
            else
            {
               
                    bFormat = TRUE;
                
            }
            if (!bFormat){
                //[self appendMessageToResults:@"directIO command fail. Invalid parameter."];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid"
                                                                message:@"Invalid parameter"
                                                               delegate:nil
                                                      cancelButtonTitle:@"Dismiss"
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
            
                     BOOL b = [BTmsrDevice SetTrackSuffix:TRACK2_ID :dataBuffer];
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTrackSuffix, Track2, %@", str]];
            return;
        }
            break;
            
        //----
        case _I_SetTrack3Suffix:
        {
            
            dataBuffer = [self StringToBytes:valueEntered];
           
            BOOL bFormat = FALSE;
            int len1= dataBuffer.length;
            if (len1<1||len1>6)
            {
                bFormat = FALSE;
            }
            else
            {
                
                bFormat = TRUE;
                
            }
            if (!bFormat){
                //[self appendMessageToResults:@"directIO command fail. Invalid parameter."];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid"
                                                                message:@"Invalid parameter"
                                                               delegate:nil
                                                      cancelButtonTitle:@"Dismiss"
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
            BOOL b = [BTmsrDevice SetTrackSuffix: TRACK3_ID :dataBuffer];
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetTrackSuffix, Track3, %@", str]];
            return;
        }
            break;
            
        //-----
        case _I_SetMSREnable:
        {
            if (valueEntered.length<1) {
                return;
            }
            BOOL b = NO;
            if ([valueEntered isEqualToString:@"1"]) {
                b = [BTmsrDevice SetMSREnable:YES]; 
            }
            else if ([valueEntered isEqualToString:@"0"])
            {
                b = [BTmsrDevice SetMSREnable:NO];
            }
            else {
                b = NO;
            }
            
            NSString *str = @"Fail!";
            if (b) {
                str = @"Success";
            }
            [self appendMessageToResults:[NSString stringWithFormat:@"SetMSREnable, %@", str]];
            return;
        }
            break;

        default:
            break;
    }

    if(inputAlert.tag == READ_FILE_COMMAND_TAG)
    {
            if (valueEntered.length < 2) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                                message:@"input data length must be 1 bytes(1byte length )." 
                                                               delegate:nil 
                                                      cancelButtonTitle:@"Dismiss" 
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
            else
            {
                dataBuffer = [self hexStringToBytes:valueEntered];
                if (dataBuffer.length<1) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                                    message:@"input value is invalid." 
                                                                   delegate:nil 
                                                          cancelButtonTitle:@"Dismiss" 
                                                          otherButtonTitles:nil];
                    [alert show];
                    [alert release];
                    return;
                }
            }
            Byte* DBuffer = (Byte*)[dataBuffer bytes];
            //[self doWriteBinary:dataBuffer];
            NSData *resultData = [BTmsrDevice Quick_Read:DBuffer[0]]; 
            [self appendMessageToResults:[NSString stringWithFormat:@"Quick_Read Result: %@", resultData.description]];
    }
    else if(inputAlert.tag == VERIFY_COMMAND_TAG)
    {
        if (valueEntered.length < 1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                            message:@"input data can't be null." 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"Dismiss" 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        else
        {
            dataBuffer = [NSData dataWithBytes:valueEntered.UTF8String length: valueEntered.length ];//[self hexStringToBytes:valueEntered];
            if (dataBuffer.length<1) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                                message:@"input value is invalid." 
                                                               delegate:nil 
                                                      cancelButtonTitle:@"Dismiss" 
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
                return;
            }
        }
        
        //[self doWriteBinary:dataBuffer];
        NSData *resultData = [BTmsrDevice Quick_Verify:dataBuffer]; 
        [self appendMessageToResults:[NSString stringWithFormat:@"Quick_Verify Result: %@", resultData.description]];
    }
    else if(inputAlert.tag == APDU_T1Raw_READ_WRITE_TAG)
    {
    }
}

/*
- (IBAction) f_QuickRead:(id)sender{
    if (userInputAlert) {
        [userInputAlert release];
        userInputAlert = nil;
    }
    
    userInputAlert = [[InputAlert alloc] init];
    userInputAlert.tag = READ_FILE_COMMAND_TAG;
    userInputAlert.delegate = self;
    [userInputAlert showWithTitle:@"QuickRead(Length)"];
}

- (IBAction) f_QuickWrite:(id)sender{
    [txtQkWrtData resignFirstResponder];
    
    NSData *dataBuffer = nil;
    if (txtQkWrtData.text.length < 2)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"Invalid input data." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    else
    {
        dataBuffer = [self hexStringToBytes:txtQkWrtData.text];
        if (dataBuffer.length<1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                            message:@"input value is invalid." 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"Dismiss" 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
    }
    
    NSData *resultData = [BTmsrDevice Quick_Write:dataBuffer];
    [self appendMessageToResults:[NSString stringWithFormat:@"Quick_Write Result: %@", resultData.description]];
}
*/
- (IBAction) f_SendAPDUToCpuCard:(id)sender{
    [txtAPDUData resignFirstResponder];
    
    NSData *dataBuffer = nil;
    NSString *valueEntered = txtAPDUData.text;
    if (valueEntered.length < 2)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                        message:@"input APDU data is invalid." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Dismiss" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    else
    {
        dataBuffer = [self hexStringToBytes:valueEntered];
        if (dataBuffer.length<1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid" 
                                                            message:@"input value is invalid." 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"Dismiss" 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
    }
    
    NSData *resultData = [BTmsrDevice SendAPDUToCpuCard: swtchReadWrit.on :dataBuffer];
    [self appendMessageToResults:[NSString stringWithFormat:@"SendAPDUToCpuCard Result: %@", resultData.description]];

}

@end
