//#define EABLE_WLAN_NOTIFICATIONS
/** HostedNetwork calls added by Connectify.  2009, 2010 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace NativeWifi
{
	/// <summary>
	/// Represents a client to the Zeroconf (Native Wifi) service.
	/// </summary>
	/// <remarks>
	/// This class is the entrypoint to Native Wifi management. To manage Wi-Fi settings, create an instance
	/// of this class.
	/// </remarks>
	public class WlanClient : IDisposable
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(WlanClient));
		/// <summary>
		/// Represents a Wifi network interface.
		/// </summary>
		public class WlanInterface
		{
			private WlanClient client;
			private Wlan.WlanInterfaceInfo info;

			#region Events
			/// <summary>
			/// Represents a method that will handle <see cref="WlanNotification"/> events.
			/// </summary>
			/// <param name="notifyData">The notification data.</param>
			public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData);

			/// <summary>
			/// Represents a method that will handle <see cref="WlanConnectionNotification"/> events.
			/// </summary>
			/// <param name="notifyData">The notification data.</param>
			/// <param name="connNotifyData">The notification data.</param>
			public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData);

			/// <summary>
			/// Represents a method that will handle <see cref="WlanReasonNotification"/> events.
			/// </summary>
			/// <param name="notifyData">The notification data.</param>
			/// <param name="reasonCode">The reason code.</param>
			public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode);

			/// <summary>
			/// Occurs when an event of any kind occurs on a WLAN interface.
			/// </summary>
			public event WlanNotificationEventHandler WlanNotification;

			/// <summary>
			/// Occurs when a WLAN interface changes connection state.
			/// </summary>
			public event WlanConnectionNotificationEventHandler WlanConnectionNotification;

			/// <summary>
			/// Occurs when a WLAN operation fails due to some reason.
			/// </summary>
			public event WlanReasonNotificationEventHandler WlanReasonNotification;

			#endregion

			#region Event queue
			private bool queueEvents;
			private AutoResetEvent eventQueueFilled = new AutoResetEvent(false);
			private Queue<object> eventQueue = new Queue<object>();

			private struct WlanConnectionNotificationEventData
			{
				public Wlan.WlanNotificationData notifyData;
				public Wlan.WlanConnectionNotificationData connNotifyData;
			}
			private struct WlanReasonNotificationData
			{
				public Wlan.WlanNotificationData notifyData;
				public Wlan.WlanReasonCode reasonCode;
			}
			#endregion

			internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info)
			{
				this.client = client;
				this.info = info;
			}

			/// <summary>
			/// Sets a parameter of the interface whose data type is <see cref="int"/>.
			/// </summary>
			/// <param name="opCode">The opcode of the parameter.</param>
			/// <param name="value">The value to set.</param>
			private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value)
			{
				IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));
				Marshal.WriteInt32(valuePtr, value);
				try
				{
					Wlan.ThrowIfError(
						Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
				}
				finally
				{
					Marshal.FreeHGlobal(valuePtr);
				}
			}
            private void SetInterfaceData(Wlan.WlanIntfOpcode opCode, object data)
            {
                IntPtr valuePtr = Marshal.AllocHGlobal(Marshal.SizeOf(data));
                Marshal.StructureToPtr(data, valuePtr, false);
                try
                {
                    Wlan.ThrowIfError(
                        Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, (uint)Marshal.SizeOf(data), valuePtr, IntPtr.Zero));
                }
                finally
                {
                    Marshal.FreeHGlobal(valuePtr);
                }
            }
              

			/// <summary>
			/// Gets a parameter of the interface whose data type is <see cref="int"/>.
			/// </summary>
			/// <param name="opCode">The opcode of the parameter.</param>
			/// <returns>The integer value.</returns>
			private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode)
			{
				IntPtr valuePtr;
				int valueSize;
				Wlan.WlanOpcodeValueType opcodeValueType;
				Wlan.ThrowIfError(
					Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
				try
				{
					return Marshal.ReadInt32(valuePtr);
				}
				finally
				{
					Wlan.WlanFreeMemory(valuePtr);
				}
            }
            private IntPtr GetInterfaceData(Wlan.WlanIntfOpcode opCode)
            {
                IntPtr valuePtr;
                int valueSize;
                Wlan.WlanOpcodeValueType opcodeValueType;
                try
                {
                    Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType);
                    return valuePtr;
                }
                catch (Exception)
                {
                    throw;
                }
            }

            public bool GetHostedNetworkSupport()
            {
                bool retval = false;
                try {
                    retval = GetInterfaceInt(Wlan.WlanIntfOpcode.HostedNetworkCapable) != 0;
                }catch(Win32Exception we)
                {
                    //log.Info("Win32Exception errorCode " + we.ErrorCode);
                    if(we.ErrorCode == -2147467259)
                    {
                        // "element not found".  not a huge deal, this probably WAS
                        // our hostednetwork adapter.  Swallown the exception and just say no.
                        retval = false;

                    } else { 
                        throw;
                    }
                }
                return retval;
            }

            /// <summary>
            /// Enables or disables background scan for this <see cref="WlanInterface"/>.
            /// </summary>
            /// <value><c>true</c> if "BackgroundScan" is enabled; otherwise, <c>false</c>.</value>
            public bool BackgroundScan
            {
                get
                {
                    return GetInterfaceInt(Wlan.WlanIntfOpcode.BackgroundScanEnabled) != 0;
                }
                set
                {
                    SetInterfaceInt(Wlan.WlanIntfOpcode.BackgroundScanEnabled, value ? 1 : 0);
                }
            }

            public NativeWifi.Wlan.WLAN_RADIO_STATE RadioStateTable
            {
                get
                {
                    IntPtr ptr = IntPtr.Zero;
                    try
                    {
                        ptr = GetInterfaceData(Wlan.WlanIntfOpcode.RadioState);
                        NativeWifi.Wlan.WLAN_RADIO_STATE radioStateTable = (NativeWifi.Wlan.WLAN_RADIO_STATE)Marshal.PtrToStructure(ptr, typeof(NativeWifi.Wlan.WLAN_RADIO_STATE));
                        return radioStateTable;
                    }
                    catch (Exception)
                    {
                        NativeWifi.Wlan.WLAN_RADIO_STATE s = new Wlan.WLAN_RADIO_STATE();
                        s.dwNumberOfPhys = 0;
                        return s;
                    }
                    finally
                    {
                        if (ptr != IntPtr.Zero)
                            Wlan.WlanFreeMemory(ptr);
                    }
                }
            }

            /// <summary>
            /// Gets a tuple of the hardward and software radio state of this <see cref="WlanInterface"/>.
            /// </summary>
            /// <value><c>true</c> if "RadioState" is enabled; otherwise, <c>false</c>.</value>
            public Tuple<bool, bool> RadioState
            {
                get
                {

                    bool enabledSoftware = false;
                    bool enabledHardware = false;

                    NativeWifi.Wlan.WLAN_RADIO_STATE radioStateTable = RadioStateTable;
                    for (int i = 0; i < radioStateTable.dwNumberOfPhys && i < radioStateTable.PhyRadioState.Length; i++)
                    {
                        if (radioStateTable.PhyRadioState[i].dot11HardwareRadioState == NativeWifi.Wlan.dot11RadioState.dot11_radio_state_on)
                        {
                            enabledHardware = true;
                        }
                        if (radioStateTable.PhyRadioState[i].dot11SoftwareRadioState == NativeWifi.Wlan.dot11RadioState.dot11_radio_state_on)
                        {
                            enabledSoftware = true;
                        }
                    }
                    return new Tuple<bool, bool>(enabledHardware, enabledSoftware);
                }
            }
            /// <summary>
            /// Gets or sets the software radio state of this <see cref="WlanInterface"/>.
            /// </summary>
            /// <value><c>true</c> if "RadioState" is enabled; otherwise, <c>false</c>.</value>
            public bool RadioSoftwareState
            {
                get
                {
                    NativeWifi.Wlan.WLAN_RADIO_STATE radioStateTable = RadioStateTable;
                    bool anyEnabled = false;
                    for (int i = 0; i < radioStateTable.dwNumberOfPhys && i < radioStateTable.PhyRadioState.Length; i++)
                    {
                        if (radioStateTable.PhyRadioState[i].dot11SoftwareRadioState == Wlan.dot11RadioState.dot11_radio_state_on)
                        {
                            anyEnabled = true;
                            break;
                        }
                    }
                    return anyEnabled;
                }
                set
                {
                    NativeWifi.Wlan.WLAN_RADIO_STATE radioStateTable = RadioStateTable;
                    for (int i = 0; i < radioStateTable.dwNumberOfPhys; i++)
                    {
                        radioStateTable.PhyRadioState[i].dot11SoftwareRadioState = value ? Wlan.dot11RadioState.dot11_radio_state_on : Wlan.dot11RadioState.dot11_radio_state_off;
                        SetInterfaceData(
                            Wlan.WlanIntfOpcode.RadioState,
                            radioStateTable.PhyRadioState[i]
                            );
                    }
                }
            }
            /// <summary>
            /// Gets or sets the hardware radio state of this <see cref="WlanInterface"/>.
            /// </summary>
            /// <value><c>true</c> if "RadioState" is enabled; otherwise, <c>false</c>.</value>
            public bool RadioHardwareState
            {
                get
                {
                    NativeWifi.Wlan.WLAN_RADIO_STATE radioStateTable = RadioStateTable;
                    bool anyEnabled = false;
                    for (int i = 0; i < radioStateTable.dwNumberOfPhys && i < radioStateTable.PhyRadioState.Length; i++)
                    {
                        if (radioStateTable.PhyRadioState[i].dot11HardwareRadioState == Wlan.dot11RadioState.dot11_radio_state_on)
                        {
                            anyEnabled = true;
                            break;
                        }
                    }
                    return anyEnabled;
                }
            }

			/// <summary>
			/// Gets or sets a value indicating whether this <see cref="WlanInterface"/> is automatically configured.
			/// </summary>
			/// <value><c>true</c> if "autoconf" is enabled; otherwise, <c>false</c>.</value>
			public bool Autoconf
			{
				get
				{
					return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0;
				}
				set
				{
					SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0);
				}
			}

			/// <summary>
			/// Gets or sets the BSS type for the indicated interface.
			/// </summary>
			/// <value>The type of the BSS.</value>
			public Wlan.Dot11BssType BssType
			{
				get
				{
					return (Wlan.Dot11BssType) GetInterfaceInt(Wlan.WlanIntfOpcode.BssType);
				}
				set
				{
					SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value);
				}
			}

            /// <summary>
            /// Gets the state of the interface.
            /// </summary>
            /// <value>The state of the interface.</value>
            public Wlan.WlanInterfaceState InterfaceState
			{
				get
				{
					return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState);
				}
			}

			/// <summary>
			/// Gets the channel.
			/// </summary>
			/// <value>The channel.</value>
			/// <remarks>Not supported on Windows XP SP2.</remarks>
			public int Channel
			{
				get
				{
					return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber);
				}				
			}

			/// <summary>
			/// Gets the RSSI.
			/// </summary>
			/// <value>The RSSI.</value>
			/// <remarks>Not supported on Windows XP SP2.</remarks>
			public int RSSI
			{
				get
				{
					return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI);
				}
			}

			/// <summary>
			/// Gets the current operation mode.
			/// </summary>
			/// <value>The current operation mode.</value>
			/// <remarks>Not supported on Windows XP SP2.</remarks>
			public Wlan.Dot11OperationMode CurrentOperationMode
			{
				get
				{
					return (Wlan.Dot11OperationMode) GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode);
				}
			}

			/// <summary>
			/// Gets the attributes of the current connection.
			/// </summary>
			/// <value>The current connection attributes.</value>
			/// <exception cref="Win32Exception">An exception with code 0x0000139F (The group or resource is not in the correct state to perform the requested operation.) will be thrown if the interface is not connected to a network.</exception>
			public Wlan.WlanConnectionAttributes CurrentConnection
			{
				get
				{
					int valueSize;
					IntPtr valuePtr;
					Wlan.WlanOpcodeValueType opcodeValueType;
					Wlan.ThrowIfError(
						Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
					try
					{
							return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes));
					}
					finally
					{
						Wlan.WlanFreeMemory(valuePtr);
					}
				}
			}

			/// <summary>
			/// Requests a scan for available networks.
			/// </summary>
			/// <remarks>
			/// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
			/// </remarks>
			public void Scan()
			{
				Wlan.ThrowIfError(
					Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
			}

			/// <summary>
			/// Converts a pointer to a available networks list (header + entries) to an array of available network entries.
			/// </summary>
			/// <param name="bssListPtr">A pointer to an available networks list's header.</param>
			/// <returns>An array of available network entries.</returns>
			private Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr)
			{
				Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader));
				long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader));
				Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems];
				for (int i = 0; i < availNetListHeader.numberOfItems; ++i)
				{
					availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork));
					availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork));
				}
				return availNets;
			}

			/// <summary>
			/// Retrieves the list of available networks.
			/// </summary>
			/// <param name="flags">Controls the type of networks returned.</param>
			/// <returns>A list of the available networks.</returns>
			public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags)
			{
				IntPtr availNetListPtr;
				Wlan.ThrowIfError(
					Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));
				try
				{
					return ConvertAvailableNetworkListPtr(availNetListPtr);
				}
				finally
				{
					Wlan.WlanFreeMemory(availNetListPtr);
				}
			}

			/// <summary>
			/// Converts a pointer to a BSS list (header + entries) to an array of BSS entries.
			/// </summary>
			/// <param name="bssListPtr">A pointer to a BSS list's header.</param>
			/// <returns>An array of BSS entries.</returns>
			private Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr)
			{
				Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader));
				long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader));
				Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems];
				for (int i=0; i<bssListHeader.numberOfItems; ++i)
				{
					bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry));
					bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry));
				}
				return bssEntries;
			}

			/// <summary>
			/// Retrieves the basic service sets (BSS) list of all available networks.
			/// </summary>
			public Wlan.WlanBssEntry[] GetNetworkBssList()
			{
				IntPtr bssListPtr;
				Wlan.ThrowIfError(
					Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr));
				try
				{
					return ConvertBssListPtr(bssListPtr);
				}
				finally
				{
					Wlan.WlanFreeMemory(bssListPtr);
				}
			}

			/// <summary>
			/// Retrieves the basic service sets (BSS) list of the specified network.
			/// </summary>
			/// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param>
			/// <param name="bssType">Indicates the BSS type of the network.</param>
			/// <param name="securityEnabled">Indicates whether security is enabled on the network.</param>
			public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
			{
				IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
				Marshal.StructureToPtr(ssid, ssidPtr, false);
				try
				{
					IntPtr bssListPtr;
					Wlan.ThrowIfError(
						Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
					try
					{
						return ConvertBssListPtr(bssListPtr);
					}
					finally
					{
						Wlan.WlanFreeMemory(bssListPtr);
					}
				}
				finally
				{
					Marshal.FreeHGlobal(ssidPtr);
				}
			}

			/// <summary>
			/// Connects to a network defined by a connection parameters structure.
			/// </summary>
			/// <param name="connectionParams">The connection paramters.</param>
			protected void Connect(Wlan.WlanConnectionParameters connectionParams)
			{
				Wlan.ThrowIfError(
					Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero));
			}

			/// <summary>
			/// Requests a connection (association) to the specified wireless network.
			/// </summary>
			/// <remarks>
			/// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
			/// </remarks>
			public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile)
			{
				Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
				connectionParams.wlanConnectionMode = connectionMode;
				connectionParams.profile = profile;
				connectionParams.dot11BssType = bssType;
				connectionParams.flags = 0;
				Connect(connectionParams);
            }

            public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, Wlan.Dot11Ssid ssid, Wlan.DOT11_BSSID_LIST bssids)
            {
                Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
                connectionParams.wlanConnectionMode = connectionMode;
                connectionParams.profile = profile;
                connectionParams.dot11BssType = bssType;
                connectionParams.flags = 0;
                connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
                Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
                connectionParams.desiredBssidListPtr = Marshal.AllocHGlobal(Marshal.SizeOf(bssids));
                Marshal.StructureToPtr(bssids, connectionParams.desiredBssidListPtr, false);
                Connect(connectionParams);
                Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
                Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
                Marshal.DestroyStructure(connectionParams.desiredBssidListPtr, bssids.GetType());
                Marshal.FreeHGlobal(connectionParams.desiredBssidListPtr);
            }
			
			/// <summary>
			/// Connects (associates) to the specified wireless network, returning either on a success to connect
			/// or a failure.
			/// </summary>
			/// <param name="connectionMode"></param>
			/// <param name="bssType"></param>
			/// <param name="profile"></param>
			/// <param name="connectTimeout"></param>
			/// <returns></returns>
			public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout)
			{
				queueEvents = true;
				try
				{
					Connect(connectionMode, bssType, profile);
					while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
                    {
                        using (new Connectify.Library.Threading.SmartLock("WlanApiConnectSynch4", eventQueue))
						{
							while (eventQueue.Count != 0)
							{
								object e = eventQueue.Dequeue();
								if (e is WlanConnectionNotificationEventData)
								{
									WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
									// Check if the conditions are good to indicate either success or failure.
									if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
									{
										switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
										{
											case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
												if (wlanConnectionData.connNotifyData.profileName == profile)
													return true;
												break;
										}
									}
									break;
								}
							}
						}
					}
				}
				finally
				{
					queueEvents = false;
					eventQueue.Clear();
				}
				return false; // timeout expired and no "connection complete"
            }
            public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, Wlan.Dot11Ssid ssid, Wlan.DOT11_BSSID_LIST bssids, int connectTimeout)
            {
                queueEvents = true;
                try
                {
                    Connect(connectionMode, bssType, profile,ssid, bssids);
                    while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
                    {
                        using (new Connectify.Library.Threading.SmartLock("WlanApiConnectSynch6", eventQueue))
                        {
                            while (eventQueue.Count != 0)
                            {
                                object e = eventQueue.Dequeue();
                                if (e is WlanConnectionNotificationEventData)
                                {
                                    WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
                                    // Check if the conditions are good to indicate either success or failure.
                                    if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
                                    {
                                        switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
                                        {
                                            case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
                                                if (wlanConnectionData.connNotifyData.profileName == profile)
                                                    return true;
                                                break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                finally
                {
                    queueEvents = false;
                    eventQueue.Clear();
                }
                return false; // timeout expired and no "connection complete"
            }


			/// <summary>
			/// Connects to the specified wireless network.
			/// </summary>
			/// <remarks>
			/// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
			/// </remarks>
			public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags)
			{
				Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
				connectionParams.wlanConnectionMode = connectionMode;
				connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
				Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
				connectionParams.dot11BssType = bssType;
				connectionParams.flags = flags;
				Connect(connectionParams);
				Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
				Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
			}

			/// <summary>
			/// Deletes a profile.
			/// </summary>
			/// <param name="profileName">
			/// The name of the profile to be deleted. Profile names are case-sensitive.
			/// On Windows XP SP2, the supplied name must match the profile name derived automatically from the SSID of the network. For an infrastructure network profile, the SSID must be supplied for the profile name. For an ad hoc network profile, the supplied name must be the SSID of the ad hoc network followed by <c>-adhoc</c>.
			/// </param>
			public void DeleteProfile(string profileName)
			{
				Wlan.ThrowIfError(
					Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero));
            }

            /// <summary>
            /// Disconnects an interface from its current network.
            /// </summary>
            public void Disconnect()
            {
                Wlan.ThrowIfError(
                    Wlan.WlanDisconnect(client.clientHandle, info.interfaceGuid, IntPtr.Zero));
            }

			/// <summary>
			/// Sets the profile.
			/// </summary>
			/// <param name="flags">The flags to set on the profile.</param>
			/// <param name="profileXml">The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.</param>
			/// <param name="overwrite">If a profile by the given name already exists, then specifies whether to overwrite it (if <c>true</c>) or return an error (if <c>false</c>).</param>
			/// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns>
			public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite)
			{
				Wlan.WlanReasonCode reasonCode;
				//Wlan.ThrowIfError(
						Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode);//);
				return reasonCode;
			}

			/// <summary>
			/// Gets the profile's XML specification.
			/// </summary>
			/// <param name="profileName">The name of the profile.</param>
			/// <returns>The XML document.</returns>
			public string GetProfileXml(string profileName)
			{
				IntPtr profileXmlPtr;
				Wlan.WlanProfileFlags flags = Wlan.WlanProfileFlags.PlainTextKey;
				Wlan.WlanAccess access;
				Wlan.ThrowIfError(
					Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, ref flags,
					               out access));
				try
				{
					return Marshal.PtrToStringUni(profileXmlPtr);
				}
				finally
				{
					Wlan.WlanFreeMemory(profileXmlPtr);
				}
			}

			/// <summary>
			/// Gets the information of all profiles on this interface.
			/// </summary>
			/// <returns>The profiles information.</returns>
			public Wlan.WlanProfileInfo[] GetProfiles()
			{
				IntPtr profileListPtr;
				Wlan.ThrowIfError(
					Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr));
				try
				{
					Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader) Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader));
					Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems];
					long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header);
					for (int i=0; i<header.numberOfItems; ++i)
					{
						Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo) Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo));
						profileInfos[i] = profileInfo;
						profileListIterator += Marshal.SizeOf(profileInfo);
					}
					return profileInfos;
				}
				finally
				{
					Wlan.WlanFreeMemory(profileListPtr);
				}
			}

			internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
			{
				if (WlanConnectionNotification != null)
					WlanConnectionNotification(notifyData, connNotifyData);

				if (queueEvents)
				{
					WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData();
					queuedEvent.notifyData = notifyData;
					queuedEvent.connNotifyData = connNotifyData;
					EnqueueEvent(queuedEvent);
				}
			}

			internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode)
			{
				if (WlanReasonNotification != null)
					WlanReasonNotification(notifyData, reasonCode);
				if (queueEvents)
				{
					WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData();
					queuedEvent.notifyData = notifyData;
					queuedEvent.reasonCode = reasonCode;
					EnqueueEvent(queuedEvent);
				}
			}

			internal void OnWlanNotification(Wlan.WlanNotificationData notifyData)
			{
				if (WlanNotification != null)
					WlanNotification(notifyData);
			}

			/// <summary>
			/// Enqueues a notification event to be processed serially.
			/// </summary>
			private void EnqueueEvent(object queuedEvent)
            {
                using (new Connectify.Library.Threading.SmartLock("WlanApiEvnqueueEvent", eventQueue))
					eventQueue.Enqueue(queuedEvent);
				eventQueueFilled.Set();
			}

			/// <summary>
			/// Gets the network interface of this wireless interface.
			/// </summary>
			/// <remarks>
			/// The network interface allows querying of generic network properties such as the interface's IP address.
			/// </remarks>
			public NetworkInterface NetworkInterface
			{
				get
				{
                    // Do not cache the NetworkInterface; We need it fresh
                    // each time cause otherwise it caches the IP information.
					foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces())
					{
						Guid netIfaceGuid = new Guid(netIface.Id);
						if (netIfaceGuid.Equals(info.interfaceGuid))
						{
							return netIface;
						}
					}
                    return null;
				}
			}

			/// <summary>
			/// The GUID of the interface (same content as the <see cref="System.Net.NetworkInformation.NetworkInterface.Id"/> value).
			/// </summary>
			public Guid InterfaceGuid
			{
				get { return info.interfaceGuid; }
			}

			/// <summary>
			/// The description of the interface.
			/// This is a user-immutable string containing the vendor and model name of the adapter.
			/// </summary>
			public string InterfaceDescription
			{
				get { return info.interfaceDescription; }
			}

			/// <summary>
			/// The friendly name given to the interface by the user (e.g. "Local Area Network Connection").
			/// </summary>
			public string InterfaceName
			{
				get { return NetworkInterface.Name; }
			}

            public NativeWifi.Wlan.DOT11_AUTH_CIPHER_PAIR[] GetAdHocAuthCipherPairs()
            {
                IntPtr ptr=IntPtr.Zero;
                try
                {
                    //int bytesNeeded = 0;
                    ptr = GetInterfaceData(Wlan.WlanIntfOpcode.SupportedAdhocAuthCipherPairs);
                    int entries = Marshal.ReadInt32(ptr);
                    // Increment the memory pointer by the size of the int.
                    IntPtr currentBuffer = new IntPtr(ptr.ToInt64() +
                       Marshal.SizeOf(typeof(int)));

                    // Allocate an array of entries.
                    NativeWifi.Wlan.DOT11_AUTH_CIPHER_PAIR[] table = new NativeWifi.Wlan.DOT11_AUTH_CIPHER_PAIR[entries];
                    // Cycle through the entries.
                    for (int index = 0; index < entries; index++)
                    {
                        // Call PtrToStructure, getting the structure information.
                        table[index] = (NativeWifi.Wlan.DOT11_AUTH_CIPHER_PAIR)Marshal.PtrToStructure(new
                       IntPtr(currentBuffer.ToInt64() + (index *
                       Marshal.SizeOf(typeof(NativeWifi.Wlan.DOT11_AUTH_CIPHER_PAIR)))), typeof(NativeWifi.Wlan.DOT11_AUTH_CIPHER_PAIR));
                    }
                    return table;
                }
                finally
                {
                    if (ptr != IntPtr.Zero)
                        Wlan.WlanFreeMemory(ptr);
                }
            }
            public NativeWifi.Wlan.WlanInterfaceCapability GetInterfaceCapability()
            {
                IntPtr ptrCapa = IntPtr.Zero;
                NativeWifi.Wlan.WlanInterfaceCapability caps = new Wlan.WlanInterfaceCapability();
                try
                {
                    int ret = NativeWifi.Wlan.WlanGetInterfaceCapability(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out ptrCapa);

                    if (ret == 0)
                    {
                        caps = (NativeWifi.Wlan.WlanInterfaceCapability)Marshal.PtrToStructure(ptrCapa, typeof(NativeWifi.Wlan.WlanInterfaceCapability));
                        NativeWifi.Wlan.WlanFreeMemory(ptrCapa);
                    }
                }
                catch (Exception e)
                {
                    log.Error(e);
                }
                return caps;
            }
        }

		private IntPtr clientHandle;
		private uint negotiatedVersion;
#if EABLE_WLAN_NOTIFICATIONS
		private Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback;
#endif

		private Dictionary<Guid,WlanInterface> ifaces = new Dictionary<Guid,WlanInterface>();

        private static object instancesLock = new object();
        private static int instances=0;
        private static List<Tuple<WlanClient, string>> instancesLive = new List<Tuple<WlanClient, string>>();
        [ThreadStatic]
        private static Tuple<WlanClient, string> threadInstance = null;
        private const int INSTANCES_WARN_LEVEL = 10;
        private static bool instancesReported = false;
        private string name = null;

        private static object singletonLock = new object();
        private static WlanClient singleton = null;
        public class Proxy : IDisposable
        {
            public WlanClient Client
            {
                get
                {
                    return singleton;
                }
            }

            public Proxy([System.Runtime.CompilerServices.CallerMemberName] string name = "unnamed")
            {
                // NOTE : we only lock around handle deletion/creation
                
                // sometime things can hang in windows networking in here. run this in a different thread that we can kill so we have a chance of recovering from a hang and not doom every future call to deadlock.
                // note that we might still will hang and/or deadlock, as it is unclear that windows networking can actually recover, and future calls will probably also simply hang.

                // NOTE : lock is outside killable threads so we dont possibly leak a lock

                bool goodHandle = false;

                // generate our lock
                try
                {
                    // if we didnt already validate this handle
                    using (Connectify.Library.Threading.SmartLock wlanClientLock = new Connectify.Library.Threading.SmartLock("WlanClient", singletonLock))
                    {
                        if (!Connectify.Library.Threading.TimedWorker.Run(10 * 1000, "WlanClientProxyValidity", delegate ()
                        {
                            // test if singleton is still valid
                            try
                            {
                                if (singleton != null)
                                {
                                    NativeWifi.Wlan.WlanHostedNetworkStatusHeader networkstatus;
                                    List<Wlan.WlanHostedNetworkPeerState> currentPeers;
                                    try
                                    {
                                        int ret = singleton.WlanHostedNetworkQueryStatus(out networkstatus, out currentPeers);
                                        if (/*ERROR_INVALID_HANDLE*/ 6 == ret)
                                        {
                                        }
                                        else
                                        {
                                            goodHandle = true;
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }))
                        {
                            log.Error("wlanclient validity check hung");
                            throw new Exception("Failed to initialize WlanClientProxy : validity hung");
                        }

                        if (!goodHandle)
                        {
                            if (!Connectify.Library.Threading.TimedWorker.Run(5 * 1000, "WlanClientProxyConstruct", delegate ()
                            {
                                if (singleton != null)
                                {
                                    // current handle is no longer valid. destroy
                                    log.Debug("wlanclient handle is stale, remaking");
                                    try
                                    {
                                        singleton.CloseHandle();
                                        singleton = null;
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                                // if there is no valid singleton, create one
                                try
                                {
                                    if (singleton == null)
                                    {
                                        singleton = new WlanClient("Singleton");
                                    }
                                    // if we got there, there was either already a valid singleton, or we created a new one
                                    goodHandle = true;
                                }
                                catch (Exception e)
                                {
                                    log.Error("could not make wlanclient singleton", e);
                                }
                            }))
                            {
                                log.Error("wlanclient creation hung");
                                throw new Exception("Failed to initialize WlanClientProxy : creation hung");
                            }
                        }
                    }
                }
                catch (Connectify.Library.Threading.SmartLock.DeadlockException e)
                {
                    log.Error("Failed to initialize WlanClientProxy : lock", e);
                }

                if (!goodHandle)
                {
                    throw new Exception("Failed to initialize WlanClientProxy : instantiation failed");
                }
            }

            public void Dispose()
            {
            }
        }

		/// <summary>
		/// Creates a new instance of a Native Wifi service client.
		/// </summary>
        public WlanClient([System.Runtime.CompilerServices.CallerMemberName] string name = "unnamed")
		{
            this.name = name;
			Wlan.ThrowIfError(
				Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_LONGHORN, IntPtr.Zero, out negotiatedVersion, out clientHandle));
			try
            {
#if EABLE_WLAN_NOTIFICATIONS
				Wlan.WlanNotificationSource prevSrc;
				wlanNotificationCallback = new Wlan.WlanNotificationCallbackDelegate(OnWlanNotification);
				Wlan.ThrowIfError(
					Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
                Wlan.ThrowIfError(Wlan.WlanRegisterVirtualStationNotification(clientHandle,true,IntPtr.Zero));
#endif
                try
                {
                    lock (instancesLock)
                    {
                        instances++;
                        Tuple<WlanClient, string> curInstance = new Tuple<WlanClient, string>(this, System.Threading.Thread.CurrentThread.Name);
                        if (threadInstance!=null)
                        {
                            log.Warn("WlanClient instance already exists on thread : " + threadInstance.Item2 + " for instance " + threadInstance.Item1.name);
                        }
                        threadInstance = curInstance;
                        instancesLive.Add(threadInstance);
                        if (instances >= INSTANCES_WARN_LEVEL)
                        {
                            log.Warn("WlanClient instances is above warning level: " + instances);
                            string liveInstanceNames = "";
                            foreach (Tuple<WlanClient, string> t in instancesLive)
                            {
                                liveInstanceNames += t.Item1.name + "("+t.Item2+")" + ";";
                            }
                            log.Warn("Live WlanClientInstances:" + liveInstanceNames);
                            if (!instancesReported)
                            {
                                instancesReported = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Error("exception doing wlanclient accounting",e);
                }
			}
			catch (Exception e)
			{
                log.Error("WlanClient", e);
				Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
				throw;
			}
		}

		~WlanClient()
		{
            CloseHandle();
		}

		private Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData)
		{
			int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData));
			if (notifyData.dataSize < expectedSize)
				return null;

			Wlan.WlanConnectionNotificationData connNotifyData =
				(Wlan.WlanConnectionNotificationData)
				Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData));
			if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success)
			{
				IntPtr profileXmlPtr = new IntPtr(
					notifyData.dataPtr.ToInt64() +
					Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64());
				connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr);
			}
			return connNotifyData;
		}

		private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context)
		{
			WlanInterface wlanIface = ifaces.ContainsKey(notifyData.interfaceGuid) ? ifaces[notifyData.interfaceGuid] : null;

            //log.Debug("WlanClient:OnWlanNotification:" + notifyData.notificationSource.ToString() + ":" + notifyData.notificationCode);
			switch(notifyData.notificationSource)
			{
				case Wlan.WlanNotificationSource.ACM:
					switch((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
					{
						case Wlan.WlanNotificationCodeAcm.ConnectionStart:
						case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
						case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
						case Wlan.WlanNotificationCodeAcm.Disconnecting:
						case Wlan.WlanNotificationCodeAcm.Disconnected:
							Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
							if (connNotifyData.HasValue)
								if (wlanIface != null)
									wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
							break;
                        case Wlan.WlanNotificationCodeAcm.ScanComplete:
						case Wlan.WlanNotificationCodeAcm.ScanFail:
                            {
                                if (notifyData.dataSize >= Marshal.SizeOf(new Int32()))
                                {
                                    Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
                                    if (wlanIface != null)
                                        wlanIface.OnWlanReason(notifyData, reasonCode);
                                }
                            }
							break;
					}
					break;
				case Wlan.WlanNotificationSource.MSM:
					switch((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
					{
						case Wlan.WlanNotificationCodeMsm.Associating:
						case Wlan.WlanNotificationCodeMsm.Associated:
						case Wlan.WlanNotificationCodeMsm.Authenticating:
						case Wlan.WlanNotificationCodeMsm.Connected:
						case Wlan.WlanNotificationCodeMsm.RoamingStart:
						case Wlan.WlanNotificationCodeMsm.RoamingEnd:
						case Wlan.WlanNotificationCodeMsm.Disassociating:
						case Wlan.WlanNotificationCodeMsm.Disconnected:
						case Wlan.WlanNotificationCodeMsm.PeerJoin:
						case Wlan.WlanNotificationCodeMsm.PeerLeave:
						case Wlan.WlanNotificationCodeMsm.AdapterRemoval:
							Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
							if (connNotifyData.HasValue)
								if (wlanIface != null)
									wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
							break;
					}
                    break;
                case Wlan.WlanNotificationSource.HNWK:
                    switch ((Wlan.WlanHostedNetworkNotificationCode)notifyData.notificationCode)
					{
                        case Wlan.WlanHostedNetworkNotificationCode.wlan_hosted_network_peer_state_change:
                            //log.Debug("have HN peer state change");
                            break;
                        case Wlan.WlanHostedNetworkNotificationCode.wlan_hosted_network_radio_state_change:
                            //log.Debug("have HN radio state change");
                            break;
                        case Wlan.WlanHostedNetworkNotificationCode.wlan_hosted_network_state_change:
                            //log.Debug("have HN state change");
							break;
					}
                    break;
			}
			
			if (wlanIface != null)
				wlanIface.OnWlanNotification(notifyData);
		}

		/// <summary>
		/// Gets the WLAN interfaces.
		/// </summary>
		/// <value>The WLAN interfaces.</value>
		public WlanInterface[] Interfaces
		{
			get
			{
				IntPtr ifaceList;
				Wlan.ThrowIfError(
					Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList));
                try
                {
                    Wlan.WlanInterfaceInfoListHeader header =
                        (Wlan.WlanInterfaceInfoListHeader)Marshal.PtrToStructure(ifaceList, typeof(Wlan.WlanInterfaceInfoListHeader));
                    Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header);
                    WlanInterface[] interfaces = new WlanInterface[header.numberOfItems];
                    List<Guid> currentIfaceGuids = new List<Guid>();
                    for (int i = 0; i < header.numberOfItems; ++i)
                    {
                        Wlan.WlanInterfaceInfo info =
                            (Wlan.WlanInterfaceInfo)Marshal.PtrToStructure(new IntPtr(listIterator), typeof(Wlan.WlanInterfaceInfo));
                        listIterator += Marshal.SizeOf(info);
                        WlanInterface wlanIface;
                        if (info.interfaceGuid != null)
                        {
                            currentIfaceGuids.Add(info.interfaceGuid);
                            if (ifaces.ContainsKey(info.interfaceGuid))
                                wlanIface = ifaces[info.interfaceGuid];
                            else
                                wlanIface = new WlanInterface(this, info);
                            interfaces[i] = wlanIface;
                            ifaces[info.interfaceGuid] = wlanIface;
                        }
                        else
                        {
                            
                            log.Warn("Interfaces - found interface without Guid (" + info.interfaceDescription + ")");
                        }
                    }

                    // Remove stale interfaces
                    Queue<Guid> deadIfacesGuids = new Queue<Guid>();
                    foreach (Guid ifaceGuid in ifaces.Keys)
                    {
                        if (!currentIfaceGuids.Contains(ifaceGuid))
                            deadIfacesGuids.Enqueue(ifaceGuid);
                    }
                    while (deadIfacesGuids.Count != 0)
                    {
                        Guid deadIfaceGuid = deadIfacesGuids.Dequeue();
                        ifaces.Remove(deadIfaceGuid);
                    }

                    return interfaces;
                }
                finally
                {
                    Wlan.WlanFreeMemory(ifaceList);
                }
			}
		}

		/// <summary>
		/// Gets a string that describes a specified reason code.
		/// </summary>
		/// <param name="reasonCode">The reason code.</param>
		/// <returns>The string.</returns>
		public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode)
		{
			StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size
			Wlan.ThrowIfError(
				Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero));
			return sb.ToString();
		}
        /// <summary>
        /// Gets a string that describes a specified reason code.
        /// </summary>
        /// <param name="reasonCode">The hosted network reason code.</param>
        /// <returns>The string.</returns>
        public static string GetStringForHostedNetworkReasonCode(Wlan.WlanHostedNetworkReason reasonCode)
        {
            // the windows wlanapi seems like it should really have this itself, so that the results are
            // internationalized, etc.  but it seems to be missing, so I'm implementing by hand here.

            string results = "Unknown";
            switch (reasonCode)
            {

                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_success:
                    results = "Success";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_unspecified:
                    results = "Unknown error";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_bad_parameters:
                    results = "Bad parameters";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_service_shutting_down:
                    results = "Service is shutting down";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_insufficient_resources:
                    results = "Service is out of resources";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_elevation_required:
                    results = "This operation requires elevation";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_read_only:
                    results = "An attempt was made to write read-only data";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_persistence_failed:
                    results = "Data persistence failed";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_crypt_error:
                    results = "A cryptographic error occurred";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_impersonation:
                    results = "User impersonation failed";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_stop_before_start:
                    results = "An incorrect function call sequence was made";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_interface_available:
                    results = "A wireless interface has become available";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_interface_unavailable:
                    results = "A wireless interface has become unavailable";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_miniport_stopped:
                    results = "The wireless miniport driver stopped the Hosted Network";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_miniport_started:
                    results = "The wireless miniport driver status changed";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_incompatible_connection_started:
                    results = "An incompatible connection started";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_incompatible_connection_stopped:
                    results = "An incompatible connection stopped";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_user_action:
                    results = "A state change occurred that was caused by explicit user action";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_client_abort:
                    results = "A state change occurred that was caused by client abort";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_ap_start_failed:
                    results = "The driver for the wireless Hosted Network failed to start";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_peer_arrived:
                    results = "A peer connected to the wireless Hosted Network";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_peer_departed:
                    results = "A peer disconnected from the wireless Hosted Network";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_peer_timeout:
                    results = "A peer timed out";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_gp_denied:
                    results = "The operation was denied by group policy";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_service_unavailable:
                    results = "The Wireless LAN service is not running";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_device_change:
                    results = "The wireless adapter used by the wireless Hosted Network changed";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_properties_change:
                    results = "The properties of the wireless Hosted Network changed";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_virtual_station_blocking_use:
                    results = "A virtual station is active and blocking operation";
                    break;
                case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_service_available_on_virtual_station:
                    results = "An identical service is available on a virtual station";
                    break;

            }
            return results;

        }

        // Hosted Network methods
        /// <summary>
        /// Connects to a network defined by a connection parameters structure.
        /// </summary>
        /// <param name="connectionParams">The connection paramters.</param>
        public int WlanHostedNetworkStartUsing(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
        {
            return Wlan.WlanHostedNetworkStartUsing(clientHandle,out reasoncode, IntPtr.Zero);
        }
        /** Makes this app stop using the network.  If the network was started with WlanHostedNetworkStartUsing,
         * then this might cause it to exit, if we were the last app using it.  If it was force started,
         * then it will keep running whether we're here or not.
         */ 
        public int  WlanHostedNetworkStopUsing(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
        {
            return Wlan.WlanHostedNetworkStopUsing(clientHandle, out reasoncode,IntPtr.Zero);
        }
        /** Force the network to stop running right now, even if others are using it. */
        public int WlanHostedNetworkForceStop(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
        {
            return Wlan.WlanHostedNetworkForceStop(clientHandle,  out reasoncode, IntPtr.Zero);
        }
        /** Makes the network start so that it will continue running even after the app exits, DOES require
         * you to be an Administrator */
        public int WlanHostedNetworkForceStart(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
        {
            return Wlan.WlanHostedNetworkForceStart(clientHandle, out reasoncode, IntPtr.Zero);
        }

        public void WlanHostedNetworkInitSettings(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
        {
            Wlan.ThrowIfError(Wlan.WlanHostedNetworkInitSettings(clientHandle, out reasoncode, IntPtr.Zero));
        }
        /** Calls WlanHostedNetworkSetProperty and sets the connection settings which are SSID and max number of peers
         * allowed to call at any one time. 
         * TODO:  need a method to handle the enable opcode.  (which will only work with elevated permissions).
         */
        public void WlanHostedNetworkSetConnectionProperties(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode,
            String ssidName,   int maxPeers        )
        {
            Wlan.Dot11Ssid hostedNetworkSSIDdot11Ssid= GetSSIDForString(ssidName);
            Wlan.WlanHostedNetworkConnectionSettings settings = new Wlan.WlanHostedNetworkConnectionSettings();
            settings.dwMaxNumberOfPeers = maxPeers;
            settings.hostedNetworkSSIDdot11Ssid = hostedNetworkSSIDdot11Ssid;
            IntPtr ptr;
            ptr = Marshal.AllocHGlobal(Marshal.SizeOf(settings));
            Marshal.StructureToPtr(settings, ptr, false);
            Wlan.ThrowIfError(Wlan.WlanHostedNetworkSetProperty(clientHandle, 
                Wlan.WlanHostedNetworkOpcode.wlan_hosted_network_opcode_connection_settings,
                Marshal.SizeOf(settings),
                ptr,            
                out reasoncode, IntPtr.Zero));
        }
        public void WlanHostedNetworkSetEnabled(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode,
            bool enable)
        {
            IntPtr ptr;
            ptr = Marshal.AllocHGlobal(Marshal.SizeOf(enable));
            Marshal.StructureToPtr(enable, ptr, false);
            Wlan.ThrowIfError(Wlan.WlanHostedNetworkSetProperty(clientHandle,
                Wlan.WlanHostedNetworkOpcode.wlan_hosted_network_opcode_enable,
                Marshal.SizeOf(enable),
                ptr,
                out reasoncode, IntPtr.Zero));
        }
        public void WlanHostedNetworkGetEnabled(out bool enable)
        {
            enable=false;
            uint size = 0;
            IntPtr ptrEnable = IntPtr.Zero;
            Wlan.WlanOpcodeValueType opCode = Wlan.WlanOpcodeValueType.QueryOnly;
            Wlan.ThrowIfError(Wlan.WlanHostedNetworkQueryProperty(clientHandle,
                Wlan.WlanHostedNetworkOpcode.wlan_hosted_network_opcode_enable,
                out size,
                out ptrEnable,
                out opCode, IntPtr.Zero));
            if (ptrEnable != IntPtr.Zero)
            {
                // TODO : Better way of marshalling out a bool
                if (size == 1)
                    enable = (bool)(Marshal.ReadByte(ptrEnable) != 0);
                else if (size==2)
                    enable = (bool)(Marshal.ReadInt16(ptrEnable) != 0);
                else if (size == 4)
                    enable = (bool)(Marshal.ReadInt32(ptrEnable) != 0);
                else if (size == 8)
                    enable = (bool)(Marshal.ReadInt64(ptrEnable) != 0);
                Wlan.WlanFreeMemory(ptrEnable);
            }
        }

        public int WlanHostedNetworkQueryStatus(out NativeWifi.Wlan.WlanHostedNetworkStatusHeader networkstatus, out List<Wlan.WlanHostedNetworkPeerState> currentPeers)
        {
            IntPtr statusptr = IntPtr.Zero;
            networkstatus = new Wlan.WlanHostedNetworkStatusHeader();

            currentPeers = new List<Wlan.WlanHostedNetworkPeerState>();

            int i = 0;
            int retval;
            while ((retval = Wlan.WlanHostedNetworkQueryStatus(clientHandle, out statusptr, IntPtr.Zero)) != 0 &&
                    i < 10)
            {
                System.Threading.Thread.Sleep(50);
                i++;
            }

            if (retval != 0)
            {
                return retval;
            }
            try
				{
					Wlan.WlanHostedNetworkStatusHeader hostedStatus =
						(Wlan.WlanHostedNetworkStatusHeader) Marshal.PtrToStructure(statusptr, typeof (Wlan.WlanHostedNetworkStatusHeader));

                    networkstatus = hostedStatus;
                   /* networkstatus.HostedNetworkState = hostedStatus.HostedNetworkState;
                    networkstatus.IPDeviceID = hostedStatus.IPDeviceID;
                    networkstatus.wlanHostedNetworkBSSID = hostedStatus.wlanHostedNetworkBSSID;
                    networkstatus.dot11PhyType = hostedStatus.dot11PhyType;
                    networkstatus.ChannelFrequency = hostedStatus.ChannelFrequency;
                    networkstatus.NumberOfPeers = hostedStatus.NumberOfPeers;
                   */
                    // so NumberOfPeers has the number of peers that are in the array.  
                    if ((hostedStatus.HostedNetworkState == Wlan.WlanHostedNetworkState.wlan_hosted_network_active) &&
                        (hostedStatus.NumberOfPeers > 0))
                    {
                        // iterate through the peers
                        Int64 listIterator = statusptr.ToInt64() + Marshal.SizeOf(hostedStatus);
                        
                        for (int peer = 0; peer < hostedStatus.NumberOfPeers; ++peer)
                        {

                            Wlan.WlanHostedNetworkPeerState info =
                                (Wlan.WlanHostedNetworkPeerState)Marshal.PtrToStructure(new IntPtr(listIterator), typeof(Wlan.WlanHostedNetworkPeerState));
                            listIterator += Marshal.SizeOf(info);
                            currentPeers.Add(info);
                        }
                    }
            }
            finally
            {
                Wlan.WlanFreeMemory(statusptr);
            }
            return 0;
        }

        public void WlanHostedNetworkSetSecondaryKey(string passphrase,bool persistent, bool isPassPhrase, 
            out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
        {
            
            uint length = (uint) passphrase.Length;
            if (isPassPhrase)
            {
                // need to add one for the \0 at end of string
                length++;
            }
            // Wlan.ThrowIfError(
                 Wlan.WlanHostedNetworkSetSecondaryKey(clientHandle, length, passphrase, 
                isPassPhrase, persistent, out reasoncode, IntPtr.Zero);
            //);

        }

        /*
         * Get the current security key
         */
        public void WlanHostedNetworkQuerySecondaryKey(out String passphrase, out bool isPassPhrase, out bool isPersistent, out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
        {
           
            String buffer = "";
            uint length = 0;
             Wlan.ThrowIfError(Wlan.WlanHostedNetworkQuerySecondaryKey(clientHandle, out length, out buffer, 
                out isPassPhrase, out isPersistent,  out reasoncode, IntPtr.Zero));          
            
            passphrase = buffer;
 
            
        }

        /// <summary>
        /// Converts a 802.11 SSID to a string.
        /// </summary>
        public static string GetStringForSSID(Wlan.Dot11Ssid ssid)
        {
            return Encoding.UTF8.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
        }

        public static Wlan.Dot11Ssid GetSSIDForString(String name)
        {
            if (name.Length > 32)
            {
                name = name.Substring(0, 32);
            }
            Wlan.Dot11Ssid ssid = new Wlan.Dot11Ssid();
            ssid.SSID = new byte[32];
            Byte[] bytes = Encoding.UTF8.GetBytes(name);
            uint length = (uint)bytes.Length;

            ssid.SSIDLength = length;
            for (int i = 0; i < ssid.SSID.Length; i++)
            {
                if (i < length)
                {
                    ssid.SSID[i] = bytes[i];
                }
                else
                {
                    ssid.SSID[i] = 0;

                }
            }
            return ssid;
        }
        /// <summary>
        /// Converts a 802.11 MAC to a string.
        /// </summary>
        public static string GetStringForMAC(Wlan.Dot11MacAddress mac)
        {

            return ConvertToHexString(mac.mac1) + ":" +
                ConvertToHexString(mac.mac2) + ":" +
                ConvertToHexString(mac.mac3) + ":" +
                ConvertToHexString(mac.mac4) + ":" +
                ConvertToHexString(mac.mac5) + ":" +
                ConvertToHexString(mac.mac6);

        }
        public static string ConvertToHexString(uint value)
        {
            StringBuilder builder = new StringBuilder("");
            builder.Append(Convert.ToString(value, 16).PadLeft(2, '0'));
            return builder.ToString();
        }
        public static string ConvertPerAuthStateToString(NativeWifi.Wlan.WlanHostedNetworkPeerAuthState val)
        {
            if (val == NativeWifi.Wlan.WlanHostedNetworkPeerAuthState.wlan_hosted_network_peer_state_invalid)
            {
                return "Invalid";
            }
            else if (val == NativeWifi.Wlan.WlanHostedNetworkPeerAuthState.wlan_hosted_network_peer_state_authenticated)
            {
                return "OK";
            }
            else
            {
                return "ERROR";
            }
        }

        private void CloseHandle()
        {
            if (clientHandle != IntPtr.Zero)
            {
                Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
                clientHandle = IntPtr.Zero;
                try
                {
                    lock (instancesLock)
                    {
                        if (instances > 0)
                        {
                            instances--;
                            if (threadInstance != null)
                            {
                                instancesLive.Remove(threadInstance);
                            }
                            else
                            {
                                log.Warn("WlanClient instance on thread " + System.Threading.Thread.CurrentThread.Name + " is already null when trying to remove");
                            }
                            threadInstance = null;
                            if (instances == INSTANCES_WARN_LEVEL - 1)
                            {
                                log.Warn("WlanClient instances fell below warning levels: " + instances);
                            }
                        }
                        if (instances == 0)
                        {
                            instancesReported = false;
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Error("exception doing wlanclient accounting", e);
                }
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            CloseHandle();
        }

        #endregion

        public WlanInterface Interface(Guid guid)
        {
            Wlan.WlanInterfaceInfo info = new Wlan.WlanInterfaceInfo();
            info.interfaceGuid = guid;
            info.interfaceDescription = "";
            info.isState = Wlan.WlanInterfaceState.NotReady;
            WlanInterface wi = new WlanInterface(this, info);
            return wi;
        }
    }

}
