'use strict';

var codeContext = require('parse-code-context');
var isWhitespace = require('is-whitespace');
var utils = require('./utils');

function Code(str, comment) {
  str = utils.restore(str);
  var start = comment.loc.end.pos;
  var endLine = comment.loc.end.line;
  var orig = str;

  str = str.slice(start);
  var slen = str.length, idx = -1;
  var chars, lines = 0;

  var arr = str.split('\n');
  var res = {};
  for (var i = 0; i < arr.length; i++) {
    var ctx = codeContext(arr[i], endLine + i);
    if (ctx) {
      res = ctx;
      break;
    }
  }
  console.log(res)


  while (++idx < slen) {
    var ch = str[idx];
    if (idx === 0 && /^\W/.test(ch)) {
      continue;
    }
    if (ch === '\n') {
      ++lines;
      continue;
    }
    if (!isWhitespace(ch) && ch !== ')') {
      chars = idx;
      break;
    }
  }

  if (isNaN(start) || typeof chars === 'undefined') {
    return {};
  }

  start += chars;
  var code = orig.slice(start);
  var codeLine = code.split('\n').shift();
  var lineno = endLine + lines - 1;

  return {
    line: lineno,
    loc: {
      start: { line: lineno, pos: start },
      end: { line: lineno, pos: start + codeLine.length }
    },
    value: codeLine.trim(),
  };
}

/**
 * Expose `Code`
 */

module.exports = Code;

@@ -234,23 +234,22 @@
 ;%0A  var 
-endL
+l
 ine
+no
  = comme
@@ -267,158 +267,74 @@
 line
-;%0A  var orig = str;%0A%0A  str = str.slice(start);%0A  var slen = str.length, idx = -1;%0A  var chars, lines = 0;%0A%0A  var arr = str.split('%5Cn');%0A  var res = %7B%7D
+ + 1;%0A  var ctx = %7B%7D;%0A%0A  var lines = str.split('%5Cn').slice(lineno)
 ;%0A  
@@ -353,19 +353,21 @@
  0; i %3C 
-arr
+lines
 .length;
@@ -382,19 +382,19 @@
     var 
-ctx
+res
  = codeC
@@ -404,23 +404,24 @@
 ext(
-arr
+lines
 %5Bi%5D, 
-endL
+l
 ine
+no
  + i
@@ -435,305 +435,49 @@
 if (
-ctx) %7B%0A      res = ctx;%0A      break;%0A    %7D%0A  %7D%0A  console.log(res)%0A%0A%0A  while (++idx %3C slen) %7B%0A    var ch = str%5Bidx%5D;%0A    if (idx === 0 && /%5E%5CW/.test(ch)) %7B%0A      continue;%0A    %7D%0A    if (ch === '%5Cn') %7B%0A      ++lines;%0A      continue;%0A    %7D%0A    if (!isWhitespace(ch) && ch !== ')') %7B%0A      chars 
+res) %7B%0A      ctx = res;%0A      lineno +
 = i
-dx
 ;%0A  
@@ -504,220 +504,118 @@
 %0A%0A  
-if (isNaN(start) %7C%7C typeof chars === 'undefined') %7B%0A    return %7B%7D;%0A  %7D%0A%0A  start += chars;%0A  var code = orig.slice(start);%0A  var codeLine = code.split('%5Cn').shift();%0A  var lineno = endLine + lines - 1;%0A%0A  return %7B
+var val = ctx.original %7C%7C '';%0A  var pos = str.slice(start).indexOf(val) + start;%0A%0A  return %7B%0A    context: ctx,
 %0A   
@@ -674,21 +674,19 @@
 o, pos: 
-start
+pos
  %7D,%0A    
@@ -717,24 +717,17 @@
 os: 
-start + codeLine
+pos + val
 .len
@@ -754,16 +754,11 @@
 ue: 
-codeLine
+val
 .tri

refactor Code logic