src/sn_normalize.c: Add a program to normalize sort networks.
[sort-networks.git] / src / sn_stage.c
index 0cfabe9..85ec45d 100644 (file)
@@ -64,6 +64,7 @@ int sn_stage_comparator_remove (sn_stage_t *s, int c_num)
   sn_comparator_t *temp;
 
   assert (c_num < s->comparators_num);
+  assert (c_num >= 0);
 
   if (nmemb > 0)
     memmove (s->comparators + c_num, s->comparators + (c_num + 1),
@@ -71,15 +72,46 @@ int sn_stage_comparator_remove (sn_stage_t *s, int c_num)
   s->comparators_num--;
 
   /* Free the unused memory */
-  temp = (sn_comparator_t *) realloc (s->comparators,
-      s->comparators_num * sizeof (sn_comparator_t));
-  if (temp == NULL)
-    return (-1);
-  s->comparators = temp;
+  if (s->comparators_num == 0)
+  {
+    free (s->comparators);
+    s->comparators = NULL;
+  }
+  else
+  {
+    temp = (sn_comparator_t *) realloc (s->comparators,
+       s->comparators_num * sizeof (sn_comparator_t));
+    if (temp == NULL)
+      return (-1);
+    s->comparators = temp;
+  }
 
   return (0);
 } /* int sn_stage_comparator_remove */
 
+sn_stage_t *sn_stage_clone (const sn_stage_t *s)
+{
+  sn_stage_t *s_copy;
+
+  s_copy = sn_stage_create (s->depth);
+  if (s_copy == NULL)
+    return (NULL);
+
+  s_copy->comparators = (sn_comparator_t *) malloc (s->comparators_num
+      * sizeof (sn_comparator_t));
+  if (s_copy->comparators == NULL)
+  {
+    free (s_copy);
+    return (NULL);
+  }
+
+  memcpy (s_copy->comparators, s->comparators,
+      s->comparators_num * sizeof (sn_comparator_t));
+  s_copy->comparators_num = s->comparators_num;
+
+  return (s_copy);
+} /* sn_stage_t *sn_stage_clone */
+
 int sn_stage_comparator_check_conflict (sn_stage_t *s, const sn_comparator_t *c0)
 {
   int i;