$(document).ready(function() {
  var $pre = $('pre');
  var log = function(m) {
    $pre.append(m).append("\r\n");
  }
  var get = // adapted from lodash.get, with thanks
    function(o,p,v) {
      var i=0, l=p.length;
      while(o && i<l) { o = o[p[i++]]; }
      return o ? o : v;
    }
  log("Loading database");
  var createOwnerPico = function(callback){
    $.getJSON("/api/new-pico", function(d) {
      if (d && d.id) {
        log("Pico created: "+d.id);
        log("Creating owner channel");
        $.getJSON("/api/pico/"+d.id+"/new-channel",
            {"name": "main", "type": "secret"},
            function(c){
              if (c && c.id) {
                log("Owner Pico ECI: "+c.id);
              } else {
                log("*Problem creating owner Pico channel");
              }
            }
        );
      } else {
        log("*Problem creating owner Pico");
      }
    });
  };
  var installRuleset = function(rid,callback){
    log("Getting "+rid);
    $.get("https://raw.githubusercontent.com/Picolab/node-pico-engine/master/krl/"+rid+".krl",function(k){
      if (k && k.length > 0) {
        log(rid+".krl length: "+k.length);
        log("Registering "+rid);
        $.getJSON("/api/ruleset/register",{"src":k},function(r){
          if (r && r.ok) {
            log(rid+" registered");
          } else {
            log("*Problem registering "+rid);
          }
        });
      } else {
        log("*Problem getting "+rid);
      }
    },"text");
  };
$.getJSON("/api/db-dump", function(db_dump){
  log("Database loaded");
  if (!db_dump.pico) {
    log("Creating owner Pico");
    createOwnerPico();
  } else {
    log("Database has an owner Pico");
  }
  if (!db_dump.rulesets) {
    log("Registering rulesets");
    installRuleset("io.picolabs.pico");
    installRuleset("io.picolabs.visual_params");
  } else {
    log("Database has rulesets");
  }
});
});

@@ -288,35 +288,8 @@
   %7D%0A
-  log(%22Loading database%22);%0A
   va
@@ -1463,16 +1463,45 @@
 );%0A  %7D;%0A
+  log(%22Loading database%22);%0A  
 $.getJSO
@@ -1537,16 +1537,18 @@
 _dump)%7B%0A
+  
   log(%22D
@@ -1565,23 +1565,24 @@
 aded%22);%0A
+  
   if (
-!
 db_dump.
@@ -1585,24 +1585,80 @@
 ump.pico) %7B%0A
+      log(%22Database has an owner Pico%22);%0A    %7D else %7B%0A  
     log(%22Cre
@@ -1673,24 +1673,26 @@
 ner Pico%22);%0A
+  
     createOw
@@ -1700,33 +1700,58 @@
 erPico();%0A  
-%7D else
+  %7D%0A    if (db_dump.rulesets)
  %7B%0A
+  
     log(%22Dat
@@ -1764,56 +1764,35 @@
 has 
-an owner Pico%22);%0A  %7D%0A  if (!db_dump.rulesets)
+rulesets%22);%0A    %7D else
  %7B%0A
+  
     
@@ -1816,24 +1816,26 @@
 rulesets%22);%0A
+  
     installR
@@ -1862,24 +1862,26 @@
 pico%22);%0A    
+  
 installRules
@@ -1919,55 +1919,14 @@
 ;%0A  
-%7D else %7B%0A    log(%22Database has rulesets%22);
+  %7D
 %0A  
-%7D%0A
 %7D);%0A

rearrange code