Index: trunk/cgi-bin/IPDB.pm
===================================================================
--- trunk/cgi-bin/IPDB.pm	(revision 723)
+++ trunk/cgi-bin/IPDB.pm	(revision 724)
@@ -214,6 +214,31 @@
   my $dbh = shift;
   my $id = shift;
+  my $createfb = shift;  # may be null at this point
 
   my $binfo = getBlockData($dbh, $id);
+
+  # Decide if we're going to add a free block.
+
+  # Caller is normal block delete -> add freeblock under $binfo->{parent_id} -> pass nothing
+  # Caller is delete for merge to leaf -> do not add freeblock -> pass 0
+  # Caller is normal master delete -> do not add freeblock -> pass nothing
+  # Caller is merge master -> add freeblock under alternate parent -> pass parent ID
+  if ($binfo->{type} ne 'mm') {
+    # Deleting a non-master block
+    if (!defined($createfb)) {
+      # No createfb flag passed;  assuming normal block delete.  Add the freeblock
+      # under the parent of the block we're deleting.
+      $createfb = $binfo->{parent_id};
+    #} else {
+      # Don't need to actually do anything here.  The caller has given us an ID,
+      # which is either 0 (causing no free block) or (theoretically) a valid block
+      # ID to add the free block under.
+    }
+  #} else {
+    # Deleting a master block
+    # Don't need to actually do anything here.  If the caller passed a parent ID,
+    # that parent will get the new free block.   if the caller didn't pass anything,
+    # no free block will be added.
+  }
 
 ##fixme:  special-case master blocks up here and quickly delete based on master_id,
@@ -279,13 +304,14 @@
   $dbh->do("DELETE FROM poolips WHERE parent_id IN ($b)", undef, (@dellist) );
 
-  # Insert a new free block in the target's parent, unless we just deleted a whole master block.
-  if ($binfo->{type} ne 'mm') {
-    my $pinfo = getBlockData($dbh, $binfo->{parent_id});
+  # Insert a new free block if needed
+  if ($createfb) {
+    my $pinfo = getBlockData($dbh, $createfb);
     my $pt = (split //, $pinfo->{type})[1];
     $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
-	$binfo->{block}, $pinfo->{city}, $pt, $binfo->{parent_id}, $pinfo->{vrf}, $binfo->{master_id});
+	$binfo->{block}, $pinfo->{city}, $pt, $createfb, $pinfo->{vrf}, $binfo->{master_id});
   }
 
 ##todo: and hey!  bonus!  we can return @dellist, or something (%cidrlist{@dellist})
+
 } # end _deleteCascade()
 
