/*
 * Copyright (C) 2013 Thomas M. Alldread
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package va7ta.app.nimblesigsweepgen;

import va7ta.app.nimblesigsweepgen0r1.R;
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the main Activity that displays the current chat session.
 */
public class NimbleSigSweepGenMain extends Activity {
    // Debugging
    private static final String TAG = "NimbleSigSweepGenMain";
    private static final boolean D = true;// false true

    // Name of the bluetooth connected device
    protected String mConnectedDeviceName = null;
//    protected Handler mHandler;
    // Array adapter for the conversation thread
    protected ArrayAdapter<String> mConversationArrayAdapter;
    // Member object for the chat services
    private int g_ReplyStkPtr = 0;
    protected String[] g_ReplyStackStr={"","","","","","","","","",""}; // 10 string stack
    protected String g_LevelValueStr="";
//    private int nsigApp.g_BT_RXD_BfrPtr=0; //must maintain a sync relationship with BluetoothChatService.nsigApp.g_BT_RXD_BfrPtr
    

    // Message types sent from the BluetoothChatService Handler
    protected static final int MESSAGE_STATE_CHANGE = 1;
    protected static final int MESSAGE_READ = 2;
    protected static final int MESSAGE_WRITE = 3;
    protected static final int MESSAGE_DEVICE_NAME = 4;
    protected static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    protected static final String DEVICE_NAME = "device_name";
    protected static final String TOAST = "toast";

    // onActivityResult Return Codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;    
    private static final int REQUEST_ENABLE_BT = 3;
    private static final int PHASE_OFFSET_UPDATE_GEN_A = 4;
    private static final int PHASE_OFFSET_UPDATE_GEN_B = 5;
    private static final int OUTPUT_LEVEL_UPDATE_GEN_A = 6;
    private static final int OUTPUT_LEVEL_UPDATE_GEN_B = 7;
    private static final int AM_MOD_INDEX_UPDATE_GEN_A = 8;
    private static final int AM_MOD_INDEX_UPDATE_GEN_B = 9;
    private static final int FM_DEV_UPDATE_GEN_A = 10;
    private static final int FM_DEV_UPDATE_GEN_B = 11;
    private static final int MOD_FREQ_HZ_UPDATE = 12;
    private static final int SWEEP_GEN_RESULTS= 13;
    private static final int SWEEP_GEN_NEW_SETUP= 14;
    private static final int SWEEP_GEN_SET_CNTR_FREQ_HZ=15;
    
    // NimbleSig Generator status codes
    private static final int ALL_MOD_OFF = 0;
    private static final int GEN_A_AM = 1;
    private static final int GEN_A_FM = 2;
    private static final int GEN_B_AM = 3;
    private static final int GEN_B_FM = 4;
    private static final int GEN_A_ON  = 5;    
    private static final int GEN_A_OFF = 6;    
    private static final int GEN_B_ON  = 7;
    private static final int GEN_B_OFF = 8;
        
    private String g_GenA_Freq_StrippedStr="50000000";
    private String g_GenB_Freq_StrippedStr="100000000";

    /*
    private boolean mExternalStorageAvailable = false;
    private boolean mExternalStorageWriteable = false;
	*/

    private boolean g_RestoreNecessary_b=true;
    public boolean g_FreshStart_b = true;
    public boolean g_WasConnected_b = false;
    public boolean g_ConnectionLost_b = false;
    public boolean g_LevelPending_b=false;


    //NimbleSig settings variables
    protected int g_ModFreqHz_Int=1000;
    protected int g_PwrMeterCalMHz_Int=50;
    protected int g_GenA_FreqHz_Int=50000000;
    protected int g_GenB_FreqHz_Int=100000000;
    protected int g_GenA_Phase_mDeg_Int=0;
    protected int g_GenB_Phase_mDeg_Int=0;
    protected int g_GenA_Level_cBm_Int=-100;
    protected int g_GenB_Level_cBm_Int=-100;
    protected int g_GenA_AM_Index_Int=30;
    protected int g_GenB_AM_Index_Int=30;
    protected int g_GenA_FM_DevHz_Int=3000;
    protected int g_GenB_FM_DevHz_Int=3000;
    protected int g_GenA_PreviousAM_Level_cBm_Int=-160;
    protected int g_GenB_PreviousAM_Level_cBm_Int=-160;
    protected int g_NewGenA_AM_LevelAvail_Int=0;
    protected int g_NewGenB_AM_LevelAvail_Int=0;
    protected int g_GenModModeStatus_Int = ALL_MOD_OFF;    
    
    public int g_mChatServiceID=0;
    
    protected boolean g_GenA_Enabled_b = true;
    protected boolean g_GenB_Enabled_b = true;
    public boolean g_GenA_FM_Active_b =false;
    public boolean g_GenB_FM_Active_b =false;
    public boolean g_GenA_AM_Active_b =false;
    public boolean g_GenB_AM_Active_b =false;


    
    // Layout Views
//  private ListView mConversationView;
    
  private Button mExitButton;
  private Button mSendButton;
  private Button mRFLvlButton;
  private Button mVFOA_MHzBtn;
  private Button mVFOA_KHzBtn;
  private Button mVFOA_HzBtn;
  private Button mVFOB_MHzBtn;
  private Button mVFOB_KHzBtn;
  private Button mVFOB_HzBtn;
  private Button msetPhaseAButton;
  private Button msetPhaseBButton;
  private Button msetLevelAButton;
  private Button msetLevelBButton;
  private Button msetAM_ModIdxA_Btn;
  private Button msetFM_ModIdxA_Btn;
  private Button msetAM_ModIdxB_Btn;
  private Button msetFM_ModIdxB_Btn;
  private Button mModA_Off_Btn;
  private Button mModB_Off_Btn;
  private Button mKillA_Btn;
  private Button mKillB_Btn;
  private Button mSetLvlA_Btn;
  private Button mSetPhaseA_Btn;
  private Button mSetLvlB_Btn;
  private Button mSetPhaseB_Btn;
  private Button mModFreqHz_Btn;
  private Button mPowerLevel_Btn;
  private Button mSweepGenBtn_Btn;
  private TextView mLevelB_Lbl;
  private TextView mPhaseB_Lbl;
  private TextView mLevelA_Lbl;
  private TextView mPhaseA_Lbl;
  private TextView mModA_AM_Lbl;
  private TextView mModA_FM_Lbl;    
  private TextView mModB_AM_Lbl;
  private TextView mModB_FM_Lbl;
  
  private EditText mGenA_FreqEntry;
  private EditText mGenB_FreqEntry;
  private EditText mNSig_CmdEditor;
  private EditText mSetLvlCalMHz;
  
  
  
  // NimbleSig RF Generator commands
  private static final String NS_GEN_A_ATTEN_CMD_STR 		= "aa";
  private static final String NS_GEN_B_ATTEN_CMD_STR 		= "ab";
  private static final String NS_GEN_A_FREQ_HZ_CMD_STR 		= "FAH";
  private static final String NS_GEN_B_FREQ_HZ_CMD_STR 		= "FBH";
  private static final String NS_GEN_AB_FREQ_HZ_CMD_STR 	= "FXH";
  private static final String NS_GEN_A_FREQ_KHZ_CMD_STR 	= "FAK";
  private static final String NS_GEN_B_FREQ_KHZ_CMD_STR 	= "FBK";
  private static final String NS_GEN_AB_FREQ_KHZ_CMD_STR 	= "FXK";
  private static final String NS_GEN_A_FREQ_MHZ_CMD_STR 	= "FAM";
  private static final String NS_GEN_B_FREQ_MHZ_CMD_STR 	= "FBM";
  private static final String NS_GEN_AB_FREQ_MHZ_CMD_STR 	= "FXM";
  private static final String NS_READ_AVERAGE_POWER_CMD_STR	= "la";
  private static final String NS_GEN_A_AM_MOD_ON_CMD_STR 	= "ma";
  private static final String NS_GEN_B_AM_MOD_ON_CMD_STR 	= "mb";
  private static final String NS_GEN_FM_MOD_INDEX_CMD_STR 	= "md";    
  private static final String NS_GEN_A_FM_MOD_ON_CMD_STR 	= "mf";
  private static final String NS_GEN_B_FM_MOD_ON_CMD_STR 	= "mg";
  private static final String NS_GEN_AM_MOD_INDEX_CMD_STR 	= "mp";
  private static final String NS_GEN_AM_MOD_FREQ_CMD_STR 	= "mq";
  private static final String NS_MOD_OFF_BOTH_GENS_CMD_STR 	= "mx";
  private static final String NS_GEN_A_DISABLE_CMD_STR   	= "ka";
  private static final String NS_GEN_A_ENABLE_CMD_STR    	= "kk";
  private static final String NS_GEN_B_DISABLE_CMD_STR   	= "kb";
  private static final String NS_GEN_B_ENABLE_CMD_STR    	= "kl";
  private static final String NS_GEN_A_PHASE_CMD_STR    	= "pa";
  private static final String NS_GEN_B_PHASE_CMD_STR    	= "pb";
  

    
  // widget variable R.ID find name references
/*
  mModA_AM_Lbl =(TextView) findViewById(R.id.modA_AM_Lbl);
  msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
  mModA_FM_Lbl =(TextView) findViewById(R.id.modA_FM_Lbl);
  msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
  mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
  mGenA_FreqEntry =(EditText) findViewById(R.id.vfoA_FreqEnter);
  mPhaseA_Lbl =(TextView) findViewById(R.id.phaseA_Lbl);
  mSetLvlA_Btn =(Button) findViewById(R.id.setLvlA_Btn);
  mLevelA_Lbl =(TextView) findViewById(R.id.levelA_Lbl);
  mSetPhaseA_Btn =(Button) findViewById(R.id.setPhaseA_Btn);
  
  mPhaseB_Lbl =(TextView) findViewById(R.id.phaseB_Lbl);
  mModB_AM_Lbl =(TextView) findViewById(R.id.modB_AM_Lbl);
  mModB_FM_Lbl =(TextView) findViewById(R.id.modB_FM_Lbl);
  mLevelB_Lbl =(TextView) findViewById(R.id.levelB_Lbl);
  mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
  msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
  mSetLvlB_Btn =(Button) findViewById(R.id.setLvlB_Btn);
  mSetPhaseB_Btn =(Button) findViewById(R.id.setPhaseB_Btn);
  mGenB_FreqEntry =(EditText) findViewById(R.id.vfoB_FreqEnter);
  mNSig_CmdEditor =(EditText) findViewById(R.id.edit_text_out);
  mSetLvlCalMHz = (EditText) findViewById(R.id.setLvlCalMHz);
*/       
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");
    	restoreSweepGenSettings();

        // Set up the window layout
	    setContentView(R.layout.activity_nimble_sig_sweep_gen_main); 
    	// prevent default keyboard from popping up at beginning
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        NS3_App nsigApp = (NS3_App)getApplication();
	    nsigApp.gs_SweepGenMode_b=false;
        // If the adapter is null, then Bluetooth is not supported
        if (nsigApp.mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        // Initialize the compose field with a listener for the return key
        mNSig_CmdEditor = (EditText) findViewById(R.id.edit_text_out);
        mNSig_CmdEditor.setOnEditorActionListener(mWriteListener);


        // Initialize the exit button with a listener that for click events
        mExitButton = (Button) findViewById(R.id.exit);
        mExitButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Exit the app
            	finish();
            	return;
            }            
        });
       	
        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                mNSig_CmdEditor =(EditText) findViewById(R.id.edit_text_out);
                String message = mNSig_CmdEditor.getText().toString();
                sendMessage(message);
            }            
        });
       	
       // Initialise the VFO A set output Level button with a listener that for click events
        mSetLvlA_Btn = (Button) findViewById(R.id.setLvlA_Btn);
        mSetLvlA_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	TextView levelA_Value=(TextView) findViewById(R.id.setLvlA_Btn);
                String currentLevelA = levelA_Value.getText().toString();       	         	            	
            	Intent startSetLevelA=new Intent(getApplicationContext(), SetLevelA.class);
            	startSetLevelA.putExtra("valLevelA",currentLevelA);
            	byte amModStatusByte=0;
            	if(g_GenA_AM_Active_b)amModStatusByte=1;
            	startSetLevelA.putExtra("statusAM_ModGenA",amModStatusByte);            	
            	startActivityForResult(startSetLevelA,OUTPUT_LEVEL_UPDATE_GEN_A);
            }
        });               
        
        // Initialise the measure RF Level Calibration button with a listener that for click events
        mSetLvlCalMHz = (EditText) findViewById(R.id.setLvlCalMHz);
        mSetLvlCalMHz.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	mSetLvlCalMHz.setText("");
            }
        }); 
        
        // Initialise the measure RF Level button with a listener that for click events
        mRFLvlButton = (Button) findViewById(R.id.RFLevelBtn);
        mRFLvlButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	measureRF_Pwr();
            }
        }); 
                               
        mModA_Off_Btn = (Button) findViewById(R.id.modA_CW_Lbl);
        mModA_Off_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
        // Initialise the VFO A turn modulation off button with a listener that for click events            	
            	setGenA_ModOff();
            }
        });
        
        mModB_Off_Btn = (Button) findViewById(R.id.modB_CW_Lbl);
        mModB_Off_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Initialise the VFO B turn modulation off button with a listener that for click events            	
            	setGenB_ModOff();
            }
        });
        
        // Initialise the sweep generator button with a listener that for click events
        mSweepGenBtn_Btn =(Button) findViewById(R.id.sweepGenBtn);
        mSweepGenBtn_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Intent startSweepGen=new Intent(getApplicationContext(), SweepControl.class);
//            	startSweepGen.putExtra("chatService",nsigApp.mChatService);
//            	startActivityForResult(startSweepGen,SWEEP_GEN_RESULTS);
            	NS3_App.sg_SweepActivated = false;
            	startActivity(startSweepGen);
            }
        });
        
        // Initialise the modulation frequency set with a listener that for click events
        mModFreqHz_Btn =(Button) findViewById(R.id.modFreqHz_Btn);
        mModFreqHz_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Button presentModFrqHz=(Button) findViewById(R.id.modFreqHz_Btn);
                String currentModFrqHz = presentModFrqHz.getText().toString();       	         	            	
            	Intent startSetModFreqHz=new Intent(getApplicationContext(), SetModFreqHz.class);
            	startSetModFreqHz.putExtra("modFrqHzVal",currentModFrqHz);
            	startActivityForResult(startSetModFreqHz,MOD_FREQ_HZ_UPDATE);
            }
        });
        
        // Initialise the gen A kill signal button with a listener that for click events
        mKillA_Btn =(Button) findViewById(R.id.killA_Btn);
        mKillA_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if(!g_GenA_Enabled_b){
                	genA_Enable();
                	genA_Enable_View();                	
                }else{
                	genA_Disable();
                	genA_Disable_View();
                }
            }
        });

        // Initialise the gen B kill signal button with a listener that for click events
        mKillB_Btn =(Button) findViewById(R.id.killB_Btn);
        mKillB_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if(!g_GenB_Enabled_b){
                	genB_Enable();
                	genB_Enable_View();
                }else{
                	genB_Disable();
                	genB_Disable_View();
                }
            }
        });
        
        
        // Initialise the gen A FM modulation deviation button with a listener that for click events
        msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
        msetFM_ModIdxA_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	TextView presentModIdxA=(TextView) findViewById(R.id.modIndexFM_A);
                String currentFM_ModIdxA = presentModIdxA.getText().toString();       	         	            	
            	Intent startSetFMmodIdxA=new Intent(getApplicationContext(), SetGen_A_FM_Dev.class);
            	startSetFMmodIdxA.putExtra("valFM_DevHzA",currentFM_ModIdxA);
            	startActivityForResult(startSetFMmodIdxA,FM_DEV_UPDATE_GEN_A);
            }
        });
        
        // Initialise the gen B FM modulation deviation button with a listener that for click events
        msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
        msetFM_ModIdxB_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	TextView presentModIdxB=(TextView) findViewById(R.id.modIndexFM_B);
                String currentFM_ModIdxB = presentModIdxB.getText().toString();       	         	            	
            	Intent startSetFMmodIdxB=new Intent(getApplicationContext(), SetGen_B_FM_Dev.class);
            	startSetFMmodIdxB.putExtra("valFM_DevHzB",currentFM_ModIdxB);
            	startActivityForResult(startSetFMmodIdxB,FM_DEV_UPDATE_GEN_B);
            }
        });
        
        // Initialise the gen A AM modulation index button with a listener that for click events
        msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
        msetAM_ModIdxA_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	TextView presentModIdxA=(TextView) findViewById(R.id.modIndexAM_A);
                String currentAM_ModIdxA = presentModIdxA.getText().toString();       	         	            	
            	Intent startSetAMmodIdxA=new Intent(getApplicationContext(), SetGen_A_AM_ModIndex.class);
            	startSetAMmodIdxA.putExtra("valAM_ModIdxA",currentAM_ModIdxA);
            	startActivityForResult(startSetAMmodIdxA,AM_MOD_INDEX_UPDATE_GEN_A);
            }
        });
        
        // Initialise the gen B AM modulation index button with a listener that for click events
        msetAM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexAM_B);
        msetAM_ModIdxB_Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	TextView presentModIdxB=(TextView) findViewById(R.id.modIndexAM_B);
                String currentAM_ModIdxB = presentModIdxB.getText().toString();       	         	            	
            	Intent startSetAMmodIdxB=new Intent(getApplicationContext(), SetGen_B_AM_ModIndex.class);
            	startSetAMmodIdxB.putExtra("valAM_ModIdxB",currentAM_ModIdxB);
            	startActivityForResult(startSetAMmodIdxB,AM_MOD_INDEX_UPDATE_GEN_B);
            }
        });
        
        // Initialise the VFO B set output Level button with a listener that for click events
        msetLevelBButton = (Button) findViewById(R.id.setLvlB_Btn);
        msetLevelBButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	TextView levelB_Value=(TextView) findViewById(R.id.setLvlB_Btn);
                String currentLevelB = levelB_Value.getText().toString();       	         	            	
            	Intent startSetLevelB=new Intent(getApplicationContext(), SetLevelB.class);
            	startSetLevelB.putExtra("valLevelB",currentLevelB);
            	byte amModStatusByte=0;
            	if(g_GenB_AM_Active_b)amModStatusByte=1; //rem if AM mode active RF level reduced by 6dB
            	startSetLevelB.putExtra("statusAM_ModGenB",amModStatusByte);            	
            	startActivityForResult(startSetLevelB,OUTPUT_LEVEL_UPDATE_GEN_B);
            }
        });
        
        // Initialise the VFO A setPhase button with a listener that for click events
        msetPhaseAButton = (Button) findViewById(R.id.setPhaseA_Btn);
        msetPhaseAButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	String currentPhaseA = msetPhaseAButton.getText().toString();//"-45.5";//                 
            	Intent startSetPhaseA=new Intent(getApplicationContext(), SetPhaseA.class);// simpler
                startSetPhaseA.putExtra("valPhaseA",currentPhaseA);
            	startActivityForResult(startSetPhaseA,PHASE_OFFSET_UPDATE_GEN_A);
            }
        });
        
        // Initialise the VFO B setPhase button with a listener that for click events
        msetPhaseBButton = (Button) findViewById(R.id.setPhaseB_Btn);
        msetPhaseBButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String currentPhaseB = msetPhaseBButton.getText().toString();//"-45.5";// 
            	Intent startSetPhaseB=new Intent(getApplicationContext(), SetPhaseB.class);
                startSetPhaseB.putExtra("valPhaseB",currentPhaseB);
            	startActivityForResult(startSetPhaseB,PHASE_OFFSET_UPDATE_GEN_B);
            }
        });
        
        // Clear the GenA edit frequency display on entry and enable buttons
        mGenA_FreqEntry = (EditText) findViewById(R.id.vfoA_FreqEnter);
        mGenA_FreqEntry.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	mGenA_FreqEntry.setText("");
            	mVFOA_MHzBtn=(Button)findViewById(R.id.vfoA_MHzBtn);
            	mVFOA_MHzBtn.setEnabled(true);
            	mVFOA_MHzBtn.setTextColor(0xFF000000);
            	mVFOA_KHzBtn=(Button)findViewById(R.id.vfoA_KHzBtn);
            	mVFOA_KHzBtn.setEnabled(true);
            	mVFOA_KHzBtn.setTextColor(0xFF000000);
            	mVFOA_HzBtn=(Button)findViewById(R.id.vfoA_HzBtn);
            	mVFOA_HzBtn.setEnabled(true);
            	mVFOA_HzBtn.setTextColor(0xFF000000);
            }
        });       

        // Initialise the VFO A Frequency MHz button with a listener that for click events
        mVFOA_MHzBtn = (Button) findViewById(R.id.vfoA_MHzBtn);
        mVFOA_MHzBtn.setOnClickListener(new OnClickListener() {
           public void onClick(View v) {
        		setA_Freq_MHz_View();
        		setGenA_Freq();
            	mVFOA_MHzBtn.setEnabled(false);
            	mVFOA_MHzBtn.setTextColor(0xFFADB2C9);
            	mVFOA_KHzBtn.setEnabled(false);
            	mVFOA_KHzBtn.setTextColor(0xFFADB2C9);
            	mVFOA_HzBtn.setEnabled(false);
            	mVFOA_HzBtn.setTextColor(0xFFADB2C9);
            }
        });

        // Initialize the VFO A Frequency KHz button with a listener that for click events
        mVFOA_KHzBtn = (Button) findViewById(R.id.vfoA_KHzBtn);
        mVFOA_KHzBtn.setOnClickListener(new OnClickListener() {
           public void onClick(View v) {
        		setA_Freq_KHz_View();
        		setGenA_Freq();
            	mVFOA_MHzBtn.setEnabled(false);
            	mVFOA_MHzBtn.setTextColor(0xFFADB2C9);
            	mVFOA_KHzBtn.setEnabled(false);
            	mVFOA_KHzBtn.setTextColor(0xFFADB2C9);
            	mVFOA_HzBtn.setEnabled(false);
            	mVFOA_HzBtn.setTextColor(0xFFADB2C9);
            }
        });

        // Initialize the VFO A Frequency Hz button with a listener that for click events
        mVFOA_HzBtn  = (Button) findViewById(R.id.vfoA_HzBtn);
        mVFOA_HzBtn.setOnClickListener(new OnClickListener() {
           public void onClick(View v) {
        		setA_Freq_Hz_View();
        		setGenA_Freq();
    			try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
            	mVFOA_MHzBtn.setEnabled(false);
            	mVFOA_MHzBtn.setTextColor(0xFFADB2C9);
            	mVFOA_KHzBtn.setEnabled(false);
            	mVFOA_KHzBtn.setTextColor(0xFFADB2C9);
            	mVFOA_HzBtn.setEnabled(false);
            	mVFOA_HzBtn.setTextColor(0xFFADB2C9);
            }
        });
        
        
        // Clear the GenB edit frequency display on entry and enable buttons
        mGenB_FreqEntry = (EditText) findViewById(R.id.vfoB_FreqEnter);
        mGenB_FreqEntry.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	mGenB_FreqEntry.setText("");
            	mVFOB_MHzBtn=(Button)findViewById(R.id.vfoB_MHzBtn);
            	mVFOB_MHzBtn.setEnabled(true);
            	mVFOB_MHzBtn.setTextColor(0xFF000000);
            	mVFOB_KHzBtn=(Button)findViewById(R.id.vfoB_KHzBtn);
            	mVFOB_KHzBtn.setEnabled(true);
            	mVFOB_KHzBtn.setTextColor(0xFF000000);
            	mVFOB_HzBtn=(Button)findViewById(R.id.vfoB_HzBtn);
            	mVFOB_HzBtn.setEnabled(true);
            	mVFOB_HzBtn.setTextColor(0xFF000000);
            }
        });       

        // Initialize the VFO B Frequency MHz button with a listener that for click events
        mVFOB_MHzBtn = (Button) findViewById(R.id.vfoB_MHzBtn);
        mVFOB_MHzBtn.setOnClickListener(new OnClickListener() {
           public void onClick(View v) {
        		setB_Freq_MHz_View();            		
        		setGenB_Freq();
            	mVFOB_MHzBtn.setEnabled(false);
            	mVFOB_MHzBtn.setTextColor(0xFFADB2C9);
            	mVFOB_KHzBtn.setEnabled(false);
            	mVFOB_KHzBtn.setTextColor(0xFFADB2C9);
            	mVFOB_HzBtn.setEnabled(false);
            	mVFOB_HzBtn.setTextColor(0xFFADB2C9);
            }
        });
        
        // Initialize the VFO B Frequency KHz button with a listener that for click events
        mVFOB_KHzBtn = (Button) findViewById(R.id.vfoB_KHzBtn);
        mVFOB_KHzBtn.setOnClickListener(new OnClickListener() {
           public void onClick(View v) {        	   
        		setB_Freq_KHz_View();            		
        		setGenB_Freq();
            	mVFOB_MHzBtn.setEnabled(false);
            	mVFOB_MHzBtn.setTextColor(0xFFADB2C9);
            	mVFOB_KHzBtn.setEnabled(false);
            	mVFOB_KHzBtn.setTextColor(0xFFADB2C9);
            	mVFOB_HzBtn.setEnabled(false);
            	mVFOB_HzBtn.setTextColor(0xFFADB2C9);
            }
        });

        // Initialize the VFO B Frequency Hz button with a listener that for click events
        mVFOB_HzBtn  = (Button) findViewById(R.id.vfoB_HzBtn);
        mVFOB_HzBtn.setOnClickListener(new OnClickListener() {
           public void onClick(View v) {
        		setB_Freq_Hz_View();            		
        		setGenB_Freq();
            	mVFOB_MHzBtn.setEnabled(false);
            	mVFOB_MHzBtn.setTextColor(0xFFADB2C9);
            	mVFOB_KHzBtn.setEnabled(false);
            	mVFOB_KHzBtn.setTextColor(0xFFADB2C9);
            	mVFOB_HzBtn.setEnabled(false);
            	mVFOB_HzBtn.setTextColor(0xFFADB2C9);
        }
        });

        /*
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but all we need
            //  to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }*/
    } // onCreate ==============================================================================

    @Override
    protected void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");
        // If BT is not on, request that it be enabled.
        // setupComPath() will then be called during onActivityResult
        NS3_App nsigApp = (NS3_App)getApplication();
        if (!nsigApp.mBluetoothAdapter.isEnabled()) {
        		enableBT();
        // Otherwise, setup the session
        } else {
            if (nsigApp.mChatService == null) setupComPath();
        }
    }//onStart ================================================================================

    @Override
    protected synchronized void onResume() {
        super.onResume();
    	restoreSweepGenSettings();
        if(D) Log.e(TAG, "+ ON RESUME +");      
        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        NS3_App nsigApp = (NS3_App)getApplication();
	    nsigApp.gs_SweepGenMode_b=false;
    	NS3_App.nimbleSigSweepGenMainHandler=mHandler;
        sendMessage("EX");//disable human interface echos

        if (nsigApp.mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (nsigApp.mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
            	nsigApp.mChatService.start();
            }
        }
        if(g_RestoreNecessary_b){
        	restoreViewSettings();
        	g_RestoreNecessary_b=false;
        }
    } //onResume ===============================================================================
    
    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
        saveSettings();        
    }//onPause ===================================================================================

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    	g_RestoreNecessary_b=true;
        saveSettings();
    }
    //onStop ===================================================================================

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if(D) Log.e(TAG, "--- ON DESTROY ---");
        NS3_App nsigApp = (NS3_App)getApplication();
        if (nsigApp.mChatService != null) nsigApp.mChatService.stop();
    }//onDestroy ================================================================================


    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener 
    mWriteListener = new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };

    
	private void setGenA_ModOff(){
		genAB_ModOff();
		g_GenModModeStatus_Int = ALL_MOD_OFF;
	    genA_ModOff_View();
	    setGenA_Level(g_GenA_Level_cBm_Int);
	    setGenA_LevelView(g_GenA_Level_cBm_Int);
	}
    
	private void setGenB_ModOff(){
	    genAB_ModOff();
	    g_GenModModeStatus_Int = ALL_MOD_OFF;
	    genB_ModOff_View();
	    setGenB_Level(g_GenB_Level_cBm_Int);
	    setGenB_LevelView(g_GenB_Level_cBm_Int);                
	}

	
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);                
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE_SECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, true);
            }
            break;
        case REQUEST_CONNECT_DEVICE_INSECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, false);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up bluetooth comm session
                setupComPath();
            } else {
                // User did not enable Bluetooth or an error occurred
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_LONG).show();
                finish();
            }
            break;
        case PHASE_OFFSET_UPDATE_GEN_A:
            // When SetPhaseA Activity returns with a new phase offset value
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valPhaseA")) {
                    String degrees = data.getStringExtra("valPhaseA");//.getString("valPhaseA");
                    float milliDegrees = 1000*Float.valueOf(degrees);
                    if(milliDegrees<0)milliDegrees+=360000;
                    if((milliDegrees>359999)|(milliDegrees<0))milliDegrees=0;// final data range check
                    g_GenA_Phase_mDeg_Int=(int)milliDegrees;
                    setGenA_Phase(g_GenA_Phase_mDeg_Int);
                    setGenA_PhaseView(g_GenA_Phase_mDeg_Int);
                }
            }
            break;
        case PHASE_OFFSET_UPDATE_GEN_B:
            // When SetPhaseB Activity returns with a new phase offset value
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valPhaseB")) {
                    String degrees = data.getStringExtra("valPhaseB");//.getString("valPhaseB");
                    float milliDegrees = 1000*Float.valueOf(degrees);
                    if(milliDegrees<0)milliDegrees+=360000;
                    if((milliDegrees>359999)|(milliDegrees<0))milliDegrees=0;// final data range check
                    g_GenB_Phase_mDeg_Int=(int)milliDegrees;
                    setGenB_Phase(g_GenB_Phase_mDeg_Int);
                    setGenB_PhaseView(g_GenB_Phase_mDeg_Int);
                }
            }
            break;
            
        case OUTPUT_LEVEL_UPDATE_GEN_A:
            // When SetLevelA Activity returns with a new RF output level in dBm
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valLevelA")) {
                    String dBm = data.getStringExtra("valLevelA");
                    float centiBm_Flt = 10*Float.valueOf(dBm);
                    g_GenA_Level_cBm_Int = (int)centiBm_Flt;
                    if(g_GenA_AM_Active_b){
                    	g_NewGenA_AM_LevelAvail_Int=1;
                    	g_GenA_PreviousAM_Level_cBm_Int=g_GenA_Level_cBm_Int;
                    }else g_NewGenA_AM_LevelAvail_Int=0;
                    setGenA_Level(g_GenA_Level_cBm_Int);
                    setGenA_LevelView(g_GenA_Level_cBm_Int);
                }
            }
            break;
            
        case OUTPUT_LEVEL_UPDATE_GEN_B:
            // When SetLevelA Activity returns with a new RF output level in dBm
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valLevelB")) {
                    String dBm = data.getStringExtra("valLevelB");
                    float centiBm_Flt = 10*Float.valueOf(dBm);
                    g_GenB_Level_cBm_Int = (int)centiBm_Flt;
                    if(g_GenB_AM_Active_b){
                    	g_NewGenB_AM_LevelAvail_Int=1;
                    	g_GenB_PreviousAM_Level_cBm_Int=g_GenB_Level_cBm_Int;
                    }else g_NewGenB_AM_LevelAvail_Int=0;                    
                    setGenB_Level(g_GenB_Level_cBm_Int);
                    setGenB_LevelView(g_GenB_Level_cBm_Int);
                }
            }
            break;

        case FM_DEV_UPDATE_GEN_A :
            // When gen A set FM deviation Activity returns with a new FM deviation value
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valFM_DevHzA")) {
                    String fmDevHz_Str = data.getStringExtra("valFM_DevHzA");
                    int fmDevHz_Int = Integer.valueOf(fmDevHz_Str);
                    g_GenA_FM_DevHz_Int = setFM_Deviation(fmDevHz_Int);//check and send the new dev value to NS
                    if(g_GenA_AM_Active_b){
                    	g_GenA_Level_cBm_Int += 60;
                        setGenA_LevelView(g_GenA_Level_cBm_Int);
                    }else if(g_GenB_AM_Active_b){
                    	g_GenB_Level_cBm_Int += 60;
                        setGenB_LevelView(g_GenB_Level_cBm_Int);
                    }
        	        genAB_ModOff();
                	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
                	activateFM_ModGenA();
                	labelFM_ModGenA_View();
                    selectFM_ModGenA();
                }
            }
            break;
          
        case FM_DEV_UPDATE_GEN_B :
            // When gen A set FM deviation Activity returns with a new FM deviation value
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valFM_DevHzB")) {
                    String fmDevHz_Str = data.getStringExtra("valFM_DevHzB");
                    int fmDevHz_Int = Integer.valueOf(fmDevHz_Str);
                    g_GenB_FM_DevHz_Int = setFM_Deviation(fmDevHz_Int);//check and send the new dev value to NS
                    if(g_GenA_AM_Active_b){
                    	g_GenA_Level_cBm_Int += 60;
                        setGenA_LevelView(g_GenA_Level_cBm_Int);
                    }else if(g_GenB_AM_Active_b){
                    	g_GenB_Level_cBm_Int += 60;
                        setGenB_LevelView(g_GenB_Level_cBm_Int);
                    }
        	        genAB_ModOff();
                	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
                	activateFM_ModGenB();
                	labelFM_ModGenB_View();                }
                	selectFM_ModGenB();
            }
            break;
          
        case AM_MOD_INDEX_UPDATE_GEN_A:
            // When SetAM_modIndexA Activity returns with a new mod index %
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valModAMIdxA")) {
                    String amModIdx_Str = data.getStringExtra("valModAMIdxA");
                    g_GenA_AM_Index_Int = Integer.valueOf(amModIdx_Str);
                    setAM_ModIndexGenA_View();//range check and set indicator text                    
                    setAM_ModIndex(g_GenA_AM_Index_Int);//set the NS mod index
                	setGenA_ModOff();
                	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
                	setGenB_ModOff();
                	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
                    activateAM_ModGenA();
                    labelAM_ModGenA_View();
                    selectAM_ModGenA();
                    g_NewGenA_AM_LevelAvail_Int=0;
                    setGenA_Level(g_GenA_Level_cBm_Int);
                    setGenA_LevelView(g_GenA_Level_cBm_Int);
                }
            }
            break;
            
        case AM_MOD_INDEX_UPDATE_GEN_B:
            // When SetAM_modIndexB Activity returns with a new mod index %
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valModAMIdxB")) {
                    String amModIdx_Str = data.getStringExtra("valModAMIdxB");
                    g_GenB_AM_Index_Int = Integer.valueOf(amModIdx_Str);
                    setAM_ModIndexGenB_View();//range check and set indicator text                    
                    setAM_ModIndex(g_GenB_AM_Index_Int);//set the NS mod index
                	setGenA_ModOff();
                	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
                	setGenB_ModOff();
                	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
                    activateAM_ModGenB();
                    labelAM_ModGenB_View();
                    selectAM_ModGenB();
                    g_NewGenB_AM_LevelAvail_Int=0;
                    setGenB_Level(g_GenB_Level_cBm_Int);
                    setGenB_LevelView(g_GenB_Level_cBm_Int);
                }
            }
            break;
            
         case MOD_FREQ_HZ_UPDATE:
            // When SetAM_modIndexA Activity returns with a new mod index %
            if (resultCode == Activity.RESULT_OK) {
                if (data.hasExtra("valModFrqHzA")) {
                    String modFrqHzStr = data.getStringExtra("valModFrqHzA");
                    g_ModFreqHz_Int=Integer.valueOf(modFrqHzStr);
                    setModFreq(g_ModFreqHz_Int);
                    setModFreqView(g_ModFreqHz_Int);
                }
            }
            break;
                       
       }
    }

	private void measureRF_Pwr(){
		TextView calMHz = (TextView) findViewById(R.id.setLvlCalMHz);
	    String calFreqStr = calMHz.getText().toString();
	    g_PwrMeterCalMHz_Int = Integer.valueOf(calFreqStr);
	    measureRF_Pwr_dBm(g_PwrMeterCalMHz_Int);
	}

    
    private void genA_Disable_View(){
    	g_GenA_Enabled_b=false;
        mKillA_Btn =(Button) findViewById(R.id.killA_Btn);
		mKillA_Btn.setText("StartA");
		selectionIndicators(GEN_A_OFF);
    }
    

    private void genA_Enable_View(){    	
    	g_GenA_Enabled_b=true;
        mKillA_Btn =(Button) findViewById(R.id.killA_Btn);
		mKillA_Btn.setText("Kill A");
		selectionIndicators(GEN_A_ON);
    }
    
    private void genB_Disable_View(){
    	g_GenB_Enabled_b=false;
        mKillB_Btn =(Button) findViewById(R.id.killB_Btn);
		mKillB_Btn.setText("StartB");
		selectionIndicators(GEN_B_OFF);
    }
		
    
    private void genB_Enable_View(){
    	g_GenB_Enabled_b=true;
        mKillB_Btn =(Button) findViewById(R.id.killB_Btn);
		mKillB_Btn.setText("Kill B");
		selectionIndicators(GEN_B_ON);
    }
    
    private void labelFM_ModGenA_View(){ //provides indicators
        mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
        mModA_Off_Btn.setText("FM Off");
        String fmDevHzDelimited_Str=spaceDelimiter(g_GenA_FM_DevHz_Int);
        msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
        msetFM_ModIdxA_Btn.setText(fmDevHzDelimited_Str);
    }
    
    private void selectFM_ModGenA(){
    	g_GenModModeStatus_Int=GEN_A_FM;
        selectionIndicators(g_GenModModeStatus_Int);    	
        g_GenA_FM_Active_b =true;
        g_GenB_FM_Active_b =false;
        g_GenA_AM_Active_b =false;
        g_GenB_AM_Active_b =false;    	
    }
    	  
    private void labelFM_ModGenB_View(){ //provides indicators and sends the mod cmd to NS   	
        mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
        mModB_Off_Btn.setText("FM Off");
        String fmDevHzDelimited_Str=spaceDelimiter(g_GenB_FM_DevHz_Int);
        msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
        msetFM_ModIdxB_Btn.setText(fmDevHzDelimited_Str);
    }
    
    private void selectFM_ModGenB(){
    	g_GenModModeStatus_Int=GEN_B_FM;
        selectionIndicators(g_GenModModeStatus_Int);    	
        g_GenA_FM_Active_b =false;
        g_GenB_FM_Active_b =true;
        g_GenA_AM_Active_b =false;
        g_GenB_AM_Active_b =false;
    }
    	    
    private void labelAM_ModGenA_View(){ //provides indicators   	
        mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
        mModA_Off_Btn.setText("AM Off");
    }
    
    private void selectAM_ModGenA(){
    	g_GenModModeStatus_Int=GEN_A_AM;
        selectionIndicators(g_GenModModeStatus_Int);
        g_GenA_FM_Active_b =false;
        g_GenB_FM_Active_b =false;
        g_GenA_AM_Active_b =true;
        g_GenB_AM_Active_b =false;
    }
    
    private void labelAM_ModGenB_View(){  //provides indicators
        mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
        mModB_Off_Btn.setText("AM Off");
    }
    
    private void selectAM_ModGenB(){
    	g_GenModModeStatus_Int=GEN_B_AM;
        selectionIndicators(g_GenModModeStatus_Int);
        g_GenA_FM_Active_b =false;
        g_GenB_FM_Active_b =false;
        g_GenA_AM_Active_b =false;
        g_GenB_AM_Active_b =true;        
    }
    
    private void setRF_LevelMeterCal_View(){ //range checks and sets the indicator text value
        String calFreqStr = String.valueOf(g_PwrMeterCalMHz_Int);
    	TextView calMHzView = (TextView) findViewById(R.id.setLvlCalMHz);
        calMHzView.setText(calFreqStr);
    }
    
    private void setAM_ModIndexGenA_View(){ //range checks and sets the indicator text value
    	if(g_GenA_AM_Index_Int <1)g_GenA_AM_Index_Int=1;
    	if(g_GenA_AM_Index_Int >99)g_GenA_AM_Index_Int=99;
        msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
        msetAM_ModIdxA_Btn.setText(String.valueOf(g_GenA_AM_Index_Int));    	
    }
    
    private void setAM_ModIndexGenB_View(){ //range checks and sets the indicator text value
    	if(g_GenB_AM_Index_Int <1)g_GenB_AM_Index_Int=1;
    	if(g_GenB_AM_Index_Int >99)g_GenB_AM_Index_Int=99;    	
        msetAM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexAM_B);
        msetAM_ModIdxB_Btn.setText(String.valueOf(g_GenB_AM_Index_Int));    	
    }

    private void setAM_ModIndex(int AM_Index_Int){ //sets the NS AM mod index
    	setAM_ModIdx(AM_Index_Int);
        try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS for NS
    }

        //check and send the new dev value to NS
    private int setFM_Deviation(int fmDevHz_Int){
        setFM_Dev(fmDevHz_Int);
        try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS for NS
    	return fmDevHz_Int;
    }
    
    private void setGenA_PhaseView(int mDeg){
    	float milliDegrees = mDeg;
        if(milliDegrees>180000)milliDegrees-=360000;
        String phaseStr=String.valueOf(milliDegrees/1000);
        mSetPhaseA_Btn =(Button) findViewById(R.id.setPhaseA_Btn);
        mSetPhaseA_Btn.setText(phaseStr);//(String.valueOf(milliDegrees/1000));
    }
    
    private void setGenB_PhaseView(int mDeg){
    	float milliDegrees = mDeg;
        if(milliDegrees>180000)milliDegrees-=360000;
        String phaseStr=String.valueOf(milliDegrees/1000);
        mSetPhaseB_Btn =(Button) findViewById(R.id.setPhaseB_Btn);
        mSetPhaseB_Btn.setText(phaseStr);//(String.valueOf(milliDegrees/1000));
    }
   
    private void setGenA_LevelView(int level_cBm_Int){    	
    	float dBmOut =(float)level_cBm_Int/10;
        mSetLvlA_Btn =(Button) findViewById(R.id.setLvlA_Btn);
    	mSetLvlA_Btn.setText(String.valueOf(dBmOut));
    }
    
    private void setGenB_LevelView(int level_cBm_Int){    	
    	float dBmOut =(float)level_cBm_Int/10;
        mSetLvlB_Btn =(Button) findViewById(R.id.setLvlB_Btn);
    	mSetLvlB_Btn.setText(String.valueOf(dBmOut));
    }

    private void setModFreqView(int freqHz_int){
    	String delimitedStr=spaceDelimiter(g_ModFreqHz_Int);
        mModFreqHz_Btn =(Button) findViewById(R.id.modFreqHz_Btn);
    	mModFreqHz_Btn.setText(delimitedStr);
    }
        
    private void setGenA_Freq(){
    	if(g_GenA_FreqHz_Int != g_GenB_FreqHz_Int)setGenA_Fq(g_GenA_FreqHz_Int);    		
    	else setGenAB_Fq(g_GenA_FreqHz_Int);//set both gens to same freq    	
    }
    
    private void setGenB_Freq(){
    	if(g_GenA_FreqHz_Int != g_GenB_FreqHz_Int)setGenB_Fq(g_GenB_FreqHz_Int);    		
    	else setGenAB_Fq(g_GenB_FreqHz_Int);//set both gens to same freq    	
    }

    private void setA_Freq_MHz_View() {
    	EditText vfoA_FreqIn = (EditText) findViewById(R.id.vfoA_FreqEnter);
        String vfoA_Freq = vfoA_FreqIn.getText().toString();
        if(vfoA_Freq.length()==0) {
            updateGenA_FreqDisp(g_GenA_FreqHz_Int);
        }else{
	        g_GenA_Freq_StrippedStr=stripSpaces(vfoA_Freq);
	        g_GenA_FreqHz_Int=1000000*Integer.valueOf(g_GenA_Freq_StrippedStr);
	        if(g_GenA_FreqHz_Int>200000000){
	        	vfoA_Freq="200";
	        	g_GenA_FreqHz_Int=200000000;
	        }
	        updateGenA_FreqDisp(g_GenA_FreqHz_Int);
	        vfoA_FreqIn.clearFocus();
        }
    }
 
    private void setA_Freq_KHz_View() {
    	EditText vfoA_FreqIn = (EditText) findViewById(R.id.vfoA_FreqEnter);
        String vfoA_Freq = vfoA_FreqIn.getText().toString();
        if(vfoA_Freq.length()==0) {
            updateGenA_FreqDisp(g_GenA_FreqHz_Int);
        }else{
	        g_GenA_Freq_StrippedStr=stripSpaces(vfoA_Freq);
	        g_GenA_FreqHz_Int=1000*Integer.valueOf(g_GenA_Freq_StrippedStr);
	        if(g_GenA_FreqHz_Int>200000000){
	        	vfoA_Freq="200";
	        	g_GenA_FreqHz_Int=200000000;
	        }
	        if(g_GenA_FreqHz_Int<100000){
	        	vfoA_Freq="100";
	        	g_GenA_FreqHz_Int=100000;
	        }
	        updateGenA_FreqDisp(g_GenA_FreqHz_Int);
	        vfoA_FreqIn.clearFocus();
        }
    }
    
    private void setA_Freq_Hz_View() {		
        mGenA_FreqEntry =(EditText) findViewById(R.id.vfoA_FreqEnter);
    	String vfoA_Freq = mGenA_FreqEntry.getText().toString();
        if(vfoA_Freq.length()==0) {
            updateGenA_FreqDisp(g_GenA_FreqHz_Int);
        }else{
	        g_GenA_Freq_StrippedStr=stripSpaces(vfoA_Freq);
	        g_GenA_FreqHz_Int=Integer.valueOf(g_GenA_Freq_StrippedStr);
	        if(g_GenA_FreqHz_Int>200000000){
	        	vfoA_Freq="200000000";
	        	g_GenA_FreqHz_Int=200000000;
	        }
	        if(g_GenA_FreqHz_Int<100000){
	        	vfoA_Freq="100000";
	        	g_GenA_FreqHz_Int=100000;
	        }
	        updateGenA_FreqDisp(g_GenA_FreqHz_Int);
	        mGenA_FreqEntry =(EditText) findViewById(R.id.vfoA_FreqEnter);
	        mGenA_FreqEntry.clearFocus();
        }
    }  
    


    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        Toast.makeText(this, savedInstanceState .getString("Previous Instance Data Restored"), Toast.LENGTH_LONG).show();
    	g_GenA_FreqHz_Int = savedInstanceState.getInt("pGenA_FreqHz_Int");
    	g_GenB_FreqHz_Int = savedInstanceState.getInt("pGenB_FreqHz_Int");
    	g_GenA_Phase_mDeg_Int = savedInstanceState.getInt("pGenA_Phase_mDeg_Int");
    	g_GenB_Phase_mDeg_Int = savedInstanceState.getInt("pGenB_Phase_mDeg_Int");
    	g_GenA_Level_cBm_Int = savedInstanceState.getInt("pGenA_Level_cBm_Int");
    	g_GenB_Level_cBm_Int = savedInstanceState.getInt("pGenB_Level_cBm_Int");
    	g_GenA_AM_Index_Int = savedInstanceState.getInt("pGenA_AM_Index_Int");
    	g_GenB_AM_Index_Int = savedInstanceState.getInt("pGenB_AM_Index_Int");
    	g_GenA_FM_DevHz_Int = savedInstanceState.getInt("pGenA_FM_DevHz_Int");
    	g_GenB_FM_DevHz_Int = savedInstanceState.getInt("pGenB_FM_DevHz_Int");
    	g_GenA_Enabled_b = savedInstanceState.getBoolean("pGenA_Enabled_b");
    	g_GenB_Enabled_b = savedInstanceState.getBoolean("pGenB_Enabled_b");
    	g_GenModModeStatus_Int = savedInstanceState.getInt("pGenOpModeStatus_Int");
    	g_ModFreqHz_Int = savedInstanceState.getInt("pModFreqHz_Int");
    	g_GenA_PreviousAM_Level_cBm_Int = savedInstanceState.getInt("pGenA_PrevAM_ModLvl_Int");
    	g_GenB_PreviousAM_Level_cBm_Int = savedInstanceState.getInt("pGenB_PrevAM_ModLvl_Int");
    	g_NewGenA_AM_LevelAvail_Int = savedInstanceState.getInt("p_NewGenA_AM_LevelAvail_Int");
    	g_NewGenB_AM_LevelAvail_Int = savedInstanceState.getInt("p_NewGenB_AM_LevelAvail_Int");
    	NS3_App.sg_SweepCenterFreqHz = savedInstanceState.getInt("p_sg_SweepCenterFreqHz_Int");
    	NS3_App.sg_SweepSpanFreqHz = savedInstanceState.getInt("p_sg_SweepSpanFreqHz");
    	NS3_App.sg_NormalizeMode_b = savedInstanceState.getBoolean("p_sg_NormalizeMode_b");
    	NS3_App.sg_10dB_Div_Yaxis_b = savedInstanceState.getBoolean("sg_10dB_Div_Yaxis_b");
    	NS3_App.sg_Yaxis_DynamicRange_dB_Int = savedInstanceState.getInt("p_sg_Yaxis_DynamicRange_dB_Int");
    	NS3_App.sg_Yaxis_RefLevel_dBm_Int = savedInstanceState.getInt("p_sg_Yaxis_RefLevel_dBm_Int");
    	NS3_App.sg_SweepTime_mS_Int = savedInstanceState.getInt("p_sg_SweepTime_mS_Int");
    	NS3_App.sg_Scale_dB_Div_Int = savedInstanceState.getInt("p_sg_Scale_dB_Div_Int");
    	NS3_App.sg_2dB_DivRefLvl_Int = savedInstanceState.getInt("p_sg_2dB_DivRefLvl_Int");
    	NS3_App.sg_Scale_dB_Div_Int = savedInstanceState.getInt("p_sg_Scale_dB_Div_Int");
    	NS3_App.sg_HzPerStep_Int = savedInstanceState.getInt("p_sg_HzPerStep_Int");
    	NS3_App.sg_HzPerDiv_Int = savedInstanceState.getInt("p_sg_HzPerDiv_Int");
    	NS3_App.sg_StepsPerSweep = savedInstanceState.getInt("p_sg_StepsPerSweep");
    	NS3_App.sg_SweepStopFreqHz = savedInstanceState.getInt("p_sg_SweepStopFreqHz");
    	NS3_App.sg_SweepStartFreqHz = savedInstanceState.getInt("p_sg_SweepStartFreqHz");
    	NS3_App.sMeasuredRFLevel_dBm_Str = savedInstanceState.getString("p_sMeasuredRFLevel_dBm_Str");
    	NS3_App.sg_HzPerDiv_Int_Str = savedInstanceState.getString("p_sg_HzPerDiv_Int_Str");
    	g_PwrMeterCalMHz_Int = savedInstanceState.getInt("pPwrMeterCalMHz_Int");
    }
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
    	super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt("pGenA_FreqHz_Int", g_GenA_FreqHz_Int);
        savedInstanceState.putInt("pGenB_FreqHz_Int", g_GenB_FreqHz_Int);
        savedInstanceState.putInt("pGenA_Phase_mDeg_Int", g_GenA_Phase_mDeg_Int);
        savedInstanceState.putInt("pGenB_Phase_mDeg_Int", g_GenB_Phase_mDeg_Int);
        savedInstanceState.putInt("pGenA_Level_cBm_Int", g_GenA_Level_cBm_Int);
        savedInstanceState.putInt("pGenB_Level_cBm_Int", g_GenB_Level_cBm_Int);
        savedInstanceState.putInt("pGenA_AM_Index_Int", g_GenA_AM_Index_Int);
        savedInstanceState.putInt("pGenB_AM_Index_Int", g_GenB_AM_Index_Int);
        savedInstanceState.putInt("pGenA_FM_DevHz_Int", g_GenA_FM_DevHz_Int);
        savedInstanceState.putInt("pGenB_FM_DevHz_Int", g_GenB_FM_DevHz_Int);
        savedInstanceState.putBoolean("pGenA_Enabled_b", g_GenA_Enabled_b);
        savedInstanceState.putBoolean("pGenB_Enabled_b", g_GenB_Enabled_b);
        savedInstanceState.putInt("pGenOpModeStatus_Int", g_GenModModeStatus_Int);
        savedInstanceState.putInt("pModFreqHz_Int", g_ModFreqHz_Int);
        savedInstanceState.putInt("pGenA_PrevAM_ModLvl_Int", g_GenA_PreviousAM_Level_cBm_Int);
        savedInstanceState.putInt("pGenB_PrevAM_ModLvl_Int", g_GenB_PreviousAM_Level_cBm_Int);
        savedInstanceState.putInt("p_NewGenA_AM_LevelAvail_Int", g_NewGenA_AM_LevelAvail_Int);
        savedInstanceState.putInt("p_NewGenB_AM_LevelAvail_Int", g_NewGenB_AM_LevelAvail_Int);        
        savedInstanceState.putInt("p_sg_SweepCenterFreqHz_Int", NS3_App.sg_SweepCenterFreqHz);        
        savedInstanceState.putInt("p_sg_SweepSpanFreqHz", NS3_App.sg_SweepSpanFreqHz);        
        savedInstanceState.putBoolean("p_sg_NormalizeMode_b", NS3_App.sg_NormalizeMode_b);        
        savedInstanceState.putBoolean("sg_10dB_Div_Yaxis_b", NS3_App.sg_10dB_Div_Yaxis_b);    
        savedInstanceState.putInt("p_sg_Yaxis_DynamicRange_dB_Int", NS3_App.sg_Yaxis_DynamicRange_dB_Int);        
        savedInstanceState.putInt("p_sg_Yaxis_RefLevel_dBm_Int", NS3_App.sg_Yaxis_RefLevel_dBm_Int);        
        savedInstanceState.putInt("p_sg_SweepTime_mS_Int", NS3_App.sg_SweepTime_mS_Int);        
        savedInstanceState.putInt("p_sg_Scale_dB_Div_Int", NS3_App.sg_Scale_dB_Div_Int);        
        savedInstanceState.putInt("p_sg_2dB_DivRefLvl_Int", NS3_App.sg_2dB_DivRefLvl_Int);        
        savedInstanceState.putInt("p_sg_Scale_dB_Div_Int", NS3_App.sg_Scale_dB_Div_Int);        
        savedInstanceState.putInt("p_sg_HzPerStep_Int", NS3_App.sg_HzPerStep_Int);        
        savedInstanceState.putInt("p_sg_HzPerDiv_Int", NS3_App.sg_HzPerDiv_Int);        
        savedInstanceState.putInt("p_sg_StepsPerSweep", NS3_App.sg_StepsPerSweep);        
        savedInstanceState.putInt("p_sg_SweepStopFreqHz", NS3_App.sg_SweepStopFreqHz);        
        savedInstanceState.putInt("p_sg_SweepStartFreqHz", NS3_App.sg_SweepStartFreqHz);         
        savedInstanceState.putString("p_sMeasuredRFLevel_dBm_Str", NS3_App.sMeasuredRFLevel_dBm_Str); 
        savedInstanceState.putString("p_sg_HzPerDiv_Int_Str", NS3_App.sg_HzPerDiv_Int_Str); 
        mSetLvlCalMHz = (EditText) findViewById(R.id.setLvlCalMHz);
        String calFreq = mSetLvlCalMHz.getText().toString();
        g_PwrMeterCalMHz_Int=Integer.valueOf(calFreq);
        savedInstanceState.putInt("pPwrMeterCalMHz_Int", g_PwrMeterCalMHz_Int);        
    	}
    
    protected void saveSettings(){    	
        SharedPreferences mPrefs = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putInt("pGenA_FreqHz_Int", g_GenA_FreqHz_Int);
        editor.putInt("pGenB_FreqHz_Int", g_GenB_FreqHz_Int);
        editor.putInt("pGenA_Phase_mDeg_Int", g_GenA_Phase_mDeg_Int);
        editor.putInt("pGenB_Phase_mDeg_Int", g_GenB_Phase_mDeg_Int);
        editor.putInt("pGenA_Level_cBm_Int", g_GenA_Level_cBm_Int);
        editor.putInt("pGenB_Level_cBm_Int", g_GenB_Level_cBm_Int);
        editor.putInt("pGenA_AM_Index_Int", g_GenA_AM_Index_Int);
        editor.putInt("pGenB_AM_Index_Int", g_GenB_AM_Index_Int);
        editor.putInt("pGenA_FM_DevHz_Int", g_GenA_FM_DevHz_Int);
        editor.putInt("pGenB_FM_DevHz_Int", g_GenB_FM_DevHz_Int);
        editor.putBoolean("pGenA_Enabled_b", g_GenA_Enabled_b);
        editor.putBoolean("pGenB_Enabled_b", g_GenB_Enabled_b);
        editor.putInt("pGenOpModeStatus_Int", g_GenModModeStatus_Int);
        editor.putInt("pModFreqHz_Int", g_ModFreqHz_Int);
        editor.putInt("pGenA_PrevAM_ModLvl_Int", g_GenA_PreviousAM_Level_cBm_Int);
        editor.putInt("pGenB_PrevAM_ModLvl_Int", g_GenB_PreviousAM_Level_cBm_Int);
        editor.putInt("p_NewGenA_AM_LevelAvail_Int", g_NewGenA_AM_LevelAvail_Int);
        editor.putInt("p_NewGenB_AM_LevelAvail_Int", g_NewGenB_AM_LevelAvail_Int);        
        editor.putInt("p_sg_SweepCenterFreqHz_Int", NS3_App.sg_SweepCenterFreqHz);        
        editor.putInt("p_sg_SweepSpanFreqHz", NS3_App.sg_SweepSpanFreqHz);        
        editor.putBoolean("p_sg_NormalizeMode_b", NS3_App.sg_NormalizeMode_b);        
        editor.putBoolean("sg_10dB_Div_Yaxis_b", NS3_App.sg_10dB_Div_Yaxis_b);    
        editor.putInt("p_sg_Yaxis_DynamicRange_dB_Int", NS3_App.sg_Yaxis_DynamicRange_dB_Int);        
        editor.putInt("p_sg_Yaxis_RefLevel_dBm_Int", NS3_App.sg_Yaxis_RefLevel_dBm_Int);        
        editor.putInt("p_sg_SweepTime_mS_Int", NS3_App.sg_SweepTime_mS_Int);        
        editor.putInt("p_sg_Scale_dB_Div_Int", NS3_App.sg_Scale_dB_Div_Int);        
        editor.putInt("p_sg_2dB_DivRefLvl_Int", NS3_App.sg_2dB_DivRefLvl_Int);        
        editor.putInt("p_sg_Scale_dB_Div_Int", NS3_App.sg_Scale_dB_Div_Int);        
        editor.putInt("p_sg_2dB_DivRefLvl_Int", NS3_App.sg_2dB_DivRefLvl_Int);        
        editor.putInt("p_sg_HzPerStep_Int", NS3_App.sg_HzPerStep_Int);        
        editor.putInt("p_sg_HzPerDiv_Int", NS3_App.sg_HzPerDiv_Int);        
        editor.putInt("p_sg_StepsPerSweep", NS3_App.sg_StepsPerSweep);        
        editor.putInt("p_sg_SweepStopFreqHz", NS3_App.sg_SweepStopFreqHz);        
        editor.putInt("p_sg_SweepStartFreqHz", NS3_App.sg_SweepStartFreqHz);         
        editor.putString("p_sMeasuredRFLevel_dBm_Str", NS3_App.sMeasuredRFLevel_dBm_Str); 
        editor.putString("p_sg_HzPerDiv_Int_Str", NS3_App.sg_HzPerDiv_Int_Str); 
        mSetLvlCalMHz = (EditText) findViewById(R.id.setLvlCalMHz);
        String calFreq = mSetLvlCalMHz.getText().toString();
        g_PwrMeterCalMHz_Int=Integer.valueOf(calFreq);
        editor.putInt("pPwrMeterCalMHz_Int", g_PwrMeterCalMHz_Int);        
        editor.commit();
        if(D) Log.d(TAG, "saveSettings - NimbleSig Generator Integer value Settings");                
    }
    
    public void restoreSweepGenSettings(){ //restore sweep gen values
        SharedPreferences mPrefs = getPreferences(Context.MODE_PRIVATE);
    	NS3_App.sg_SweepCenterFreqHz = mPrefs.getInt("p_sg_SweepCenterFreqHz_Int", 0);
    	NS3_App.sg_SweepSpanFreqHz =  mPrefs.getInt("p_sg_SweepSpanFreqHz", 0);    	
    	NS3_App.sg_NormalizeMode_b =  mPrefs.getBoolean("p_sg_NormalizeMode_b", false);
    	NS3_App.sg_10dB_Div_Yaxis_b =  mPrefs.getBoolean("p_sg_10dB_Div_Yaxis_b", true);
    	NS3_App.sg_Yaxis_RefLevel_dBm_Int =  mPrefs.getInt("p_sg_Yaxis_RefLevel_dBm_Int", 0);    	
    	NS3_App.sg_Yaxis_RefLevel_dBm_Int =  mPrefs.getInt("p_sg_Yaxis_RefLevel_dBm_Int", 0);    	
    	NS3_App.sg_Scale_dB_Div_Int =  mPrefs.getInt("p_sg_Scale_dB_Div_Int", 0);    	
    	NS3_App.sg_2dB_DivRefLvl_Int =  mPrefs.getInt("p_sg_2dB_DivRefLvl_Int", 0);    	
    	NS3_App.sg_Scale_dB_Div_Int =  mPrefs.getInt("p_sg_Scale_dB_Div_Int", 0);    	
    	NS3_App.sg_2dB_DivRefLvl_Int =  mPrefs.getInt("p_sg_2dB_DivRefLvl_Int", 0);    	
    	NS3_App.sg_HzPerStep_Int =  mPrefs.getInt("p_sg_HzPerStep_Int", 0);    	
    	NS3_App.sg_HzPerDiv_Int =  mPrefs.getInt("p_sg_HzPerDiv_Int", 0);    	
    	NS3_App.sg_StepsPerSweep =  mPrefs.getInt("p_sg_StepsPerSweep", 0);    	
    	NS3_App.sg_SweepStartFreqHz =  mPrefs.getInt("p_sg_SweepStartFreqHz", 0);    	
    	NS3_App.sMeasuredRFLevel_dBm_Str =  mPrefs.getString("p_sMeasuredRFLevel_dBm_Str", null);    	
    	NS3_App.sg_HzPerDiv_Int_Str =  mPrefs.getString("p_sg_HzPerDiv_Int_Str", null);    	
    }
    
    public void restoreViewSettings(){ //restore GUI view values
        SharedPreferences mPrefs = getPreferences(Context.MODE_PRIVATE);
        g_NewGenA_AM_LevelAvail_Int = mPrefs.getInt("p_NewGenA_AM_LevelAvail_Int", 0);
        g_NewGenB_AM_LevelAvail_Int = mPrefs.getInt("p_NewGenB_AM_LevelAvail_Int", 0);
        g_GenModModeStatus_Int = mPrefs.getInt("pGenOpModeStatus_Int", 0);
        g_GenA_FreqHz_Int = mPrefs.getInt("pGenA_FreqHz_Int", 50000000);
        	restoreGenAFreq_View();
        g_GenB_FreqHz_Int = mPrefs.getInt("pGenB_FreqHz_Int", 100000000);
        	restoreGenBFreq_View();  
        g_GenA_Phase_mDeg_Int = mPrefs.getInt("pGenA_Phase_mDeg_Int", 0);
        	setGenA_PhaseView(g_GenA_Phase_mDeg_Int);
        g_GenB_Phase_mDeg_Int = mPrefs.getInt("pGenB_Phase_mDeg_Int", 0);
        	setGenB_PhaseView(g_GenB_Phase_mDeg_Int);
        g_GenA_Level_cBm_Int = mPrefs.getInt("pGenA_Level_cBm_Int", -100);
        	setGenA_LevelView(g_GenA_Level_cBm_Int);
        g_GenB_Level_cBm_Int = mPrefs.getInt("pGenB_Level_cBm_Int", -100);
        g_GenA_PreviousAM_Level_cBm_Int = mPrefs.getInt("pGenA_PrevAM_ModLvl_Int", -160);
        g_GenB_PreviousAM_Level_cBm_Int = mPrefs.getInt("pGenB_PrevAM_ModLvl_Int", -160);
        	setGenB_LevelView(g_GenB_Level_cBm_Int);
        g_GenA_AM_Index_Int = mPrefs.getInt("pGenA_AM_Index_Int", 30);
        	setAM_ModIndexGenA_View();//range check and set indicator text                    
        g_GenB_AM_Index_Int = mPrefs.getInt("pGenB_AM_Index_Int", 30);
        	setAM_ModIndexGenB_View();//range check and set indicator text                    
        g_GenA_FM_DevHz_Int = mPrefs.getInt("pGenA_FM_DevHz_Int", 3000);
        	labelFM_ModGenA_View();
        g_GenB_FM_DevHz_Int = mPrefs.getInt("pGenB_FM_DevHz_Int", 5000);
        	labelFM_ModGenB_View();        
            switch (g_GenModModeStatus_Int) {
            case ALL_MOD_OFF:
            	genA_ModOff_View();
            	genB_ModOff_View();
                break;
            case GEN_A_AM:
                selectAM_ModGenA();
                labelAM_ModGenA_View();
                break;
            case GEN_B_AM:
                selectAM_ModGenB();
                labelAM_ModGenB_View();
                break;
            case GEN_A_FM:
                selectFM_ModGenA();
            	labelFM_ModGenA_View();
                break;
            case GEN_B_FM:
                selectFM_ModGenB();
            	labelFM_ModGenB_View();
                break;             
            }    
        g_ModFreqHz_Int = mPrefs.getInt("pModFreqHz_Int", 400);
        	setModFreqView(g_ModFreqHz_Int);
        g_PwrMeterCalMHz_Int = mPrefs.getInt("pPwrMeterCalMHz_Int", 100);
        	setRF_LevelMeterCal_View();
        g_GenA_Enabled_b = mPrefs.getBoolean("pGenA_Enabled_b", true);
        	if(g_GenA_Enabled_b)genA_Enable_View();
        	else genA_Disable_View();
        g_GenB_Enabled_b = mPrefs.getBoolean("pGenB_Enabled_b", true);
        	if(g_GenB_Enabled_b)genB_Enable_View();
        	else genB_Disable_View();
            if(D) Log.d(TAG, "View Settings Restored");                
    }

	protected void restoreNSGenSettings(){ //sync NS RF generator to GUI settings
    	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
        

		if(g_GenA_Enabled_b)genA_Enable();
        else genA_Disable();
        	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
        if(g_GenB_Enabled_b)genB_Enable();
        else genB_Disable();
        	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		switch (g_GenModModeStatus_Int) {
        case ALL_MOD_OFF:
        	bothGen_ModOff();//
            break;
        case GEN_A_AM:
        	activateAM_ModGenA();
            break;
        case GEN_B_AM:
        	activateAM_ModGenB();
            break;
        case GEN_A_FM:
        	activateFM_ModGenA();
            break;
        case GEN_B_FM:
        	activateFM_ModGenB();
            break;             
        }    
			try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		setGenA_Fq(g_GenA_FreqHz_Int);
			try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		setGenB_Fq(g_GenB_FreqHz_Int);
			try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		setGenA_Phase(g_GenA_Phase_mDeg_Int);
    		try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
    	setGenB_Phase(g_GenB_Phase_mDeg_Int);
    		try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		if(g_GenB_AM_Active_b)setAM_ModIdx(g_GenB_AM_Index_Int);      
		else setAM_ModIdx(g_GenA_AM_Index_Int);      
    		try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		if(g_GenA_FM_Active_b)setFM_Dev(g_GenA_FM_DevHz_Int);
		else setFM_Dev(g_GenB_FM_DevHz_Int);
    		try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
    	setModFreq(g_ModFreqHz_Int);
    		try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
    	g_NewGenA_AM_LevelAvail_Int=0;
    	setGenA_Level(g_GenA_Level_cBm_Int);
			try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		g_NewGenB_AM_LevelAvail_Int=0;
		setGenA_Level(g_GenB_Level_cBm_Int);
			try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
		measureRF_Pwr_dBm(g_PwrMeterCalMHz_Int);
			try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
	}
	
    
	private void restoreGenAFreq_View(){
    	String numberStr=String.valueOf(g_GenA_FreqHz_Int);
        mGenA_FreqEntry =(EditText) findViewById(R.id.vfoA_FreqEnter);
        mGenA_FreqEntry.setText(numberStr);
        setA_Freq_Hz_View();    	
    }
    private void restoreGenBFreq_View(){
    	String numberStr=String.valueOf(g_GenB_FreqHz_Int);
        mGenB_FreqEntry =(EditText) findViewById(R.id.vfoB_FreqEnter);
        mGenB_FreqEntry.setText(numberStr);
        setB_Freq_Hz_View();    	
    }
    
    private void setB_Freq_MHz_View() {
    	EditText vfoB_FreqIn = (EditText) findViewById(R.id.vfoB_FreqEnter);
        String vfoB_Freq_Str = vfoB_FreqIn.getText().toString();
        if(vfoB_Freq_Str.length()==0) {
            updateGenB_FreqDisp(g_GenB_FreqHz_Int);
        }else{
	        g_GenB_Freq_StrippedStr=stripSpaces(vfoB_Freq_Str);
	        g_GenB_FreqHz_Int=1000000*Integer.valueOf(g_GenB_Freq_StrippedStr);
	        if(g_GenB_FreqHz_Int>200000000){
	        	vfoB_Freq_Str="200";
	        	g_GenB_FreqHz_Int=200000000;
	        }
	        updateGenB_FreqDisp(g_GenB_FreqHz_Int);
	        vfoB_FreqIn.clearFocus();
        }
    }
    
    protected void setB_Freq_KHz_View() {
        // Send a message using content of the edit text widget
    	EditText vfoB_FreqIn = (EditText) findViewById(R.id.vfoB_FreqEnter);
        String vfoB_Freq_Str = vfoB_FreqIn.getText().toString();
        if(vfoB_Freq_Str.length()==0) {
            updateGenB_FreqDisp(g_GenB_FreqHz_Int);
        }else{
	        g_GenB_Freq_StrippedStr=stripSpaces(vfoB_Freq_Str);
	        g_GenB_FreqHz_Int=1000*Integer.valueOf(g_GenB_Freq_StrippedStr);
	        if(g_GenB_FreqHz_Int>200000000){
	        	vfoB_Freq_Str="200";
	        	g_GenB_FreqHz_Int=200000000;
	        }
	        if(g_GenB_FreqHz_Int<100000){
	        	vfoB_Freq_Str="100";
	        	g_GenB_FreqHz_Int=100000;
	        }
	        updateGenB_FreqDisp(g_GenB_FreqHz_Int);
	        vfoB_FreqIn.clearFocus();
        }
    }
    
    private void setB_Freq_Hz_View() {
        // Send a message using content of the edit text widget
    	EditText vfoB_FreqIn = (EditText) findViewById(R.id.vfoB_FreqEnter);
        String vfoB_Freq_Str = vfoB_FreqIn.getText().toString();
        if(vfoB_Freq_Str.length()==0) {
            updateGenB_FreqDisp(g_GenB_FreqHz_Int);
        }else{
	        g_GenB_Freq_StrippedStr=stripSpaces(vfoB_Freq_Str);
	        g_GenB_FreqHz_Int=Integer.valueOf(g_GenB_Freq_StrippedStr);
	        if(g_GenB_FreqHz_Int>200000000){
	        	vfoB_Freq_Str="200000000";
	        	g_GenB_FreqHz_Int=200000000;
	        }
	        if(g_GenB_FreqHz_Int<100000){
	        	vfoB_Freq_Str="100000";
	        	g_GenB_FreqHz_Int=100000;
	        }
	        updateGenB_FreqDisp(g_GenB_FreqHz_Int);
	        vfoB_FreqIn.clearFocus();
        }
    }
    
    //delimit MHz, KHz, Hz with spaces and update entry
    private void updateGenA_FreqDisp(int freq){
     	String tempStr = spaceDelimiter(freq);
        mGenA_FreqEntry =(EditText) findViewById(R.id.vfoA_FreqEnter);
     	mGenA_FreqEntry.setText(tempStr);
    }
       
    //delimit MHz, KHz, Hz with spaces and update entry
    private void updateGenB_FreqDisp(int freq){ 
     	String tempStr = spaceDelimiter(freq);
        mGenB_FreqEntry =(EditText) findViewById(R.id.vfoB_FreqEnter);
     	mGenB_FreqEntry.setText(tempStr);    	
    }
    
    // convert int to string and add space delimiters for GUI display
    private String spaceDelimiter(int freq_Int){
    	String freqDelimited_Str = String.valueOf(freq_Int);
        char tempChr[]=freqDelimited_Str.toCharArray();
        int l=freqDelimited_Str.length();
        int space1=l-4;
        int space2=l-7;
        String tempStr="";
        for(int i=0;i<l;i++){
        	tempStr+=String.valueOf(tempChr[i]);
        	if((i==space1)|(i==space2))tempStr+=' ';
        }     	
    	return tempStr;
    }

    private String stripSpaces(String str){
        int l=str.length();
        int i=0;
        char tempChr[]=str.toCharArray();
        String tempStr="";
        while(i<l){
        	if(tempChr[i] !=' '){
        		tempStr+=String.valueOf(tempChr[i]);
        	}
        	i++;
        }
    	return tempStr;
    }
        
    private void selectionIndicators(int mode) {
        switch (mode) {
        case GEN_A_AM:
            mModA_AM_Lbl =(TextView) findViewById(R.id.modA_AM_Lbl);
            mModA_AM_Lbl.setBackgroundColor(0xFF51A61F);//0xFFEDD6AB
            msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
            msetAM_ModIdxA_Btn.setBackgroundColor(0xFF51A61F);//0xFFEDD6AB
            mModA_FM_Lbl =(TextView) findViewById(R.id.modA_FM_Lbl);
            mModA_FM_Lbl.setBackgroundColor(0xFFDEB999);//0xFF51A61F
            msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
            msetFM_ModIdxA_Btn.setBackgroundColor(0xFFDEB999);//0xFF51A61F
            mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
            mModA_Off_Btn.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F 
            genB_ModOff_View();
            break;
            
        case GEN_A_FM:
            mModA_AM_Lbl =(TextView) findViewById(R.id.modA_AM_Lbl);
            mModA_AM_Lbl.setBackgroundColor(0xFFEDD6AB);//0xFFEDD6AB //0xFF51A61F
            msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
            msetAM_ModIdxA_Btn.setBackgroundColor(0xFFEDD6AB);// 0xFF51A61F
            mModA_FM_Lbl =(TextView) findViewById(R.id.modA_FM_Lbl);
            mModA_FM_Lbl.setBackgroundColor(0xFF51A61F);// 0xFFDEB999
            msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
            msetFM_ModIdxA_Btn.setBackgroundColor(0xFF51A61F);//0xFF51A61F //0xFFDEB999
            mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
            mModA_Off_Btn.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F 
            genB_ModOff_View();
            break;
            
        case GEN_B_AM:
            mModB_AM_Lbl =(TextView) findViewById(R.id.modB_AM_Lbl);
            mModB_AM_Lbl.setBackgroundColor(0xFF51A61F);//0xFFEDD6AB
            msetAM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexAM_B);
            msetAM_ModIdxB_Btn.setBackgroundColor(0xFF51A61F);//0xFFEDD6AB
            mModB_FM_Lbl =(TextView) findViewById(R.id.modB_FM_Lbl);
            mModB_FM_Lbl.setBackgroundColor(0xFFDEB999);//0xFF51A61F
            msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
            msetFM_ModIdxB_Btn.setBackgroundColor(0xFFDEB999);//0xFF51A61F
            mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
            mModB_Off_Btn.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F 
            genA_ModOff_View();
            break;
            
        case GEN_B_FM:
            mModB_AM_Lbl =(TextView) findViewById(R.id.modB_AM_Lbl);
            mModB_AM_Lbl.setBackgroundColor(0xFFEDD6AB);//0xFFEDD6AB //0xFF51A61F
            msetAM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexAM_B);
            msetAM_ModIdxB_Btn.setBackgroundColor(0xFFEDD6AB);// 0xFF51A61F
            mModB_FM_Lbl =(TextView) findViewById(R.id.modB_FM_Lbl);
            mModB_FM_Lbl.setBackgroundColor(0xFF51A61F);// 0xFFDEB999
            msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
            msetFM_ModIdxB_Btn.setBackgroundColor(0xFF51A61F);//0xFF51A61F //0xFFDEB999
            mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
            mModB_Off_Btn.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F 
            genA_ModOff_View();
            break;
        
	    case GEN_A_OFF:
	        mModA_AM_Lbl =(TextView) findViewById(R.id.modA_AM_Lbl);
	        mModA_AM_Lbl.setTextColor(0xFFADB2C9);
	        msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
	        msetAM_ModIdxA_Btn.setTextColor(0xFFADB2C9);
	        mModA_FM_Lbl =(TextView) findViewById(R.id.modA_FM_Lbl);
	        mModA_FM_Lbl.setTextColor(0xFFADB2C9);
	        msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
	        msetFM_ModIdxA_Btn.setTextColor(0xFFADB2C9);
	        mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
	        mModA_Off_Btn.setTextColor(0xFFADB2C9);
	        mGenA_FreqEntry =(EditText) findViewById(R.id.vfoA_FreqEnter);
	        mGenA_FreqEntry.setTextColor(0xFFADB2C9);
	        mPhaseA_Lbl =(TextView) findViewById(R.id.phaseA_Lbl);
	        mPhaseA_Lbl.setTextColor(0xFFADB2C9);
	        mSetLvlA_Btn =(Button) findViewById(R.id.setLvlA_Btn);
	        mSetLvlA_Btn.setTextColor(0xFFADB2C9);
	        mLevelA_Lbl =(TextView) findViewById(R.id.levelA_Lbl);
	        mLevelA_Lbl.setTextColor(0xFFADB2C9);
	        mSetPhaseA_Btn =(Button) findViewById(R.id.setPhaseA_Btn);
	        mSetPhaseA_Btn.setTextColor(0xFFADB2C9);
	        break;
	        
	    case GEN_A_ON:
	        mModA_AM_Lbl =(TextView) findViewById(R.id.modA_AM_Lbl);
	        mModA_AM_Lbl.setTextColor(0xFF000000);
	        msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
	        msetAM_ModIdxA_Btn.setTextColor(0xFF000000);
	        mModA_FM_Lbl =(TextView) findViewById(R.id.modA_FM_Lbl);
	        mModA_FM_Lbl.setTextColor(0xFF000000);
	        msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
	        msetFM_ModIdxA_Btn.setTextColor(0xFF000000);
	        mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
	        mModA_Off_Btn.setTextColor(0xFF000000);
	        mGenA_FreqEntry =(EditText) findViewById(R.id.vfoA_FreqEnter);
	        mGenA_FreqEntry.setTextColor(0xFF000000);
	        mPhaseA_Lbl =(TextView) findViewById(R.id.phaseA_Lbl);
	        mPhaseA_Lbl.setTextColor(0xFF000000);
	        mSetLvlA_Btn =(Button) findViewById(R.id.setLvlA_Btn);
	        mSetLvlA_Btn.setTextColor(0xFF000000);
	        mLevelA_Lbl =(TextView) findViewById(R.id.levelA_Lbl);
	        mLevelA_Lbl.setTextColor(0xFF000000);
	        mSetPhaseA_Btn =(Button) findViewById(R.id.setPhaseA_Btn);
	        mSetPhaseA_Btn.setTextColor(0xFF000000);
	        break;
	        
	    case GEN_B_OFF:
	        mModB_AM_Lbl =(TextView) findViewById(R.id.modB_AM_Lbl);
	        mModB_AM_Lbl.setTextColor(0xFFADB2C9);
	        msetAM_ModIdxB_Btn.setTextColor(0xFFADB2C9);
	        mModB_FM_Lbl =(TextView) findViewById(R.id.modB_FM_Lbl);
	        mModB_FM_Lbl.setTextColor(0xFFADB2C9);
	        msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
	        msetFM_ModIdxB_Btn.setTextColor(0xFFADB2C9);
	        mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
	        mModB_Off_Btn.setTextColor(0xFFADB2C9);
	        mGenB_FreqEntry =(EditText) findViewById(R.id.vfoB_FreqEnter);
	        mGenB_FreqEntry.setTextColor(0xFFADB2C9);
	        mPhaseB_Lbl =(TextView) findViewById(R.id.phaseB_Lbl);
	        mPhaseB_Lbl.setTextColor(0xFFADB2C9);
	        mSetLvlB_Btn =(Button) findViewById(R.id.setLvlB_Btn);
	        mSetLvlB_Btn.setTextColor(0xFFADB2C9);
	        mLevelB_Lbl =(TextView) findViewById(R.id.levelB_Lbl);
	        mLevelB_Lbl.setTextColor(0xFFADB2C9);
	        mSetPhaseB_Btn =(Button) findViewById(R.id.setPhaseB_Btn);
	        mSetPhaseB_Btn.setTextColor(0xFFADB2C9);
	        break;
	        
	    case GEN_B_ON:
	        mModB_AM_Lbl =(TextView) findViewById(R.id.modB_AM_Lbl);
	        mModB_AM_Lbl.setTextColor(0xFF000000);
	        msetAM_ModIdxB_Btn.setTextColor(0xFF000000);
	        mModB_FM_Lbl =(TextView) findViewById(R.id.modB_FM_Lbl);
	        mModB_FM_Lbl.setTextColor(0xFF000000);
	        msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
	        msetFM_ModIdxB_Btn.setTextColor(0xFF000000);
	        mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
	        mModB_Off_Btn.setTextColor(0xFF000000);
	        mGenB_FreqEntry =(EditText) findViewById(R.id.vfoB_FreqEnter);
	        mGenB_FreqEntry.setTextColor(0xFF000000);
	        mPhaseB_Lbl =(TextView) findViewById(R.id.phaseB_Lbl);
	        mPhaseB_Lbl.setTextColor(0xFF000000);
	        mSetLvlB_Btn =(Button) findViewById(R.id.setLvlB_Btn);
	        mSetLvlB_Btn.setTextColor(0xFF000000);
	        mLevelB_Lbl =(TextView) findViewById(R.id.levelB_Lbl);
	        mLevelB_Lbl.setTextColor(0xFF000000);
	        mSetPhaseB_Btn =(Button) findViewById(R.id.setPhaseB_Btn);
	        mSetPhaseB_Btn.setTextColor(0xFF000000);
	        break;	        
        }       
    }     

    private void genAB_ModOff(){
    	bothGen_ModOff();
    }
    
    private void genA_ModOff_View() { //set the modulation widget colors
        mModA_AM_Lbl =(TextView) findViewById(R.id.modA_AM_Lbl);
        mModA_AM_Lbl.setBackgroundColor(0xFFEDD6AB);// 0xFF51A61F
        msetAM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexAM_A);
        msetAM_ModIdxA_Btn.setBackgroundColor(0xFFEDD6AB);// 0xFF51A61F
        mModA_FM_Lbl =(TextView) findViewById(R.id.modA_FM_Lbl);
        mModA_FM_Lbl.setBackgroundColor(0xFFDEB999);//0xFF51A61F
        msetFM_ModIdxA_Btn =(Button) findViewById(R.id.modIndexFM_A);
        msetFM_ModIdxA_Btn.setBackgroundColor(0xFFDEB999);//0xFF51A61F
        mModA_Off_Btn =(Button) findViewById(R.id.modA_CW_Lbl);
        mModA_Off_Btn.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F 
        mModA_Off_Btn.setText("Mod Off");
    }
    
    private void genB_ModOff_View() { //set the modulation widget colors
        mModB_AM_Lbl =(TextView) findViewById(R.id.modB_AM_Lbl);
        mModB_AM_Lbl.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F            
        msetAM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexAM_B);
        msetAM_ModIdxB_Btn.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F
        mModB_FM_Lbl =(TextView) findViewById(R.id.modB_FM_Lbl);
        mModB_FM_Lbl.setBackgroundColor(0xFFDEB999);//0xFF51A61F
        msetFM_ModIdxB_Btn =(Button) findViewById(R.id.modIndexFM_B);
        msetFM_ModIdxB_Btn.setBackgroundColor(0xFFDEB999);//0xFF51A61F
        mModB_Off_Btn =(Button) findViewById(R.id.modB_CW_Lbl);
        mModB_Off_Btn.setBackgroundColor(0xFFEDD6AB);//0xFF51A61F    	
        mModB_Off_Btn.setText("Mod Off");
        }

    //ActionBar Code============================================
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_bar_nimble_sig_rfgen_main, menu);
//        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent serverIntent = null;
        switch (item.getItemId()) {
        case R.id.secure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
            return true;
        case R.id.insecure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        }
        return false;
    }
    // End ActionBar Code================================
    // Bluetooth Link   Section ========================================================
    public void enableBT(){
	    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
	    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    }

    protected void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras()
            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        NS3_App nsigApp = (NS3_App)getApplication();
        BluetoothDevice device = nsigApp.mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        nsigApp.mChatService.connect(device, secure);
    }

    public void setupComPath() { // called by onStart
        if(D) Log.d(TAG, "setupComPath()");

        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);

        // Initialize the BluetoothChatService to perform bluetooth connections
        NS3_App nsigApp = (NS3_App)getApplication();
        nsigApp.mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        nsigApp.mOutStringBuffer = new StringBuffer("");
    }//setupComPath ===================================
    

    public void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        NS3_App nsigApp = (NS3_App)getApplication();
        if (nsigApp.mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    public void sendMessage(String message) {
        // Check that we're actually connected before trying anything
    	
        NS3_App nsigApp = (NS3_App)getApplication();
    	int chatServiceState = nsigApp.mChatService.getState();
        if (chatServiceState != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            blueToothConnectionNeeded();
            return;
        }
        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
        	message += '\r';
            byte[] send = message.getBytes();
            nsigApp.mChatService.write(send);
        	EditText ns3CmdTxtView = (EditText) findViewById(R.id.edit_text_out);
            ns3CmdTxtView.setText(message);

            // Reset out string buffer to zero and clear the edit text field
            nsigApp.mOutStringBuffer.setLength(0);
//            mNSig_CmdEditor =(EditText) findViewById(R.id.edit_text_out);
//            mNSig_CmdEditor.setText(nsigApp.mOutStringBuffer);
         }
//        return true;
    }
    
    private void blueToothConnectionNeeded(){
       	final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
       	tg.startTone(ToneGenerator.TONE_CDMA_CALLDROP_LITE); 
        Toast.makeText(this, "Bluetooth is not connected", Toast.LENGTH_SHORT).show();
    }

    // The Handler that gets information back from the BluetoothChatService
        private final Handler mHandler = new Handler() {
    	@Override
        public void handleMessage(Message msg) {
//        	Intent ctsIntent = new Intent(Intent.ACTION_SEND);
//        	ctsIntent.setType("cts");
//    	    NS3_App.dataHandler = mHandler;
        	
	        if(D) Log.e(TAG, "NS_SweepGen mHandler entered");
		    if(NS3_App.sg_SweepActivated){
    	        if(D) Log.e(TAG, "NS_Sweep mHandler EJECTION ");    		    	
		    	return;
		    }
	        	switch (msg.what) {
	            case MESSAGE_STATE_CHANGE:
	                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
	                switch (msg.arg1) {
	                case BluetoothChatService.STATE_LISTEN:
	                case BluetoothChatService.STATE_NONE:
	                    setStatus(R.string.title_not_connected);
	                    if(g_WasConnected_b==true){//save settings if connection lost
	                    	saveSettings();
	                    	g_WasConnected_b=false;
	                    	g_ConnectionLost_b=true;
	                    }
	                    break;
	                case BluetoothChatService.STATE_CONNECTED:
	                	String subTitle_Str = getString(R.string.title_connected_to, mConnectedDeviceName);
	                    setStatus(subTitle_Str);
	                    mConversationArrayAdapter.clear();
	       	            TextView nsReplyTxt = (TextView) findViewById(R.id.nsReply);
	       	            nsReplyTxt.setText("\nNimbleSig CONNECTED !!!");
	       	            nimbleSigConnected();
	       	            g_WasConnected_b=true;
		       	        if(g_FreshStart_b){
		       	        	g_FreshStart_b=false;
		       	        } 
	       	        	restoreNSGenSettings();
		       	        if(g_ConnectionLost_b){
	//	       	        	restoreNSGenSettings();
		       	        	g_ConnectionLost_b=false;	       	        	
		       	        }
	       	            break;
	                case BluetoothChatService.STATE_CONNECTING:
	                    setStatus(R.string.title_connecting);
	                    break;
	                }
	                break;
	            case MESSAGE_WRITE:
	    	        if(D) Log.e(TAG, "mHandler MESSAGE_WRITE");              	
	                byte[] writeBuf = (byte[]) msg.obj;
	                // construct a string from the buffer
	                String writeMessage = new String(writeBuf);
	                mConversationArrayAdapter.add("Me:  " + writeMessage);
	                break;
	            case MESSAGE_READ:
	    	        if(D) Log.e(TAG, "SweepGen mHandler MESSAGE_READ");              	
	                byte[] readBuf = (byte[]) msg.obj;
	                byte[] buffer2 = new byte[2048];
	                String replyScrolled;
	                
	
	                // insert the characters into the second buffer
	                NS3_App nsigApp = (NS3_App)getApplication();
	                for(int i=0;i<msg.arg1;i++){
	                	buffer2[i]=readBuf[nsigApp.g_BT_RXD_BfrPtr++];
	                	if(nsigApp.g_BT_RXD_BfrPtr>2047)nsigApp.g_BT_RXD_BfrPtr=0;
	                }
	                // construct a string from the valid bytes in the buffer
	                String readMsgStr = new String(buffer2, 0, msg.arg1);//arg1 = byte count
	
	                g_ReplyStackStr[g_ReplyStkPtr]=readMsgStr;//add the latest message to the stack
	                if(++g_ReplyStkPtr>3)g_ReplyStkPtr=0;//limit number of lines sent to the display
	                replyScrolled="";
	                for(int i=0;i<4;i++){
	                	replyScrolled+=g_ReplyStackStr[g_ReplyStkPtr++];
	                    if(g_ReplyStkPtr>3)g_ReplyStkPtr=0;
	                }
	                final TextView nsReply = (TextView)findViewById(R.id.nsReply);
	                nsReply.setText(replyScrolled);
	                setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
	                
	                int i = readMsgStr.indexOf( "-");
	                if(i > -1){
	                	g_LevelPending_b=true;
	                	g_LevelValueStr="-";
	                }
	            	if(g_LevelPending_b){
	                	int l = readMsgStr.length();
	                	i++;               	
	                	while(l>i){
	                		char c = (readMsgStr.charAt(i++));
	                		if(c=='.')g_LevelValueStr+=c;
	                		else if ((c>='0')&&(c<='9'))g_LevelValueStr+=c;
	                		else{
	                			g_LevelPending_b = false;
	                			// write new level reading to GUI
	                	        mPowerLevel_Btn = (Button) findViewById(R.id.RFLevelBtn);
	                	        mPowerLevel_Btn.setText(g_LevelValueStr + " dBm");
	                			break;
	                		}
	                	}
	            	}               	            	
					break;
	            case MESSAGE_DEVICE_NAME:
	                // save the connected device's name
	                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
	                NS3_App.mConnectedDeviceName=mConnectedDeviceName;
	                Toast.makeText(getApplicationContext(), "Connected to "
	                               + mConnectedDeviceName, Toast.LENGTH_LONG).show();
	                break;
	            case MESSAGE_TOAST:
	                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
	                               Toast.LENGTH_SHORT).show();
	                break;
	            }
	        }
    };
    
    protected final void setStatus(int resId) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(resId);
    }

    private final void setStatus(CharSequence subTitle) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(subTitle);
    }
    
    private void nimbleSigConnected(){
        Toast.makeText(this, R.string.NS_Connected, Toast.LENGTH_LONG).show();    	
        final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        tg.startTone(ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE); 
    }

    private void blueToothNotConnected(){
       	TextView nsReplyTxt = (TextView) findViewById(R.id.nsReply);
       	nsReplyTxt.append("\nNimbleSig NOT-CONNECTED !!!"); 
       	final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
       	tg.startTone(ToneGenerator.TONE_CDMA_CALLDROP_LITE); 
    }
    // END Bluetooth Link Section  ======================================================= 
    
    // NimbleSig Generator control section =========================================
    //NimbleSig module command methods ==================================================
    
    protected void bothGen_ModOff(){
    	sendNS_Cmd(NS_MOD_OFF_BOTH_GENS_CMD_STR);
    		try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
    	setGenA_Fq(g_GenA_FreqHz_Int); // restore carrier 
        	try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
        setGenB_Fq(g_GenB_FreqHz_Int); // restore carrier
    	g_GenA_FM_Active_b = false;
        g_GenB_FM_Active_b = false;
        g_GenA_AM_Active_b = false;
        g_GenB_AM_Active_b = false;
    }

    protected void measureRF_Pwr_dBm(int freqMHz){
	    String calFreq = String.valueOf(freqMHz);
	    sendNS_Cmd(NS_READ_AVERAGE_POWER_CMD_STR+calFreq);
	}

    protected void genA_Disable(){
		sendNS_Cmd(NS_GEN_A_DISABLE_CMD_STR);
    }
    
    public void sendNS_Cmd(String cmdStr){
        sendMessage(cmdStr);    	
//		try{Thread.sleep(10);}catch (InterruptedException e) {}// wait 10mS
    }

    protected void genA_Enable(){    	
		sendNS_Cmd(NS_GEN_A_ENABLE_CMD_STR);            		
    }
    
    protected void genB_Disable(){
		sendNS_Cmd(NS_GEN_B_DISABLE_CMD_STR);
    }
		
    protected void genB_Enable(){
		sendNS_Cmd(NS_GEN_B_ENABLE_CMD_STR);            		
    }
    protected void activateFM_ModGenA(){ //mod cmd to NS   	
		sendNS_Cmd(NS_GEN_A_FM_MOD_ON_CMD_STR);                          
    }
    	
    protected void activateFM_ModGenB(){ //provides indicators and sends the mod cmd to NS   	
    	sendNS_Cmd(NS_GEN_B_FM_MOD_ON_CMD_STR);                          
    }
    	
    protected void activateAM_ModGenA(){ //sends the mod ON cmd to NS   	
		sendNS_Cmd(NS_GEN_A_AM_MOD_ON_CMD_STR); //genA AM mod "on" command                       
    }
    
    protected void activateAM_ModGenB(){  //sends the mod cmd to NS   	
		sendNS_Cmd(NS_GEN_B_AM_MOD_ON_CMD_STR); //genB AM mod "on" command                       
    }
    
    protected void setAM_ModIdx(int AM_Index_Int){ //sets the NS AM mod index
    	if(AM_Index_Int<1)AM_Index_Int=1;
    	if(AM_Index_Int>99)AM_Index_Int=99;
    	String modIndex_Str=String.valueOf(AM_Index_Int);
		sendNS_Cmd(NS_GEN_AM_MOD_INDEX_CMD_STR + modIndex_Str);
    }

    protected int setFM_Dev(int fmDevHz_Int){//sets the NS FM Mod Deviation
    	if(fmDevHz_Int<1)fmDevHz_Int=1;
    	if(fmDevHz_Int>100000)fmDevHz_Int=100000;
    	String fmDevHz_Str=String.valueOf(fmDevHz_Int);   	
        sendNS_Cmd(NS_GEN_FM_MOD_INDEX_CMD_STR + fmDevHz_Str); //set deviation
    	return fmDevHz_Int;
    }
    
    protected void setGenA_Phase(int mDeg){
    	if(mDeg<-180000)mDeg=-180000;
    	if(mDeg>180000)mDeg=180000;
        String newPhaseA_mDeg = String.valueOf(mDeg);
        sendNS_Cmd(NS_GEN_A_PHASE_CMD_STR + newPhaseA_mDeg); 
    }
    
    protected void setGenB_Phase(int mDeg){
    	if(mDeg<-180000)mDeg=-180000;
    	if(mDeg>180000)mDeg=180000;
        String newPhaseB_mDeg = String.valueOf(mDeg);
        sendNS_Cmd(NS_GEN_B_PHASE_CMD_STR + newPhaseB_mDeg); 
    }
    
	protected void setGenA_Atten(int attenVal){
    	if(attenVal<0)attenVal=0;
    	if(attenVal>100)attenVal=100;
		String newOutLevel_cBm_Str = String.valueOf(attenVal);
	    sendNS_Cmd(NS_GEN_A_ATTEN_CMD_STR + newOutLevel_cBm_Str); 
	}

	protected void setGenB_Atten(int attenVal){
    	if(attenVal<0)attenVal=0;
    	if(attenVal>100)attenVal=100;
		String newOutLevel_cBm_Str = String.valueOf(attenVal);
	    sendNS_Cmd(NS_GEN_B_ATTEN_CMD_STR + newOutLevel_cBm_Str); 
	}

    protected void setModFreq(int freqHz_int){
        if(g_ModFreqHz_Int < 1)g_ModFreqHz_Int=1;
        if(g_ModFreqHz_Int > 20000)g_ModFreqHz_Int=20000;
        String modFrqHzStr=String.valueOf(g_ModFreqHz_Int);
        sendNS_Cmd(NS_GEN_AM_MOD_FREQ_CMD_STR + modFrqHzStr); 
    }
    
	protected void setGenA_Fq(int genA_FreqHz_Int){
        if(genA_FreqHz_Int < 100000)genA_FreqHz_Int=100000;
        if(genA_FreqHz_Int > 200000000)genA_FreqHz_Int=200000000;
	    sendNS_Cmd(NS_GEN_A_FREQ_HZ_CMD_STR + String.valueOf(genA_FreqHz_Int)); 
	}

	protected void setGenAB_Fq(int genAB_FreqHz_Int){
        if(genAB_FreqHz_Int < 100000)genAB_FreqHz_Int=100000;
        if(genAB_FreqHz_Int > 200000000)genAB_FreqHz_Int=200000000;
	    sendNS_Cmd(NS_GEN_AB_FREQ_HZ_CMD_STR + String.valueOf(genAB_FreqHz_Int)); 
		
	}
	protected void setGenB_Fq(int genB_FreqHz_Int){
        if(genB_FreqHz_Int < 100000)genB_FreqHz_Int=100000;
        if(genB_FreqHz_Int > 200000000)genB_FreqHz_Int=200000000;
	    sendNS_Cmd(NS_GEN_B_FREQ_HZ_CMD_STR + String.valueOf(genB_FreqHz_Int)); 	
	}
    
    //=====END===NimbleSig module command methods =====================================
	
    protected void setGenA_Level(int level_cBm_Int){
    	if(g_GenA_AM_Active_b){    	
    		if(g_NewGenA_AM_LevelAvail_Int == 0) level_cBm_Int = g_GenA_PreviousAM_Level_cBm_Int;
	        if(level_cBm_Int>-160)level_cBm_Int=-160;
	        if(level_cBm_Int<-260)level_cBm_Int=-260;// final data range check
    	}else{
	        if(level_cBm_Int>-100)level_cBm_Int=-100;
	        if(level_cBm_Int<-200)level_cBm_Int=-200;// final data range check
    	}
        g_GenA_Level_cBm_Int = (int)level_cBm_Int;
        int attenVal = 0;
    	if(g_GenA_AM_Active_b) attenVal = -160-level_cBm_Int;
    	else attenVal = -100-level_cBm_Int;//attenuator value in centi_dB
    	setGenA_Atten(attenVal);
    }

    protected void setGenB_Level(int level_cBm_Int){    	
    	if(g_GenB_AM_Active_b){    	
    		if(g_NewGenB_AM_LevelAvail_Int == 0) level_cBm_Int = g_GenB_PreviousAM_Level_cBm_Int;
	        if(level_cBm_Int>-160)level_cBm_Int=-160;
	        if(level_cBm_Int<-260)level_cBm_Int=-260;// final data range check
    	}else{
	        if(level_cBm_Int>-100)level_cBm_Int=-100;
	        if(level_cBm_Int<-200)level_cBm_Int=-200;// final data range check
    	}
        g_GenB_Level_cBm_Int = (int)level_cBm_Int;
        int attenVal = 0;//attenuator value in centi_dB
    	if(g_GenB_AM_Active_b) attenVal = -160-level_cBm_Int;
    	else attenVal = -100-level_cBm_Int;//attenuator value in centi_dB
    	setGenB_Atten(attenVal);
    }
        
    

    // END NimbleSig Generator control section =========================================
    
}

