var fs = require('fs-extra');
var helper = require('helper');
var forEach = helper.forEach;
var ensure = helper.ensure;
var LocalPath = helper.localPath;

var Entry = require('entry');
var Metadata = require('metadata');
var Ignored = require('ignored');
var Rename = require('./set/catchRename');
var Preview = require('../../modules/preview');
var isDraft = require('../../drafts').isDraft;
var rebuildDependents = require('./rebuildDependents');

module.exports = function (blogID, path, callback){

  ensure(blogID, 'string')
    .and(path, 'string')
    .and(callback, 'function');

  // We don't know if this file used to be a draft based 
  // on its metadata. We should probably look this up?
  isDraft(blogID, path, function(err, is_draft){

    // Build a queue. This assumes each method
    // can handle folders properly. And accepts a callback
    var queue = [
      Metadata.drop.bind(this, blogID, path),
      Ignored.drop.bind(this, blogID, path),
      Rename.forDeleted.bind(this, blogID, path),
      rebuildDependents.bind(this, blogID, path),
      Entry.drop.bind(this, blogID, path),
      fs.remove.bind(this, LocalPath(blogID, path))
    ];

    if (is_draft) Preview.remove(blogID, path);

    forEach(queue, function(method, next){

      method(next);

    }, callback);
  });
};

@@ -84,16 +84,57 @@
 forEach;
+ // Order is important, don't do parallel
 %0Avar ens
@@ -796,105 +796,87 @@
  // 
-Build a queue. This assumes each method%0A    // can handle folders properly. And accepts a callbac
+ORDER IS IMPORTANT%0A    // Rebuild must happen after we remove the file from dis
 k%0A  
@@ -901,21 +901,17 @@
     
-Metadata.drop
+fs.remove
 .bin
@@ -910,32 +910,42 @@
 move.bind(this, 
+LocalPath(
 blogID, path),%0A 
@@ -941,24 +941,25 @@
 D, path)
+)
 ,%0A      
 Ignored.
@@ -950,23 +950,24 @@
 ,%0A      
-Ignored
+Metadata
 .drop.bi
@@ -1000,25 +1000,20 @@
     
-Rename.forDeleted
+Ignored.drop
 .bin
@@ -1041,33 +1041,33 @@
 ,%0A      
-rebuildDependents
+Rename.forDeleted
 .bind(th
@@ -1130,33 +1130,41 @@
 ath),%0A      
-fs.remove
+rebuildDependents
 .bind(this, 
@@ -1159,34 +1159,24 @@
 .bind(this, 
-LocalPath(
 blogID, path
@@ -1176,17 +1176,16 @@
 D, path)
-)
 %0A    %5D;%0A

Fix order of functions when a file is deleted