   
 }
 
+void removeWifiSwitch(char* topic, char* payload) {
+  int switchNumber = switchNumberFromTopic(topic);
+  Ws *targetSwitch = findSwitch(switchNumber);
+
+  if (targetSwitch != NULL) {
+     
+     char t[52];
+     snprintf(t, 51,"/devices/%s-%02d/controls/Power/type", SWITCH_ID, switchNumber);
+     publishRetained(t, "");
+
+     memset(t, NULL, 52);
+
+     snprintf(t, 51,"/devices/%s-%02d/controls/Power", SWITCH_ID, switchNumber);
+     publishRetained(t, "");
+
+     memset(t, NULL, 52);
+  
+     snprintf(t, 51,"/devices/%s-%02d/meta/room", SWITCH_ID, switchNumber);
+     publishRetained(t, "");
+
+     memset(t, NULL, 52);
+
+     snprintf(t, 51,"/devices/%s-%02d/meta/name", SWITCH_ID, switchNumber);
+     publishRetained(t, "");
+
+
+    if (targetSwitch == firstSwitch) {
+      firstSwitch = targetSwitch->next;      
+    } else {
+      Ws* before = firstSwitch;    
+      while(before->next != NULL && before->next != targetSwitch)
+      {before = before->next;}        
+      before->next = targetSwitch->next;      
+    }
+    free(targetSwitch);
+    
+  }
+}
+
+
+int switchNumberFromTopic(char* topic) {
+   int switchNumber;
+   sscanf(topic+sizeof(CLIENT_ID)/sizeof(char)+5+15, "%d", &switchNumber);
+   return switchNumber;
+}
 
 void addWifiSwitch(char* topic, char* payload) {
    //Serial.println("Adding new device"); 

  //Serial.println(payload); 

  if (strncmp(topic,"/sys", 4) == 0) { // Cheap parsing here since there is just one function for /sys on this device
    addWifiSwitch(topic, payload);
    return;  
  } 


void loop() {
  client.loop();  // Mqtt loop
  if (connCtr % 65000 == 0) {
    if (!client.connected()) {
      Serial.println("not connected");
connectToMqttServer();
}
    
    connCtr = 0;
  }
  connCtr++;
  
}

void publishRetained(char* topic, char* payload) {
