var marked = require('marked'),
    utils = require('./utils');

module.exports = function (source, options) {
    var toc = {
            index: -1,
            data: '',
            headers: []
        },
        maxDepth = options.maxDepth;

    var tocMatch = source.match(/<!--( )*(toc|TOC)( )*-->/);

    if (!tocMatch) return toc;

    toc.index = tocMatch.index + tocMatch[0].length;
    toc.data = '\n';

    var tocSource = source.substring(toc.index),
        parsingIndex = toc.index,
        usedHeaders = [],
        cache = {};

    var tokens = marked.lexer(tocSource);

    for (var i = 0; i < tokens.length; i++) {
        if (tokens[i].type === 'heading') {
            var header = tokens[i];

            if (header.depth > maxDepth) continue;

            var href = utils.getHref(header.text);
            if (cache.hasOwnProperty(href)) {
                href += '-' + cache[href]++;
            } else {
                cache[href] = 1;
            }

            var tocElem = '* <a href="#' + href + '">' + header.text.replace(/\\/g, '\\\\') + '</a>\n',
                indent = utils.getIndent(usedHeaders, header.depth);

            usedHeaders.unshift({
                depth: header.depth,
                indent: indent
            });

            toc.data += indent + tocElem;

            var headerRegExp = utils.getHeaderRegExp(header.text),
                matchedHeader = source.substring(parsingIndex).match(headerRegExp),
                headerIndex = matchedHeader.index + source.substring(0, parsingIndex).length;

            toc.headers.push({ index: headerIndex, href: '\n<a name="' + href + '"></a>' });

            parsingIndex = headerIndex + matchedHeader[0].length;
        }
    }

    return toc;
};

@@ -653,17 +653,17 @@
 i%5D.type 
-=
+!
 == 'head
@@ -668,22 +668,27 @@
 ading') 
-%7B%0A    
+continue;%0A%0A
         
@@ -716,28 +716,24 @@
 %5D;%0A%0A        
-   
- 
 if (header.d
@@ -764,28 +764,24 @@
 e;%0A%0A        
-    
 var href = u
@@ -811,28 +811,24 @@
 t);%0A        
- 
-   
 if (cache.ha
@@ -845,28 +845,24 @@
 ty(href)) %7B%0A
-    
             
@@ -898,20 +898,16 @@
         
-    
 %7D else %7B
@@ -915,28 +915,24 @@
             
-  
-  
 cache%5Bhref%5D 
@@ -944,27 +944,19 @@
         
-    %7D%0A%0A    
+%7D%0A%0A
         
@@ -1055,28 +1055,24 @@
             
-   
- 
 indent = uti
@@ -1117,28 +1117,24 @@
 );%0A%0A        
-    
 usedHeaders.
@@ -1155,20 +1155,16 @@
         
-  
-  
 depth: h
@@ -1176,20 +1176,16 @@
 .depth,%0A
-    
         
@@ -1215,21 +1215,13 @@
     
-    
 %7D);%0A%0A
-    
     
@@ -1255,20 +1255,16 @@
 cElem;%0A%0A
-    
         
@@ -1330,20 +1330,16 @@
         
- 
-   
 matchedH
@@ -1398,20 +1398,16 @@
 egExp),%0A
-    
         
@@ -1493,28 +1493,24 @@
 h;%0A%0A        
-    
 toc.headers.
@@ -1583,28 +1583,24 @@
 );%0A%0A        
-  
-  
 parsingIndex
@@ -1641,26 +1641,16 @@
 length;%0A
-        %7D%0A
     %7D%0A%0A 

Refactor the code