wip
[oweals/gnunet.git] / src / transport / gnunet-service-transport.c
index 25a6446e748cb7c57b6f9bf396bb0d91c2df89d2..49f9531df6e69e6caffd83b3c564ab08036c9ee9 100644 (file)
 #include <glpk.h>
 #endif
 
-#define DEBUG_BLACKLIST GNUNET_YES
+#define DEBUG_BLACKLIST GNUNET_NO
 
-#define DEBUG_PING_PONG GNUNET_YES
+#define DEBUG_PING_PONG GNUNET_NO
 
-#define DEBUG_TRANSPORT_HELLO GNUNET_YES
+#define DEBUG_TRANSPORT_HELLO GNUNET_NO
 
 #define DEBUG_ATS GNUNET_NO
+
 #define VERBOSE_ATS GNUNET_NO
 
 /**
  */
 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
 
+#define VERY_BIG_DOUBLE_VALUE 100000000000LL
+
+#define ATS_NEW 0
+#define ATS_Q_UPDATED 1
+#define ATS_C_UPDATED 2
+#define ATS_QC_UPDATED 3
+#define ATS_UNMODIFIED 4
 
 /**
  * List of addresses of other peers
@@ -190,6 +198,10 @@ struct ForeignAddressList
    */
   struct Session *session;
 
+  struct ATS_ressource_entry * ressources;
+
+  struct ATS_quality_entry * quality;
+
   /**
    * What was the last latency observed for this address, plugin and peer?
    */
@@ -340,6 +352,8 @@ struct TransportPlugin
    */
   int rebuild;
 
+  struct ATS_plugin * rc;
+
   /**
    * Hashmap of blacklisted peers for this particular transport.
    */
@@ -448,7 +462,6 @@ struct ReadyList
    * To which neighbour does this ready list belong to?
    */
   struct NeighbourList *neighbour;
-
 };
 
 
@@ -836,6 +849,266 @@ struct CheckHelloValidatedContext
   unsigned int ve_count;
 };
 
+struct ATS_quality_metric
+{
+       int index;
+       int atis_index;
+       char * name;
+};
+
+struct ATS_mechanism
+{
+       struct ATS_mechanism * prev;
+       struct ATS_mechanism * next;
+       struct ForeignAddressList * addr;
+       struct TransportPlugin * plugin;
+       struct ATS_peer * peer;
+       int col_index;
+       int     id;
+       struct ATS_ressource_cost * rc;
+};
+
+struct ATS_peer
+{
+       int id;
+       struct GNUNET_PeerIdentity peer;
+       struct NeighbourList * n;
+       struct ATS_mechanism * m_head;
+       struct ATS_mechanism * m_tail;
+
+       /* preference value f */
+       double f;
+       int     t;
+};
+
+struct ATS_stat
+{
+       /**
+        * result of last GLPK run
+        * 5 == OPTIMAL
+        */
+       int solution;
+
+       /**
+        * is problem currently valid and can it be solved
+        */
+       int valid;
+
+       /**
+        * Number of transport mechanisms in the problem
+        */
+       int c_mechs;
+
+       /**
+        * Number of transport mechanisms in the problem
+        */
+       int c_peers;
+
+       /**
+        * row index where quality related rows start
+        */
+       int begin_qm;
+
+       /**
+        * row index where quality related rows end
+        */
+       int end_qm;
+
+       /**
+        * row index where ressource cost related rows start
+        */
+       int begin_cr;
+
+       /**
+        * row index where ressource cost related rows end
+        */
+       int end_cr;
+
+       int col_d;
+       int col_u;
+       int col_r;
+       int col_qm;
+       int col_cr;
+};
+
+struct ATS_ressource_entry
+{
+       /* index in ressources array */
+       int index;
+       /* depending ATSi parameter to calculcate limits */
+       int atis_index;
+       /* lower bound */
+       double c;
+};
+
+
+struct ATS_ressource
+{
+       /* index in ressources array */
+       int index;
+       /* depending ATSi parameter to calculcate limits */
+       int atis_index;
+       /* cfg option to load limits */
+       char * cfg_param;
+       /* lower bound */
+       double c_min;
+       /* upper bound */
+       double c_max;
+
+       /* cofficients for the specific plugins */
+       double c_unix;
+       double c_tcp;
+       double c_udp;
+       double c_http;
+       double c_https;
+       double c_wlan;
+       double c_default;
+};
+
+static struct ATS_ressource ressources[] =
+{
+               /* FIXME: the coefficients for the specific plugins */
+               {1, 7, "LAN_BW_LIMIT", 0, VERY_BIG_DOUBLE_VALUE, 0, 1, 1, 2, 2, 1, 3},
+               {2, 7, "WAN_BW_LIMIT", 0, VERY_BIG_DOUBLE_VALUE, 0, 1, 1, 2, 2, 2, 3},
+               {3, 4, "WLAN_ENERGY_LIMIT", 0, VERY_BIG_DOUBLE_VALUE, 0, 0, 0, 0, 0, 2, 1}
+/*
+               {4, 4, "COST_ENERGY_CONSUMPTION", VERY_BIG_DOUBLE_VALUE},
+               {5, 5, "COST_CONNECT", VERY_BIG_DOUBLE_VALUE},
+               {6, 6, "COST_BANDWITH_AVAILABLE", VERY_BIG_DOUBLE_VALUE},
+               {7, 7, "COST_NETWORK_OVERHEAD", VERY_BIG_DOUBLE_VALUE},*/
+};
+
+static int available_ressources = 3;
+
+
+
+struct ATS_info
+{
+
+       /**
+        * Time of last execution
+        */
+       struct GNUNET_TIME_Absolute last;
+       /**
+        * Minimum intervall between two executions
+        */
+       struct GNUNET_TIME_Relative min_delta;
+       /**
+        * Regular intervall when execution is triggered
+        */
+       struct GNUNET_TIME_Relative exec_interval;
+       /**
+        * Maximum execution time per calculation
+        */
+       struct GNUNET_TIME_Relative max_exec_duration;
+
+#if HAVE_LIBGLPK
+       /**
+        * GLPK (MLP) problem object
+        */
+       glp_prob *prob;
+#endif
+
+       /**
+        * task to recalculate the bandwidth assignment
+        */
+       GNUNET_SCHEDULER_TaskIdentifier ats_task;
+
+       /**
+        * Current state of the GLPK problem
+        */
+       struct ATS_stat stat;
+
+       /**
+        * mechanisms used in current problem
+        * needed for problem modification
+        */
+       struct ATS_mechanism * mechanisms;
+
+       /**
+        * peers used in current problem
+        * needed for problem modification
+        */
+       struct ATS_peer * peers;
+
+       /**
+        * Maximum number of LP iterations per calculation
+        */
+       int max_iterations;
+
+       /**
+        * Dump problem to a file?
+        */
+       int save_mlp;
+
+       /**
+        * Dump solution to a file
+        */
+       int save_solution;
+
+       /**
+        * Dump solution when minimum peers:
+        */
+       int dump_min_peers;
+
+       /**
+        * Dump solution when minimum addresses:
+        */
+       int dump_min_addr;
+
+       /**
+        * Dump solution overwrite file:
+        */
+       int dump_overwrite;
+
+       /**
+        * Ressource costs or quality metrics changed
+        * update problem before solving
+        */
+       int modified_resources;
+
+       /**
+        * Ressource costs or quality metrics changed, update matrix
+        * update problem before solving
+        */
+       int modified_quality;
+
+       /**
+        * Peers have connected or disconnected
+        * problem has to be recreated
+        */
+       int modified_addr;
+
+       /**
+        * Was the available basis invalid and we needed to rerun simplex?
+        */
+       int simplex_rerun_required;
+
+       /**
+        * Diversity weight
+        */
+       double D;
+
+       /**
+        * Utility weight
+        */
+       double U;
+
+       /**
+        * Relativity weight
+        */
+       double R;
+
+       /**
+        * Minimum bandwidth per peer
+        */
+       int v_b_min;
+
+       /**
+        * Minimum number of connections per peer
+        */
+       int v_n_min;
+};
 
 
 /**
@@ -914,6 +1187,22 @@ static struct GNUNET_STATISTICS_Handle *stats;
  */
 static struct ATS_info *ats;
 
+struct ATS_quality_entry
+{
+       int index;
+       int atsi_index;
+       uint32_t values[3];
+       int current;
+};
+
+static struct ATS_quality_metric qm[] =
+{
+               {1, 1028, "QUALITY_NET_DISTANCE"},
+               {2, 1034, "QUALITY_NET_DELAY"},
+};
+static int available_quality_metrics = 2;
+
+
 /**
  * The peer specified by the given neighbour has timed-out or a plugin
  * has disconnected.  We may either need to do nothing (other plugins
@@ -933,29 +1222,31 @@ static void disconnect_neighbour (struct NeighbourList *n, int check);
  * Check the ready list for the given neighbour and if a plugin is
  * ready for transmission (and if we have a message), do so!
  *
- * @param neighbour target peer for which to transmit
+ * @param nexi target peer for which to transmit
  */
 static void try_transmission_to_peer (struct NeighbourList *n);
 
+static void ats_shutdown ( );
 
-struct ATS_info * ats_init ();
-
-void ats_shutdown ( );
-
-void ats_notify_peer_connect (
+static void ats_notify_peer_connect (
                const struct GNUNET_PeerIdentity *peer,
-               const struct GNUNET_TRANSPORT_ATS_Information *ats_data);
+               const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count);
 
-void ats_notify_peer_disconnect (
+static void ats_notify_peer_disconnect (
                const struct GNUNET_PeerIdentity *peer);
 
-void ats_notify_ats_data (
+#if 0
+static void ats_notify_ats_data (
                const struct GNUNET_PeerIdentity *peer,
                const struct GNUNET_TRANSPORT_ATS_Information *ats_data);
+#endif
 
 struct ForeignAddressList * ats_get_preferred_address (
                struct NeighbourList *n);
 
+static void
+ats_calculate_bandwidth_distribution ();
+
 /**
  * Find an entry in the neighbour list for a particular peer.
  *
@@ -972,6 +1263,47 @@ find_neighbour (const struct GNUNET_PeerIdentity *key)
   return head;
 }
 
+static int update_addr_value (struct ForeignAddressList *fal, uint32_t value , int ats_index)
+{
+       int c;
+       int set = GNUNET_NO;
+       for (c=0; c<available_quality_metrics; c++)
+       {
+         if (ats_index == qm[c].atis_index)
+         {
+                 fal->quality[c].values[0] = fal->quality[c].values[1];
+                 fal->quality[c].values[1] = fal->quality[c].values[2];
+                 fal->quality[c].values[2] = value;
+                 set = GNUNET_YES;
+                 ats->modified_quality = GNUNET_YES;
+         }
+       }
+       if (set == GNUNET_NO)
+       {
+         for (c=0; c<available_ressources; c++)
+         {
+                 if (ats_index == ressources[c].atis_index)
+                 {
+                         fal->ressources[c].c = value;
+                         set = GNUNET_YES;
+                         ats->modified_resources = GNUNET_YES;
+                 }
+         }
+       }
+
+       return set;
+}
+
+static int update_addr_ats (struct ForeignAddressList *fal, const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count)
+{
+       int c1, set;
+       set = GNUNET_NO;
+       for (c1=0; c1<ats_count; c1++)
+       {
+                 set = update_addr_value(fal, ntohl(ats_data[c1].value), ntohl(ats_data[c1].type));
+       }
+       return set;
+}
 
 /**
  * Find an entry in the transport list for a particular transport.
@@ -1394,7 +1726,7 @@ transmit_to_client (struct TransportClient *client,
   GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
                                     client->message_queue_tail,
                                     client->message_queue_tail,
-                                    q);                                
+                                    q);
   client->message_count++;
   if (client->th == NULL)
     {
@@ -1668,7 +2000,7 @@ try_transmission_to_peer (struct NeighbourList *n)
 #if DEBUG_TRANSPORT
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Transmission queue for `%4s' is empty\n",
-                 GNUNET_i2s (&neighbour->id));
+                 GNUNET_i2s (&n->id));
 #endif
       return;                     /* nothing to do */
     }
@@ -1749,7 +2081,7 @@ try_transmission_to_peer (struct NeighbourList *n)
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
               mq->message_buf_size,
-              GNUNET_i2s (&neighbour->id),
+              GNUNET_i2s (&n->id),
              (mq->specific_address->addr != NULL)
              ? a2s (mq->plugin->short_name,
                     mq->specific_address->addr,
@@ -1975,7 +2307,7 @@ expire_address_task (void *cls,
  *        expired
  */
 static void
-update_addresses (struct TransportPlugin *plugin, 
+update_addresses (struct TransportPlugin *plugin,
                  int fresh)
 {
   static struct GNUNET_TIME_Absolute last_update;
@@ -2109,7 +2441,7 @@ try_fast_reconnect (struct TransportPlugin *p,
      Furthermore, the same mechanism (or small variation) could be used
      to switch to a better-performing plugin (ATS).
 
-     Finally, this needs to be tested throughly... */                                                          
+     Finally, this needs to be tested throughly... */
 
   /*
    * GNUNET_NO in the call below makes transport disconnect the peer,
@@ -2192,6 +2524,8 @@ plugin_env_session_end  (void *cls,
       GNUNET_SCHEDULER_cancel (pos->revalidate_task);
       pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
     }
+  GNUNET_free_non_null(pos->ressources);
+  GNUNET_free_non_null(pos->quality);
   GNUNET_free (pos);
   if (nl->received_pong == GNUNET_NO)
     return; /* nothing to do, never connected... */
@@ -2251,15 +2585,15 @@ plugin_env_notify_address (void *cls,
   al = p->addresses;
   while (al != NULL)
     {
-      if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
-        {            
+      if ( (addrlen == al->addrlen) &&
+          (0 == memcmp (addr, &al[1], addrlen)) )
+        {
          al->expires = abex;
          update_addresses (p, GNUNET_NO);
           return;
         }
       al = al->next;
     }
-
   al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
   al->next = p->addresses;
   p->addresses = al;
@@ -2313,7 +2647,7 @@ notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
   memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
 
   /* notify ats about connecting peer */
-  ats_notify_peer_connect (peer, &(cim->ats));
+  ats_notify_peer_connect (peer, &(cim->ats), 2);
 
   cpos = clients;
   while (cpos != NULL)
@@ -2429,6 +2763,7 @@ add_peer_address (struct NeighbourList *neighbour,
 {
   struct ReadyList *head;
   struct ForeignAddressList *ret;
+  int c;
 
   ret = find_peer_address (neighbour, tname, session, addr, addrlen);
   if (ret != NULL)
@@ -2445,7 +2780,7 @@ add_peer_address (struct NeighbourList *neighbour,
     return NULL;
   ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
   ret->session = session;
-  if (addrlen > 0)
+  if ((addrlen > 0) && (addr != NULL))
     {
       ret->addr = (const char*) &ret[1];
       memcpy (&ret[1], addr, addrlen);
@@ -2454,6 +2789,54 @@ add_peer_address (struct NeighbourList *neighbour,
     {
       ret->addr = NULL;
     }
+
+  ret->ressources = GNUNET_malloc(available_ressources * sizeof (struct ATS_ressource_entry));
+  int plugin;
+  for (c=0; c<available_ressources; c++)
+  {
+         struct ATS_ressource_entry *r = ret->ressources;
+         r[c].index = c;
+         r[c].atis_index = ressources[c].atis_index;
+         if (0 == strcmp(neighbour->plugins->plugin->short_name,"unix"))
+         {
+                 r[c].c = ressources[c].c_unix;
+                 plugin = 1;
+         }
+         else if (0 == strcmp(neighbour->plugins->plugin->short_name,"udp"))
+         {
+                 r[c].c = ressources[c].c_udp;
+                 plugin = 2;
+         }
+         else if (0 == strcmp(neighbour->plugins->plugin->short_name,"tcp"))
+         {
+                 r[c].c = ressources[c].c_tcp;
+                 plugin = 3;
+         }
+         else if (0 == strcmp(neighbour->plugins->plugin->short_name,"http"))
+         {
+                 r[c].c = ressources[c].c_http;
+                 plugin = 4;
+         }
+         else if (0 == strcmp(neighbour->plugins->plugin->short_name,"https"))
+         {
+                 r[c].c = ressources[c].c_https;
+                 plugin = 5;
+         }
+         else if (0 == strcmp(neighbour->plugins->plugin->short_name,"wlan"))
+         {
+                 r[c].c = ressources[c].c_wlan;
+                 plugin = 6;
+         }
+         else
+         {
+               plugin = -1;
+               r[c].c = ressources[c].c_default;
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR,"Assigning default cost to peer `%s' addr plugin `%s'! This should not happen!",
+                               GNUNET_i2s(&neighbour->peer), neighbour->plugins->plugin->short_name);
+         }
+  }
+
+  ret->quality = GNUNET_malloc (available_quality_metrics * sizeof (struct ATS_quality_entry));
   ret->addrlen = addrlen;
   ret->expires = GNUNET_TIME_relative_to_absolute
     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
@@ -3081,7 +3464,7 @@ do_blacklist_check (void *cls,
   if (bl == NULL)
     {
       bc->cont (bc->cont_cls,
-               setup_new_neighbour (&bc->peer, bc->do_hello));         
+               setup_new_neighbour (&bc->peer, bc->do_hello));
       GNUNET_free (bc);
       return;
     }
@@ -3293,7 +3676,7 @@ send_periodic_ping (void *cls,
   size_t tsize;
 
   peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
-  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
+  if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
     return;
   tp = peer_address->ready_list->plugin;
   neighbour = peer_address->ready_list->neighbour;
@@ -3459,7 +3842,7 @@ schedule_next_ping (struct ForeignAddressList *fal)
     {
       delay = GNUNET_TIME_UNIT_ZERO;
       fal->estimated = GNUNET_YES;
-    }                          
+    }
   if (GNUNET_YES == fal->connected)
     {
       delay = GNUNET_TIME_relative_min (delay,
@@ -3521,14 +3904,14 @@ handle_payload_message (const struct GNUNET_MessageHeader *message,
     {
       n->quota_violation_count++;
 #if DEBUG_TRANSPORT
-      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,                     
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
                  n->in_tracker.available_bytes_per_s__,
                  n->quota_violation_count);
 #endif
       /* Discount 32k per violation */
       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
-                                       - 32 * 1024);           
+                                       - 32 * 1024);
     }
   else
     {
@@ -3700,7 +4083,7 @@ check_pending_validation (void *cls,
                      a2s (ve->transport_name,
                           &addr[slen],
                           alen));
-         return GNUNET_NO;     
+         return GNUNET_NO;
        }
       if (GNUNET_OK !=
          GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
@@ -3770,6 +4153,8 @@ check_pending_validation (void *cls,
                                1,
                                GNUNET_NO);
       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
+      update_addr_value (fal, GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value, GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
+
       schedule_next_ping (fal);
       if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
        n->latency = fal->latency;
@@ -4170,7 +4555,7 @@ check_hello_validated (void *cls,
          GNUNET_CONTAINER_DLL_remove (chvc_head,
                                       chvc_tail,
                                       chvc);
-         GNUNET_free (chvc);   
+         GNUNET_free (chvc);
        }
       return;
     }
@@ -4460,7 +4845,11 @@ disconnect_neighbour (struct NeighbourList *n, int check)
              GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
              peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
            }
-          GNUNET_free(peer_pos);
+                 GNUNET_free(peer_pos->ressources);
+                 peer_pos->ressources = NULL;
+                 GNUNET_free(peer_pos->quality);
+                 peer_pos->ressources = NULL;
+                 GNUNET_free(peer_pos);
         }
       GNUNET_free (rpos);
     }
@@ -4687,7 +5076,7 @@ handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
          GNUNET_assert (GNUNET_OK ==
                         GNUNET_CRYPTO_rsa_sign (my_private_key,
                                                 &pong->purpose,
-                                                &oal->pong_signature));        
+                                                &oal->pong_signature));
          memcpy (&pong->signature,
                  &oal->pong_signature,
                  sizeof (struct GNUNET_CRYPTO_RsaSignature));
@@ -4699,7 +5088,7 @@ handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
          GNUNET_assert (GNUNET_OK ==
                         GNUNET_CRYPTO_rsa_sign (my_private_key,
                                                 &pong->purpose,
-                                                &pong->signature));    
+                                                &pong->signature));
        }
       else
        {
@@ -4770,6 +5159,9 @@ handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
 }
 
 
+
+
+
 /**
  * Function called by the plugin for each received message.
  * Update data volumes, possibly notify plugins about
@@ -4817,6 +5209,7 @@ plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
   peer_address = NULL;
   distance = 1;
+
   for (c=0; c<ats_count; c++)
   {
          if (ntohl(ats_data[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
@@ -4824,8 +5217,10 @@ plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
                  distance = ntohl(ats_data[c].value);
          }
   }
+
   /* notify ATS about incoming data */
-  ats_notify_ats_data(peer, ats_data);
+  //ats_notify_ats_data(peer, ats_data);
+
 
   if (message != NULL)
     {
@@ -4838,7 +5233,11 @@ plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
                                         sender_address_len);
       if (peer_address != NULL)
        {
-         peer_address->distance = distance;
+
+      update_addr_ats(peer_address, ats_data, ats_count);
+      update_addr_value(peer_address, distance, GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
+
+      peer_address->distance = distance;
          if (GNUNET_YES == peer_address->validated)
            mark_address_connected (peer_address);
          peer_address->timeout
@@ -4849,6 +5248,7 @@ plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
        }
       /* update traffic received amount ... */
       msize = ntohs (message->size);
+
       GNUNET_STATISTICS_update (stats,
                                gettext_noop ("# bytes received from other peers"),
                                msize,
@@ -4876,6 +5276,27 @@ plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
                                    GNUNET_NO);
          return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
        }
+    if ((ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_ATS) &&
+       (ntohs(message->size) == (sizeof (struct GNUNET_MessageHeader) + sizeof (uint32_t))))
+    {
+       uint32_t value =  ntohl(*((uint32_t *) &message[1]));
+       //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "GNUNET_MESSAGE_TYPE_TRANSPORT_ATS: %i \n", value);
+       /* Force ressource and quality update */
+       if (value == 4)
+       {
+               ats->modified_resources = GNUNET_YES;
+               ats->modified_quality = GNUNET_YES;
+       }
+       /* Force cost update */
+       if (value == 3)
+               ats->modified_resources = GNUNET_YES;
+       /* Force quality update */
+       if (value == 2)
+               ats->modified_quality = GNUNET_YES;
+       /* Force full rebuild */
+       if (value == 1)
+               ats->modified_addr = GNUNET_YES;
+    }
 
 #if DEBUG_PING_PONG
           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
@@ -4899,6 +5320,8 @@ plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
        case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
          handle_pong (plugin, message, peer, sender_address, sender_address_len);
          break;
+       case GNUNET_MESSAGE_TYPE_TRANSPORT_ATS:
+         break;
        default:
          handle_payload_message (message, n);
          break;
@@ -5406,7 +5829,7 @@ client_disconnect_notification (void *cls,
                  if (bc->th != NULL)
                    {
                      GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
-                     bc->th = NULL;            
+                     bc->th = NULL;
                    }
                  if (bc->task == GNUNET_SCHEDULER_NO_TASK)
                    bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
@@ -5551,357 +5974,1040 @@ shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
   GNUNET_break (bc_head == NULL);
 }
 
-struct ATS_transports
+#if HAVE_LIBGLPK
+static int ats_evaluate_results (int result, int solution, char * problem)
 {
-       int     id;
-       double c_max;
-       double c_1;
-};
+       int cont = GNUNET_NO;
+       int error_kind = GNUNET_ERROR_TYPE_DEBUG;
+#if DEBUG_ATS
+       error_kind = GNUNET_ERROR_TYPE_ERROR;
+#endif
 
-#if HAVE_LIBGLPK
-static glp_prob *
-ats_create_problem (int peers,
-                   int transports, 
-                   double b_min, 
-                   double b_max,
-                   double r, double R, 
-                   const struct ATS_peer * pl, 
-                   const struct ATS_transports * tl, 
-                   int max_it, 
-                   int max_dur, int mlp)
+       switch (result) {
+       case GLP_ESTOP  :    /* search terminated by application */
+               GNUNET_log (error_kind, "%s , Search terminated by application ", problem);
+               break;
+       case GLP_EITLIM :    /* iteration limit exceeded */
+               GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Iteration limit exceeded ", problem);
+               break;
+       break;
+       case GLP_ETMLIM :    /* time limit exceeded */
+               GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Time limit exceeded ", problem);
+       break;
+       case GLP_ENOPFS :    /* no primal feasible solution */
+       case GLP_ENODFS :    /* no dual feasible solution */
+               GNUNET_log (error_kind, "%s No feasible solution", problem);
+       break;
+
+       case GLP_EBADB  :    /* invalid basis */
+       case GLP_ESING  :    /* singular matrix */
+       case GLP_ECOND  :    /* ill-conditioned matrix */
+       case GLP_EBOUND :    /* invalid bounds */
+       case GLP_EFAIL  :    /* solver failed */
+       case GLP_EOBJLL :    /* objective lower limit reached */
+       case GLP_EOBJUL :    /* objective upper limit reached */
+       case GLP_EROOT  :    /* root LP optimum not provided */
+               GNUNET_log (error_kind, "%s Invalid Input data: %i\n", problem, result);
+       break;
+
+       case 0:
+                       GNUNET_log (error_kind, "%s Problem has been solved\n", problem);
+       break;
+       }
+
+       switch (solution) {
+               case GLP_UNDEF:
+                       GNUNET_log (error_kind, "%s solution is undefined\n", problem);
+                       break;
+               case GLP_OPT:
+                       GNUNET_log (error_kind, "%s solution is optimal\n", problem);
+                       cont=GNUNET_YES;
+                       break;
+               case GLP_FEAS:
+                       GNUNET_log (error_kind, "%s solution is %s feasible, however, its optimality (or non-optimality) has not been proven, \n", problem, (0==strcmp(problem,"LP")?"":"integer"));
+                       cont=GNUNET_YES;
+                       break;
+               case GLP_NOFEAS:
+                       GNUNET_log (error_kind, "%s problem has no %sfeasible solution\n", problem,  (0==strcmp(problem,"LP")?"":"integer "));
+                       break;
+               case GLP_INFEAS:
+                       GNUNET_log (error_kind, "%s problem is infeasible \n", problem);
+                       break;
+               case GLP_UNBND:
+                       GNUNET_log (error_kind, "%s problem is unbounded \n", problem);
+               default:
+                       break;
+       }
+return cont;
+}
+
+static void ats_solve_problem (unsigned int max_it, unsigned int  max_dur, unsigned int c_peers, unsigned int  c_mechs, struct ATS_stat *stat)
 {
+       int result;
+       int lp_solution;
+       int mlp_solution;
+
+       // Solving simplex
+
+       glp_smcp opt_lp;
+       glp_init_smcp(&opt_lp);
+#if VERBOSE_ATS
+       opt_lp.msg_lev = GLP_MSG_ALL;
+#else
+       opt_lp.msg_lev = GLP_MSG_OFF;
+#endif
+
+       // setting iteration limit
+       opt_lp.it_lim = max_it;
+       // maximum duration
+       opt_lp.tm_lim = max_dur;
+
+       if (ats->modified_addr == GNUNET_YES)
+               opt_lp.presolve = GLP_ON;
+       result = glp_simplex(ats->prob, &opt_lp);
+       lp_solution =  glp_get_status (ats->prob);
 
-       int result = GLP_UNDEF;
-       int c1, c2;
-       glp_prob *lp;
-       char * peer_n;
-
-       int rows = 1 + (3*peers) +  (transports);
-       int cols = peers;
-       int index = 1;
-       int start = 0;
-       int cur_row = 0;
-
-       //int ia[1+(rows*cols)];
-       //int ja[1+(rows*cols)];
-       //double ar[1+(rows*cols)];
-
-       int * ia = GNUNET_malloc (1+(rows*cols) * sizeof (int));
-       int * ja = GNUNET_malloc (1+(rows*cols) * sizeof (int));
-       double * ar = GNUNET_malloc(1+(rows*cols)* sizeof (double));
-
-       double value;
-
-       if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Creating LP problem: %i peers, relativity r %3.2f, b_max %5.2f, b_min %5.2f, \n",peers, r, b_max, b_min);
-       if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Current memory consumption  %i\n",(1+(rows*cols) * (2*sizeof(int) + sizeof(double))) / (1024*1024));
-       lp = glp_create_prob();
-       glp_set_prob_name(lp, "gnunet ats bandwidth distribution");
-       glp_set_obj_dir(lp, GLP_MAX);
-       /* Adding transports and objective function coefficients*/
-       glp_add_cols(lp, cols);
-       for (c1=1; c1<=cols; c1++)
+       if ((result == GLP_ETMLIM) || (result == GLP_ETMLIM))
        {
-               GNUNET_asprintf(&peer_n,"%s",GNUNET_i2s(&pl[c1-1].peer));
-               if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Peer[%i] , transport %i, %s: f: %f\n",c1-1 , pl[c1-1].t, peer_n, pl[c1-1].f);
-               /* add a single transport*/
-               glp_set_col_name(lp, c1, peer_n);
-               /* add a lower bound */
-               glp_set_col_bnds(lp, c1, GLP_LO, 0.0, 0.0);
-               /* set coefficient function */
-               value = pl[c1-1].f/b_max;
-               value = 1.0;
-               glp_set_obj_coef(lp, c1, value);
-               GNUNET_free(peer_n);
+               ats->stat.valid = GNUNET_NO;
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ATS exceeded time or iteration limit!\n");
+               return;
+       }
+
+       if (ats_evaluate_results(result, lp_solution, "LP") == GNUNET_YES)
+       {
+                       stat->valid = GNUNET_YES;
        }
+       else
+       {
+               ats->simplex_rerun_required = GNUNET_YES;
+               opt_lp.presolve = GLP_ON;
+               result = glp_simplex(ats->prob, &opt_lp);
+               lp_solution =  glp_get_status (ats->prob);
 
-       /* Adding constraints */
-       glp_add_rows(lp, rows);
-       cur_row = 1;
+               // TODO: Remove if this does not appear until release
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "EXECUTED SIMPLEX WITH PRESOLVER! %i", lp_solution);
 
-       /* constraint 1: Maximum bandwidth for all peers
-        * sum(b_i) <= b_max
-        */
-       glp_set_row_bnds(lp, cur_row, GLP_UP, 0.0, b_max);
-       for (index=1; index<=cols; index++)
+               if (ats_evaluate_results(result, lp_solution, "LP") != GNUNET_YES)
+               {
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "After execution simplex with presolver: STILL INVALID!\n");
+                       char * filename;
+                       GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%llu.mlp",ats->stat.c_peers, ats->stat.c_mechs, GNUNET_TIME_absolute_get().abs_value);
+                       glp_write_lp (ats->prob, NULL, filename);
+                       GNUNET_free (filename);
+                       stat->valid = GNUNET_NO;
+                       return;
+               }
+               stat->valid = GNUNET_YES;
+       }
+
+       // Solving mlp
+       glp_iocp opt_mlp;
+       glp_init_iocp(&opt_mlp);
+       // maximum duration
+       opt_mlp.tm_lim = max_dur;
+       // output level
+#if VERBOSE_ATS
+       opt_mlp.msg_lev = GLP_MSG_ALL;
+#else
+       opt_mlp.msg_lev = GLP_MSG_OFF;
+#endif
+
+       result = glp_intopt (ats->prob, &opt_mlp);
+       mlp_solution =  glp_mip_status (ats->prob);
+       stat->solution = mlp_solution;
+
+       if (ats_evaluate_results(result, mlp_solution, "MLP") == GNUNET_YES)
+       {
+               stat->valid = GNUNET_YES;
+       }
+       else
        {
-               ia[index] = 1, ja[index] = index, ar[index] = 1.0;
+               // TODO: Remove if this does not appear until release
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR,  "MLP SOLUTION INVALID: %i\n", lp_solution);
+               stat->valid = GNUNET_NO;
        }
 
-       /* constraint 2: Maximum bandwidth per peer
-        * V b_i in B:  b_i <= b_max
-        */
-       cur_row = 2;
-       start = index+1;
-       for (c1=0; c1<peers; c1++)
+/*
+       int check;
+       int error = GNUNET_NO;
+       double bw;
+       struct ATS_mechanism *t = NULL;
+       for (c=1; c<= (c_peers); c++ )
+       {
+               check = GNUNET_NO;
+               t = peers[c].m_head;
+               while (t!=NULL)
+               {
+                       bw = glp_get_col_prim(prob, t->col_index);
+                       if (bw > 1.0)
+                       {
+#if VERBOSE_ATS
+                               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[%i][%i] `%s' %s %s %f\n", c, t->col_index, GNUNET_h2s(&peers[c].peer.hashPubKey), t->plugin->short_name, glp_get_col_name(prob,t->col_index), bw);
+#endif
+                               if (check ==GNUNET_YES)
+                               {
+                                       glp_write_sol(prob, "invalid_solution.mlp");
+                                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid solution, check invalid_solution.mlp");
+                                       GNUNET_STATISTICS_update (stats, "ATS invalid solutions", 1, GNUNET_NO);
+                                       error = GNUNET_YES;
+                               }
+                               if (check ==GNUNET_NO)
+                                       check = GNUNET_YES;
+                       }
+                       t = t->next;
+               }
+       }*/
+
+#if VERBOSE_ATS
+       if (glp_get_col_prim(ats->prob,2*c_mechs+1) != 1)
+       {
+       int c;
+       for (c=1; c<= available_quality_metrics; c++ )
+       {
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+3+c), glp_get_col_prim(ats->prob,2*c_mechs+3+c));
+       }
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+1), glp_get_col_prim(ats->prob,2*c_mechs+1));
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+2), glp_get_col_prim(ats->prob,2*c_mechs+2));
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+3), glp_get_col_prim(ats->prob,2*c_mechs+3));
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "objective value:  %f\n", glp_mip_obj_val(ats->prob));
+       }
+#endif
+}
+
+static void ats_delete_problem ()
+{
+       int c;
+
+       for (c=0; c< (ats->stat).c_mechs; c++)
+               GNUNET_free_non_null (ats->mechanisms[c].rc);
+
+       if (ats->mechanisms!=NULL)
+       {
+               GNUNET_free(ats->mechanisms);
+               ats->mechanisms = NULL;
+       }
+       if (ats->peers!=NULL)
+       {
+               GNUNET_free(ats->peers);
+               ats->peers = NULL;
+       }
+
+       if (ats->prob != NULL)
        {
-               //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "row: %i \n", cur_row);
-               glp_set_row_bnds(lp, cur_row , GLP_UP, 0.0, b_max);
+               glp_delete_prob(ats->prob);
+               ats->prob = NULL;
+       }
+
+       ats->stat.begin_cr = GNUNET_SYSERR;
+       ats->stat.begin_qm = GNUNET_SYSERR;
+       ats->stat.c_mechs = 0;
+       ats->stat.c_peers = 0;
+       ats->stat.end_cr = GNUNET_SYSERR;
+       ats->stat.end_qm = GNUNET_SYSERR;
+       ats->stat.solution = GNUNET_SYSERR;
+       ats->stat.valid = GNUNET_SYSERR;
+}
+
+
+static void ats_update_problem_qm ()
+{
+       int array_index;
+       int row_index;
+       int c, c2;
+       int c_q_metrics = available_quality_metrics;
+
+       int *ja    = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
+       double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
+#if DEBUG_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
+#endif
+       row_index = ats->stat.begin_qm;
+
+       for (c=1; c <= c_q_metrics; c++)
+       {
+               array_index = 1;
+               double value = 1;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
+#endif
 
-               for (c2 = 1; c2 <= cols; c2++)
+               glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
+               for (c2=1; c2<=ats->stat.c_mechs; c2++)
                {
-                       ia[index] = cur_row;
-                       ja[index] = c2;
-                       ar[index] = ((c1+1 == c2) ? 1.0 : 0.0);
-                       index++;
+                       ja[array_index] = c2;
+
+                       if (qm[c-1].atis_index  == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
+                       {
+                               double v0, v1, v2;
+                               v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
+                               if (v1 < 1) v0 = 0.1;
+                               v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
+                               if (v1 < 1) v0 = 0.1;
+                               v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
+                               if (v1 < 1) v0 = 0.1;
+                               value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
+                               //value = 1;
+                       }
+                       if (qm[c-1].atis_index  == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
+                       {
+                               double v0, v1, v2;
+                               v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
+                               if (v0 < 1) v0 = 1;
+                               v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
+                               if (v1 < 1) v1 = 1;
+                               v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
+                               if (v2 < 1) v2 = 1;
+                               value =  (v0 + 2 * v1 + 3 * v2) / 6.0;
+                               if (value >= 1)
+                                       value =  (double) 10 / value;
+                               else
+                                       value = 10;
+                       }
+                       ar[array_index] = (ats->mechanisms[c2].peer->f) * value;
+#if VERBOSE_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: %s [%i,%i]=%f \n",array_index, qm[c-1].name, row_index, ja[array_index], ar[array_index]);
+#endif
+                       array_index++;
                }
-               cur_row++;
+               ja[array_index] = ats->stat.col_qm + c - 1;
+               ar[array_index] = -1;
+
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
+               #endif
+               glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
+
+               array_index = 1;
+               row_index++;
        }
 
-       /* constraint 3: Minimum bandwidth
-        * V b_i in B:  b_i >= b_min
-        */
-       start = index+1;
-       for (c1=0; c1<peers; c1++)
+       GNUNET_free_non_null (ja);
+       GNUNET_free_non_null (ar);
+}
+
+
+static void ats_update_problem_cr ()
+{
+
+       int array_index;
+       int row_index;
+       int c, c2;
+       double ct_max, ct_min;
+
+       int *ja    = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
+       double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
+
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
+       row_index = ats->stat.begin_cr;
+
+       for (c=0; c<available_ressources; c++)
        {
-               glp_set_row_bnds(lp, cur_row , GLP_LO, b_min, 0.0);
+               ct_max = ressources[c].c_max;
+               ct_min = ressources[c].c_min;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
+#endif
+               glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
 
-               for (c2 = 1; c2 <= cols; c2++)
+               for (c2=1; c2<=ats->stat.c_mechs; c2++)
                {
-                       ia[index] = cur_row;
-                       ja[index] = c2;
-                       ar[index] = ((c1+1 == c2) ? 1.0 : 0.0);
-                       index++;
+                       double value = 0;
+                       ja[array_index] = c2;
+                       value = ats->mechanisms[c2].addr->ressources[c].c;
+                       ar[array_index] = value;
+#if VERBOSE_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
+#endif
+                       array_index++;
                }
-               cur_row++;
+               glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
+
+               row_index ++;
        }
 
-       /* constraint 4: Bandwidth assignment relativity to peer preference
-        * V b_i in B:  b_i >= b_min
-        */
-       start = index+1;
-       for (c1=0; c1<peers; c1++)
+
+       GNUNET_free_non_null (ja);
+       GNUNET_free_non_null (ar);
+}
+
+
+#if 0
+static void ats_update_problem_qm_TEST ()
+{
+       int row_index;
+       int c, c2;
+
+       int old_ja[ats->stat.c_mechs + 2];
+       double old_ar[ats->stat.c_mechs + 2];
+       int c_old;
+       int changed = 0;
+
+       int *ja    = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
+       double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
+#if DEBUG_ATS
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics TEST\n");
+#endif
+       if (ats->stat.begin_qm >0)
+               row_index = ats->stat.begin_qm;
+       else
+               return;
+
+
+       for (c=0; c<available_quality_metrics; c++)
+       {
+
+               c_old = glp_get_mat_row (ats->prob, row_index, old_ja, old_ar);
+
+               glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
+
+               for (c2=1; c2<=c_old; c2++)
+               {
+                       ja[c2] = old_ja[c2];
+                       if ((changed < 3) && (c2>2) && (old_ar[c2] != -1))
+                       {
+                               ar[c2] = old_ar[c2] + 5 - changed;
+                               changed ++;
+                       }
+                       else
+                               ar[c2] = old_ar[c2];
+#if VERBOSE_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: old [%i,%i]=%f  new [%i,%i]=%f\n",c2, row_index, old_ja[c2], old_ar[c2], row_index, ja[c2], ar[c2]);
+#endif
+               }
+               glp_set_mat_row (ats->prob, row_index, c_old, ja, ar);
+
+               row_index ++;
+       }
+
+       GNUNET_free_non_null (ja);
+       GNUNET_free_non_null (ar);
+}
+#endif
+
+
+/** solve the bandwidth distribution problem
+ * @param max_it maximum iterations
+ * @param max_dur maximum duration in ms
+ * @param D    weight for diversity
+ * @param U weight for utility
+ * @param R weight for relativity
+ * @param v_b_min minimal bandwidth per peer
+ * @param v_n_min minimum number of connections
+ * @param stat result struct
+ * @return GNUNET_SYSERR if glpk is not available, number of mechanisms used
+ */
+static int ats_create_problem (double D, double U, double R, int v_b_min, int v_n_min, struct ATS_stat *stat)
+{
+       if (ats->prob != NULL)
+               glp_delete_prob(ats->prob);
+
+       ats->prob = glp_create_prob();
+
+       int c;
+       int c_peers = 0;
+       int c_mechs = 0;
+
+       int c_c_ressources = available_ressources;
+       int c_q_metrics = available_quality_metrics;
+
+       double M = VERY_BIG_DOUBLE_VALUE;
+       double Q[c_q_metrics+1];
+       for (c=1; c<=c_q_metrics; c++)
        {
+               Q[c] = 1;
+       }
 
-               value = pl[c1].f * r;
-               glp_set_row_bnds(lp, cur_row , GLP_LO, value, 0.0);
-               for (c2 = 1; c2 <= cols; c2++)
+       struct NeighbourList *next = neighbours;
+       while (next!=NULL)
+       {
+               struct ReadyList *r_next = next->plugins;
+               while (r_next != NULL)
                {
-                       //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "c1: %i c2 %i  index: %i \n",c1 , c2, index);
-                       ia[index] = cur_row;
-                       ja[index] = c2;
-                       ar[index] = ((c1+1 == c2) ? (1.0/b_max) : 0.0);
-                       //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ia: %i ja %i  ar: %f \n",cur_row , c2, ((c1+1 == c2) ? 1.0 : 0.0));
-                       index++;
+                       struct ForeignAddressList * a_next = r_next->addresses;
+                       while (a_next != NULL)
+                       {
+                               c_mechs++;
+                               a_next = a_next->next;
+                       }
+                       r_next = r_next->next;
                }
-               cur_row++;
+               next = next->next;
+               c_peers++;
        }
 
-       /* constraint 4: transport capacity
-        * sum of b * c_i < c_max */
-       start = index+1;
-       for (c1=0; c1<transports; c1++)
+       if (c_mechs==0)
        {
+#if DEBUG_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No addresses for bw distribution available\n", c_peers);
+#endif
+               stat->valid = GNUNET_NO;
+               stat->c_peers = 0;
+               stat->c_mechs = 0;
+               return GNUNET_SYSERR;
+       }
+
+       ats->mechanisms = GNUNET_malloc((1+c_mechs) * sizeof (struct ATS_mechanism));
+       ats->peers =  GNUNET_malloc((1+c_peers) * sizeof (struct ATS_peer));
 
-               value = tl[c1].c_max;
-               if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transport %i: c_max %5.2f c_1 %5.2f \n", c1, value, tl[c1].c_1);
-               glp_set_row_bnds(lp, cur_row , GLP_UP, 0.0 , value);
+       struct ATS_mechanism * mechanisms = ats->mechanisms;
+       struct ATS_peer * peers = ats->peers;
 
-               for (c2 = 1; c2 <= cols; c2++)
+       c_mechs = 1;
+       c_peers = 1;
+       next = neighbours;
+       while (next!=NULL)
+       {
+               peers[c_peers].peer = next->id;
+               peers[c_peers].m_head = NULL;
+               peers[c_peers].m_tail = NULL;
+               // FIXME
+               peers[c_peers].f = 1.0 / c_mechs;
+
+               struct ReadyList *r_next = next->plugins;
+               while (r_next != NULL)
                {
-                       ia[index] = cur_row;
-                       ja[index] = c2;
-                       ar[index] = ((pl[c1-1].t == tl[c1].id) ? (tl[c1].c_1) : 0.0);
-                       index++;
+                       struct ForeignAddressList * a_next = r_next->addresses;
+                       while (a_next != NULL)
+                       {
+                               mechanisms[c_mechs].addr = a_next;
+                               mechanisms[c_mechs].col_index = c_mechs;
+                               mechanisms[c_mechs].peer = &peers[c_peers];
+                               mechanisms[c_mechs].next = NULL;
+                               mechanisms[c_mechs].plugin = r_next->plugin;
+
+                               GNUNET_CONTAINER_DLL_insert_tail(peers[c_peers].m_head, peers[c_peers].m_tail, &mechanisms[c_mechs]);
+                               c_mechs++;
+                               a_next = a_next->next;
+                       }
+                       r_next = r_next->next;
                }
-               cur_row++;
+               c_peers++;
+               next = next->next;
        }
+       c_mechs--;
+       c_peers--;
+
+       if (v_n_min > c_peers)
+               v_n_min = c_peers;
+
+#if VERBOSE_ATS
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Creating problem with: %i peers, %i mechanisms, %i resource entries, %i quality metrics \n", c_peers, c_mechs, c_c_ressources, c_q_metrics);
+#endif
+
+       int size =  1 + 3 + 10 *c_mechs + c_peers + (c_q_metrics*c_mechs)+ c_q_metrics + c_c_ressources * c_mechs ;
+       int row_index;
+       int array_index=1;
+       int * ia = GNUNET_malloc (size * sizeof (int));
+       int * ja = GNUNET_malloc (size * sizeof (int));
+       double * ar = GNUNET_malloc(size* sizeof (double));
+
+       glp_set_prob_name(ats->prob, "gnunet ats bandwidth distribution");
+       glp_set_obj_dir(ats->prob, GLP_MAX);
+
+       /* adding columns */
+       char * name;
+       glp_add_cols(ats->prob, 2 * c_mechs);
+       /* adding b_t cols */
+       for (c=1; c <= c_mechs; c++)
+       {
 
-       glp_load_matrix(lp, rows * cols, ia, ja, ar);
+               GNUNET_asprintf(&name, "p_%s_b%i",GNUNET_i2s(&(mechanisms[c].peer->peer)), c);
+               glp_set_col_name(ats->prob, c, name);
+               GNUNET_free (name);
+               glp_set_col_bnds(ats->prob, c, GLP_LO, 0.0, 0.0);
+               glp_set_obj_coef(ats->prob, c, 0);
 
-       /* Solve the MLP problem */
-       if (mlp == GNUNET_YES)
+       }
+       /* adding n_t cols */
+       for (c=c_mechs+1; c <= 2*c_mechs; c++)
        {
-               glp_iocp opt;
-               glp_init_iocp(&opt);
-
-               /* Use LP presolver (if not, valid LP solution has to be provided)*/
-               opt.presolve =GLP_ON;
-               /* maximum duration */
-               opt.tm_lim = max_dur;
-               /* output level */
-               if (VERBOSE_ATS)
-                       opt.msg_lev = GLP_MSG_ALL;
-               else
-                       opt.msg_lev = GLP_MSG_OFF;
-               result = glp_intopt(lp, &opt);
+               GNUNET_asprintf(&name, "p_%s_n%i",GNUNET_i2s(&(mechanisms[c-c_mechs].peer->peer)),(c-c_mechs));
+               glp_set_col_name(ats->prob, c, name);
+               GNUNET_free (name);
+               glp_set_col_bnds(ats->prob, c, GLP_DB, 0.0, 1.0);
+               glp_set_col_kind(ats->prob, c, GLP_IV);
+               glp_set_obj_coef(ats->prob, c, 0);
        }
-       /* Solve the LP problem */
+
+       /* feasibility constraints */
+       /* Constraint 1: one address per peer*/
+       row_index = 1;
+       glp_add_rows(ats->prob, c_peers);
+       for (c=1; c<=c_peers; c++)
        {
-               glp_smcp opt ;
-               glp_init_smcp(&opt);
-
-               /* maximum iterations */
-               opt.it_lim = max_it;
-               /* maximum duration */
-               opt.tm_lim = max_dur;
-               /* output level */
-               if (VERBOSE_ATS)
-                       opt.msg_lev = GLP_MSG_ALL;
-               else
-                       opt.msg_lev = GLP_MSG_OFF;
+               glp_set_row_bnds(ats->prob, row_index, GLP_FX, 1.0, 1.0);
+
+               struct ATS_mechanism *m = peers[c].m_head;
+               while (m!=NULL)
+               {
+                       ia[array_index] = row_index;
+                       ja[array_index] = (c_mechs + m->col_index);
+                       ar[array_index] = 1;
+#if VERBOSE_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+                       array_index++;
+                       m = m->next;
+               }
+               row_index++;
+       }
 
-               result = glp_simplex(lp, &opt);
+       /* Constraint 2: only active mechanism gets bandwidth assigned */
+       glp_add_rows(ats->prob, c_mechs);
+       for (c=1; c<=c_mechs; c++)
+       {
+               /* b_t - n_t * M <= 0 */
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
+#endif
+               glp_set_row_bnds(ats->prob, row_index, GLP_UP, 0.0, 0.0);
+
+               ia[array_index] = row_index;
+               ja[array_index] = mechanisms[c].col_index;
+               ar[array_index] = 1;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+               ia[array_index] = row_index;
+               ja[array_index] = c_mechs + mechanisms[c].col_index;
+               ar[array_index] = -M;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+               row_index ++;
        }
 
-       if (DEBUG_ATS)
+       /* Constraint 3: minimum bandwidth*/
+       glp_add_rows(ats->prob, c_mechs);
+       for (c=1; c<=c_mechs; c++)
        {
-               switch (result) {
-               case GLP_ESTOP  :    /* search terminated by application */
-                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Search terminated by application ");
-               case GLP_EITLIM :    /* iteration limit exceeded */
-                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Iteration limit exceeded ");
-               break;
-               case GLP_ETMLIM :    /* time limit exceeded */
-                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Time limit exceeded ");
-               break;
-               case GLP_ENOFEAS:    /* no primal/dual feasible solution */
-               case GLP_ENOCVG :    /* no convergence */
-               case GLP_ERANGE :        /* result out of range */
-               case GLP_ENOPFS :    /* no primal feasible solution */
-               case GLP_ENODFS :    /* no dual feasible solution */
-                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No feasible solution");
-               break;
+               /* b_t - n_t * b_min <= 0 */
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
+#endif
+               glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
 
-               case GLP_EBADB  :    /* invalid basis */
-               case GLP_ESING  :    /* singular matrix */
-               case GLP_ECOND  :    /* ill-conditioned matrix */
-               case GLP_EBOUND :    /* invalid bounds */
-               case GLP_EFAIL  :    /* solver failed */
-               case GLP_EOBJLL :    /* objective lower limit reached */
-               case GLP_EOBJUL :    /* objective upper limit reached */
-               case GLP_EROOT  :    /* root LP optimum not provided */
-               case GLP_EMIPGAP:    /* relative mip gap tolerance reached */
-               case GLP_EINSTAB:    /* numerical instability */
-               case GLP_EDATA  :    /* invalid data */
-                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid Input data\n");
-               break;
+               ia[array_index] = row_index;
+               ja[array_index] = mechanisms[c].col_index;
+               ar[array_index] = 1;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+               ia[array_index] = row_index;
+               ja[array_index] = c_mechs + mechanisms[c].col_index;
+               ar[array_index] = -v_b_min;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+               row_index ++;
+       }
+       int c2;
+       /* Constraint 4: max ressource capacity */
+       /* V cr: bt * ct_r <= cr_max
+        * */
+       glp_add_rows(ats->prob, available_ressources);
+       double ct_max = VERY_BIG_DOUBLE_VALUE;
+       double ct_min = 0.0;
 
-               break;
-                       default:
-                               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Optimal solution\n");
-               break;
+       stat->begin_cr = array_index;
+
+       for (c=0; c<available_ressources; c++)
+       {
+               ct_max = ressources[c].c_max;
+               ct_min = ressources[c].c_min;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
+#endif
+               glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
+
+               for (c2=1; c2<=c_mechs; c2++)
+               {
+                       double value = 0;
+                       ia[array_index] = row_index;
+                       ja[array_index] = c2;
+                       value = mechanisms[c2].addr->ressources[c].c;
+                       ar[array_index] = value;
+#if VERBOSE_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+                       array_index++;
+               }
+               row_index ++;
+       }
+       stat->end_cr = array_index--;
+
+       /* Constraint 5: min number of connections*/
+       glp_add_rows(ats->prob, 1);
+       for (c=1; c<=c_mechs; c++)
+       {
+               // b_t - n_t * b_min >= 0
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
+#endif
+               glp_set_row_bnds(ats->prob, row_index, GLP_LO, v_n_min, 0.0);
+
+               ia[array_index] = row_index;
+               ja[array_index] = c_mechs + mechanisms[c].col_index;
+               ar[array_index] = 1;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+       }
+       row_index ++;
+
+       // optimisation constraints
+
+       // adding columns
+
+       // Constraint 6: optimize for diversity
+       int col_d;
+       col_d = glp_add_cols(ats->prob, 1);
+       stat->col_d = col_d;
+       //GNUNET_assert (col_d == (2*c_mechs) + 1);
+       glp_set_col_name(ats->prob, col_d, "d");
+       glp_set_obj_coef(ats->prob, col_d, D);
+       glp_set_col_bnds(ats->prob, col_d, GLP_LO, 0.0, 0.0);
+       glp_add_rows(ats->prob, 1);
+#if VERBOSE_ATS
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
+#endif
+       glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
+       for (c=1; c<=c_mechs; c++)
+       {
+               // b_t - n_t * b_min >= 0
+               ia[array_index] = row_index;
+               ja[array_index] = c_mechs + mechanisms[c].col_index;
+               ar[array_index] = 1;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+       }
+       ia[array_index] = row_index;
+       ja[array_index] = col_d;
+       ar[array_index] = -1;
+#if VERBOSE_ATS
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+       array_index++;
+       row_index ++;
+
+
+       // Constraint 7: optimize for quality
+       int col_qm;
+       col_qm = glp_add_cols(ats->prob, c_q_metrics);
+       stat->col_qm = col_qm;
+       //GNUNET_assert (col_qm == (2*c_mechs) + 3 + 1);
+       for (c=0; c< c_q_metrics; c++)
+       {
+               GNUNET_asprintf(&name, "Q_%s",qm[c].name);
+               glp_set_col_name(ats->prob, col_qm + c, name);
+               glp_set_col_bnds(ats->prob, col_qm + c, GLP_LO, 0.0, 0.0);
+               GNUNET_free (name);
+               glp_set_obj_coef(ats->prob, col_qm + c, Q[c]);
+       }
+    glp_add_rows(ats->prob, available_quality_metrics);
+       stat->begin_qm = row_index;
+       for (c=1; c <= c_q_metrics; c++)
+       {
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
+#endif
+               double value = 1;
+               glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
+               for (c2=1; c2<=c_mechs; c2++)
+               {
+
+                       ia[array_index] = row_index;
+                       ja[array_index] = c2;
+                       if (qm[c-1].atis_index  == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
+                       {
+                               double v0, v1, v2;
+                               v0 = mechanisms[c2].addr->quality[c-1].values[0];
+                               if (v1 < 1) v0 = 0.1;
+                               v1 = mechanisms[c2].addr->quality[c-1].values[1];
+                               if (v1 < 1) v0 = 0.1;
+                               v2 = mechanisms[c2].addr->quality[c-1].values[2];
+                               if (v1 < 1) v0 = 0.1;
+                               value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
+                               value = 1;
+                       }
+                       if (qm[c-1].atis_index  == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
+                       {
+                               double v0, v1, v2;
+                               v0 = mechanisms[c2].addr->quality[c-1].values[0];
+                               if (v0 < 1) v0 = 1;
+                               v1 = mechanisms[c2].addr->quality[c-1].values[1];
+                               if (v1 < 1) v1 = 1;
+                               v2 = mechanisms[c2].addr->quality[c-1].values[2];
+                               if (v2 < 1) v2 = 1;
+                               value =  (v0 + 2 * v1 + 3 * v2) / 6.0;
+                               if (value >= 1)
+                                       value =  (double) 10 / value;
+                               else
+                                       value = 10;
+                       }
+                       ar[array_index] = (mechanisms[c2].peer->f) * value ;
+#if VERBOSE_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: %s [%i,%i]=%f \n",array_index, qm[c-1].name, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+                       array_index++;
                }
+
+               ia[array_index] = row_index;
+               ja[array_index] = col_qm + c - 1;
+               ar[array_index] = -1;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+               row_index++;
+       }
+       stat->end_qm = row_index-1;
+
+       // Constraint 8: optimize bandwidth utility
+       int col_u;
+       col_u = glp_add_cols(ats->prob, 1);
+       stat->col_u = col_u;
+       //GNUNET_assert (col_u == (2*c_mechs) + 2);
+       glp_set_col_name(ats->prob, col_u, "u");
+       glp_set_obj_coef(ats->prob, col_u, U);
+       glp_set_col_bnds(ats->prob, col_u, GLP_LO, 0.0, 0.0);
+       glp_add_rows(ats->prob, 1);
+#if VERBOSE_ATS
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
+#endif
+       glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
+       for (c=1; c<=c_mechs; c++)
+       {
+               ia[array_index] = row_index;
+               ja[array_index] = c;
+               ar[array_index] = mechanisms[c].peer->f;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
        }
+       ia[array_index] = row_index;
+       ja[array_index] = col_u;
+       ar[array_index] = -1;
+#if VERBOSE_ATS
+       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
 
-       char * debug_solution = NULL;
-       char * old = NULL;
-       for (c1=1; c1<= peers; c1++ )
+       array_index++;
+       row_index ++;
+
+       // Constraint 9: optimize relativity
+       int col_r;
+       col_r = glp_add_cols(ats->prob, 1);
+       stat->col_r = col_r;
+       //GNUNET_assert (col_r == (2*c_mechs) + 3);
+       glp_set_col_name(ats->prob, col_r, "r");
+       glp_set_obj_coef(ats->prob, col_r, R);
+       glp_set_col_bnds(ats->prob, col_r, GLP_LO, 0.0, 0.0);
+       glp_add_rows(ats->prob, c_peers);
+       for (c=1; c<=c_peers; c++)
        {
-               old = debug_solution;
-               GNUNET_asprintf(&debug_solution, "%s %s = %g;", (debug_solution!=NULL) ? debug_solution : "", GNUNET_i2s(&pl[c1-1].peer), glp_get_col_prim(lp, c1));
-               if (old!=NULL) GNUNET_free(old);
+               glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
+
+               struct ATS_mechanism *m = peers[c].m_head;
+               while (m!=NULL)
+               {
+                       ia[array_index] = row_index;
+                       ja[array_index] = m->col_index;
+                       ar[array_index] = 1 / mechanisms[c].peer->f;
+#if VERBOSE_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+                       array_index++;
+                       m = m->next;
+               }
+               ia[array_index] = row_index;
+               ja[array_index] = col_r;
+               ar[array_index] = -1;
+#if VERBOSE_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
+#endif
+               array_index++;
+
+               row_index++;
        }
-       GNUNET_asprintf(&debug_solution, "%s z = %g; \n", debug_solution,  glp_get_obj_val(lp));
-       if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s \n",debug_solution);
-       GNUNET_free(debug_solution);
 
-       glp_delete_prob(lp);
+       /* Loading the matrix */
+       glp_load_matrix(ats->prob, array_index-1, ia, ja, ar);
 
-       GNUNET_free(ar);
-       GNUNET_free(ia);
-       GNUNET_free(ja);
+       stat->c_mechs = c_mechs;
+       stat->c_peers = c_peers;
+       stat->solution = 0;
+       stat->valid = GNUNET_YES;
+
+       /* clean up */
+
+       GNUNET_free (ja);
+       GNUNET_free (ia);
+       GNUNET_free (ar);
+
+       return GNUNET_OK;
 
-       return lp;
 }
-#else
-static void *
-ats_create_problem (int peers,
-                   int transports, 
-                   double b_min, 
-                   double b_max,
-                   double r, double R, 
-                   const struct ATS_peer * pl, 
-                   const struct ATS_transports * tl, 
-                   int max_it, 
-                   int max_dur, int mlp)
+
+void ats_notify_ats_data (
+               const struct GNUNET_PeerIdentity *peer,
+               const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
 {
-  return NULL;
-}
+#if DEBUG_ATS
+       GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ATS_notify_ats_data: %s\n",GNUNET_i2s(peer));
 #endif
+       ats_calculate_bandwidth_distribution();
+}
+#endif //END: HAVE_LIBGLPK
 
-
-void ats_calculate_bandwidth_distribution ()
+static void
+ats_calculate_bandwidth_distribution ()
 {
-       struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_difference(ats->last,GNUNET_TIME_absolute_get());
+#if HAVE_LIBGLPK
+       struct GNUNET_TIME_Absolute start;
+       struct GNUNET_TIME_Relative creation;
+       struct GNUNET_TIME_Relative solving;
+       char *text = "unmodified";
+
+       struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_difference (ats->last, GNUNET_TIME_absolute_get());
        if (delta.rel_value < ats->min_delta.rel_value)
        {
 #if DEBUG_ATS
-               //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Minimum time between cycles not reached\n");
+               GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Minimum time between cycles not reached\n");
 #endif
                return;
        }
 
-       struct GNUNET_TIME_Absolute start;
-       int test = 3;
-       int mlp = GNUNET_YES;
-
-       //for (test=1; test<75000; test++)
-       //{
-       int peers = test;
-       int transports = 3;
-
-       double b_min   = 1;
-       double b_max   = 100000.0;
-       double r           = 0.85;//1.0;
-       double R           = 1.0;
-
-       int it = ATS_MAX_ITERATIONS;
        int dur = 500;
        if (INT_MAX < ats->max_exec_duration.rel_value)
                dur = INT_MAX;
        else
                dur = (int) ats->max_exec_duration.rel_value;
+       ats->simplex_rerun_required = GNUNET_NO;
 
+       start = GNUNET_TIME_absolute_get();
+       if ((ats->modified_addr == GNUNET_YES) || (ats->prob==NULL))
+       {
+               text = "new";
+               ats->modified_addr = GNUNET_YES;
+               ats_delete_problem ();
+               ats_create_problem (ats->D, ats->U, ats->R, ats->v_b_min, ats->v_n_min, &ats->stat);
+#if DEBUG_ATS
+               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Peers/Addresses were modified... new problem: %i peer, %i mechs\n", ats->stat.c_peers, ats->stat.c_mechs);
+#endif
+       }
+       else if ((ats->modified_addr == GNUNET_NO) && (ats->modified_resources == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
+       {
+               ats_update_problem_cr();
+               text = "modified resources";
+       }
+       else if ((ats->modified_addr == GNUNET_NO) && (ats->modified_quality == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
+       {
+               ats_update_problem_qm();
+               //ats_update_problem_qm_TEST ();
+               text = "modified quality";
+       }
+#if DEBUG_ATS
+       else GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Problem is unmodified\n");
+#endif
 
-       struct ATS_transports * tl = GNUNET_malloc(transports * sizeof (struct ATS_peer));
+       creation = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
+       start = GNUNET_TIME_absolute_get();
 
-       struct ATS_peer * pl = GNUNET_malloc(peers * sizeof (struct ATS_peer));
-       int c = 0;
-       while (c < peers)
+       if (ats->stat.valid == GNUNET_YES)
        {
-               pl[c].peer.hashPubKey.bits[0] = c+1;
-               pl[c].f = 1 / (double) peers ;
-               pl[c].t = 1;
-               //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_calculate_bandwidth_distribution Peer[%i] : %s %p \n",c , GNUNET_i2s(&pl[c].peer), &pl[c].peer);
-               c++;
+               ats->stat.solution = GNUNET_SYSERR;
+               ats_solve_problem(ats->max_iterations, ats->max_exec_duration.rel_value, ats->stat.c_peers, ats->stat.c_mechs, &ats->stat);
        }
-       c = 0;
-       while (c < transports)
+       solving = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
+
+       if (ats->stat.valid == GNUNET_YES)
        {
-               tl[c].id = c;
-               tl[c].c_max = 100000;
-               tl[c].c_1 = 1;
-               c++;
-               //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_calculate_bandwidth_distribution Peer[%i] : %s %p \n",c , GNUNET_i2s(&pl[c].peer), &pl[c].peer);
+#if DEBUG_ATS
+                       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP %s: creation time in [ms] %llu execution time in [ms] %llu for %i mechanisms: simplex rerun: %s\n",
+                                       text, creation.rel_value, solving.rel_value,
+                                       ats->stat.c_mechs,
+                                       (ats->simplex_rerun_required == GNUNET_NO) ? " NO" : "YES");
+#endif
+               GNUNET_STATISTICS_set (stats, "ATS duration", solving.rel_value + creation.rel_value, GNUNET_NO);
+               GNUNET_STATISTICS_set (stats, "ATS mechanisms", ats->stat.c_mechs, GNUNET_NO);
+               GNUNET_STATISTICS_set (stats, "ATS peers", ats->stat.c_peers, GNUNET_NO);
+               GNUNET_STATISTICS_set (stats, "ATS solution", ats->stat.solution, GNUNET_NO);
+               GNUNET_STATISTICS_set (stats, "ATS timestamp", start.abs_value, GNUNET_NO);
+
+               if ((ats->modified_addr == GNUNET_YES) || (ats->prob==NULL))
+                       GNUNET_STATISTICS_set (stats, "ATS state",ATS_NEW, GNUNET_NO);
+               else if ((ats->modified_resources == GNUNET_YES) &&
+                               (ats->modified_quality == GNUNET_NO))
+                       GNUNET_STATISTICS_set (stats, "ATS state", ATS_C_UPDATED, GNUNET_NO);
+               else if ((ats->modified_resources == GNUNET_NO) &&
+                               (ats->modified_quality == GNUNET_YES) &&
+                               (ats->simplex_rerun_required == GNUNET_NO))
+                       GNUNET_STATISTICS_set (stats, "ATS state", ATS_Q_UPDATED, GNUNET_NO);
+               else if ((ats->modified_resources == GNUNET_YES) &&
+                               (ats->modified_quality == GNUNET_YES) &&
+                               (ats->simplex_rerun_required == GNUNET_NO))
+                       GNUNET_STATISTICS_set (stats, "ATS state", ATS_QC_UPDATED, GNUNET_NO);
+               else if (ats->simplex_rerun_required == GNUNET_NO)
+                       GNUNET_STATISTICS_set (stats, "ATS state", ATS_UNMODIFIED, GNUNET_NO);
        }
 
-       // test //
-
-       //pl[0].f = 0.33;
-       //pl[2].f = 0.43;
-       //pl[1].f = 0.33;
-       // test //
-       start = GNUNET_TIME_absolute_get();
-       ats_create_problem(peers, transports, b_min, b_max, r, R, pl, tl, it, dur, mlp);
-       if (DEBUG_ATS)
-               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s,%i,%llu,%i\n",(mlp)?"mlp":"lp", peers,
-                               GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get()).rel_value, (1+(peers*transports) * (2*sizeof(int) + sizeof(double))));
-
-       GNUNET_free (pl);
-       GNUNET_free (tl);
-       //}
+       if ((ats->save_mlp == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
+       {
+               char * filename;
+               if (ats->dump_overwrite == GNUNET_NO)
+               {
+                       GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.mlp",
+                       ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
+                       glp_write_lp (ats->prob, NULL, filename);
+               }
+               else
+               {
+                       GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.mlp",
+                       ats->stat.c_peers, ats->stat.c_mechs );
+                       glp_write_lp (ats->prob, NULL, filename);
+               }
+               GNUNET_free (filename);
+       }
+       if ((ats->save_solution == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
+       {
+               char * filename;
+               if (ats->dump_overwrite == GNUNET_NO)
+               {
+                       GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.sol",
+                       ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
+                       glp_print_sol (ats->prob, filename);
+               }
+               else
+               {
+                       GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.sol",
+                       ats->stat.c_peers, ats->stat.c_mechs);
+                       glp_print_sol (ats->prob, filename);
+               }
+               GNUNET_free (filename);
+       }
        ats->last = GNUNET_TIME_absolute_get();
+       ats->modified_addr = GNUNET_NO;
+       ats->modified_resources = GNUNET_NO;
+       ats->modified_quality = GNUNET_NO;
+#endif
 }
 
-
-
-void
+static void
 ats_schedule_calculation (void *cls,
                          const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
        struct ATS_info *ats = (struct ATS_info *) cls;
-       if (ats==NULL)
-               return;
+       if (ats==NULL) return;
 
        ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
        if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
@@ -5910,59 +7016,119 @@ ats_schedule_calculation (void *cls,
 #if DEBUG_ATS
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Running scheduled calculation\n");
 #endif
+
        ats_calculate_bandwidth_distribution (ats);
 
-       ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->exec_intervall,
+       ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->exec_interval,
                                        &ats_schedule_calculation, ats);
 }
 
-
-int ats_map_remove_peer (void *cls,
-               const GNUNET_HashCode * key,
-               void *value)
+void ats_init ()
 {
+       int c = 0;
+       unsigned long long  value;
+       char * section;
 
-       struct ATS_peer * p =  (struct ATS_peer *) value;
-#if DEBUG_ATS
-       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "map_remove_peer_it: `%s'\n", GNUNET_i2s(&p->peer));
+       ats = GNUNET_malloc(sizeof (struct ATS_info));
+
+       ats->min_delta = ATS_MIN_INTERVAL;
+       ats->exec_interval = ATS_EXEC_INTERVAL;
+       ats->max_exec_duration = ATS_MAX_EXEC_DURATION;
+       ats->max_iterations = ATS_MAX_ITERATIONS;
+       ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
+
+#if !HAVE_LIBGLPK
+       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "GLPK not installed, ATS not active\n");
+       return;
 #endif
-       /* cleanup peer */
-       GNUNET_free(p);
 
-       return GNUNET_YES;
-}
+       ats->D = 1.0;
+       ats->U = 1.0;
+       ats->R = 1.0;
+       ats->v_b_min = 64000;
+       ats->v_n_min = 10;
+       ats->dump_min_peers = 1;
+       ats->dump_min_addr = 1;
+       ats->dump_overwrite = GNUNET_NO;
 
+#if HAVE_LIBGLPK
+       ats->prob = NULL;
+#endif
 
-struct ATS_info * ats_init ()
-{
-       struct ATS_info * ats;
+       /* loading cost ressources */
+       for (c=0; c<available_ressources; c++)
+       {
+               GNUNET_asprintf(&section,"%s_UP",ressources[c].cfg_param);
+               if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
+               {
+                       if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
+                       {
 #if DEBUG_ATS
-       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_init\n");
+                               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
 #endif
-       ats = GNUNET_malloc(sizeof (struct ATS_info));
-       ats->peers = GNUNET_CONTAINER_multihashmap_create(10);
-       GNUNET_assert(ats->peers!=NULL);
+                               ressources[c].c_max = value;
+                       }
+               }
+               GNUNET_free (section);
+               GNUNET_asprintf(&section,"%s_DOWN",ressources[c].cfg_param);
+               if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
+               {
+                       if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
+                       {
+#if DEBUG_ATS
+                               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
+#endif
+                               ressources[c].c_min = value;
+                       }
+               }
+               GNUNET_free (section);
+       }
 
-       ats->min_delta = ATS_MIN_INTERVAL;
-       ats->exec_intervall = ATS_EXEC_INTERVAL;
-       ats->max_exec_duration = ATS_MAX_EXEC_DURATION;
-       ats->max_iterations = ATS_MAX_ITERATIONS;
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MLP"))
+               ats->save_mlp = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_MLP");
 
-       ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
-/*
-       ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->reg_delta,
-                                       &schedule_calculation, NULL);
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_SOLUTION"))
+               ats->save_solution = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_SOLUTION");
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
+               ats->dump_overwrite = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_OVERWRITE");
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_PEERS"))
+       {
+               GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_PEERS", &value);
+               ats->dump_min_peers= value;
+       }
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_ADDRS"))
+       {
+               GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_ADDRS", &value);
+               ats->dump_min_addr= value;
+       }
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
+       {
+               GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_OVERWRITE", &value);
+               ats->min_delta.rel_value = value;
+       }
 
-       ats->ats_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                       &schedule_calculation, NULL);
-*/
-       ats->ats_task = GNUNET_SCHEDULER_add_now(&ats_schedule_calculation, ats);
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
+       {
+               GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
+               ats->min_delta.rel_value = value;
+       }
 
-       return ats;
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_EXEC_INTERVAL"))
+       {
+               GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_EXEC_INTERVAL", &value);
+               ats->exec_interval.rel_value = value;
+       }
+       if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
+       {
+               GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
+               ats->min_delta.rel_value = value;
+       }
+
+       ats->ats_task = GNUNET_SCHEDULER_add_now(&ats_schedule_calculation, ats);
 }
 
 
-void ats_shutdown ()
+static void ats_shutdown ()
 {
 #if DEBUG_ATS
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_destroy\n");
@@ -5970,36 +7136,23 @@ void ats_shutdown ()
        if (ats->ats_task != GNUNET_SCHEDULER_NO_TASK)
                GNUNET_SCHEDULER_cancel(ats->ats_task);
        ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
-
-       GNUNET_CONTAINER_multihashmap_iterate (ats->peers,ats_map_remove_peer,NULL);
-       GNUNET_CONTAINER_multihashmap_destroy (ats->peers);
+#if HAVE_LIBGLPK
+       ats_delete_problem ();
+#endif
        GNUNET_free (ats);
 }
 
 
 void ats_notify_peer_connect (
                const struct GNUNET_PeerIdentity *peer,
-               const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
+               const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count)
 {
-       int c = 0;
 #if DEBUG_ATS
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_connect: %s\n",GNUNET_i2s(peer));
 #endif
 
-       while (ntohl(ats_data[c].type)!=0)
-       {
-#if DEBUG_ATS
-               GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats type [%i]: %i\n",ntohl(ats_data[c].type), ntohl(ats_data[c].value));
-#endif
-               c++;
-       }
-       /* check if peer is already known */
-       if (!GNUNET_CONTAINER_multihashmap_contains (ats->peers,&peer->hashPubKey))
-       {
-               struct ATS_peer * p = GNUNET_malloc (sizeof (struct ATS_peer));
-               memcpy(&p->peer, peer, sizeof (struct GNUNET_PeerIdentity));
-               GNUNET_CONTAINER_multihashmap_put(ats->peers, &p->peer.hashPubKey, p, GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
-       }
+       //update_addr_ats();
+       ats->modified_addr = GNUNET_YES;
 
        ats_calculate_bandwidth_distribution(ats);
 }
@@ -6010,25 +7163,10 @@ void ats_notify_peer_disconnect (
 #if DEBUG_ATS
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_disconnect: %s\n",GNUNET_i2s(peer));
 #endif
-       /* remove peer */
-       if (GNUNET_CONTAINER_multihashmap_contains (ats->peers, &peer->hashPubKey))
-       {
-               ats_map_remove_peer(NULL, &peer->hashPubKey, GNUNET_CONTAINER_multihashmap_get (ats->peers, &peer->hashPubKey));
-               GNUNET_CONTAINER_multihashmap_remove_all (ats->peers, &peer->hashPubKey);
-       }
 
-       ats_calculate_bandwidth_distribution (ats);
-}
+       ats->modified_addr = GNUNET_YES;
 
-
-void ats_notify_ats_data (
-               const struct GNUNET_PeerIdentity *peer,
-               const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
-{
-#if DEBUG_ATS
-       GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ATS_notify_ats_data: %s\n",GNUNET_i2s(peer));
-#endif
-       ats_calculate_bandwidth_distribution(ats);
+       ats_calculate_bandwidth_distribution (ats);
 }
 
 struct ForeignAddressList * ats_get_preferred_address (
@@ -6113,19 +7251,13 @@ run (void *cls,
       validation_map = NULL;
       return;
     }
-#if HAVE_GLPK
-         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("HAVE\n"));
-#else
-         //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("NOT HAVE\n"));
-#endif
 
-  ats = ats_init();
   max_connect_per_transport = (uint32_t) tneigh;
   peerinfo = GNUNET_PEERINFO_connect (cfg);
   if (peerinfo == NULL)
     {
       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
-                 _("Could not access PEERINFO service.  Exiting.\n")); 
+                 _("Could not access PEERINFO service.  Exiting.\n"));
       GNUNET_SCHEDULER_shutdown ();
       if (stats != NULL)
        {
@@ -6182,6 +7314,8 @@ run (void *cls,
   if (no_transports)
     refresh_hello ();
 
+  ats_init();
+
 #if DEBUG_TRANSPORT
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
 #endif