const net = require('net');
const when = require('when');
const errors = require('../errors');

module.exports = function (min = 22, max = undefined) {
  return when.promise((resolve, reject) => {
    let port = min;
    let portCheckServer = net.createServer();
    portCheckServer.maxConnections = 0;
    portCheckServer.on('error', () => {
      if (!max || port < max) {
        port = port + 1;
        portCheckServer.listen(port);
      } else {
        reject(new errors.GeneralError('Unable to find open port', 500));
      }
    });
    portCheckServer.on('listening', () => {
      const {port} = portCheckServer.address();
      portCheckServer.close(() => {
        portCheckServer = null;
        resolve(port);
      });
    });
    portCheckServer.listen(port);
  });
};

@@ -126,10 +126,9 @@
 n = 
-22
+1
 , ma
@@ -197,17 +197,22 @@
     let 
-p
+checkP
 ort = mi
@@ -348,16 +348,38 @@
       if
+ (checkPort %3C 65535 &&
  (!max %7C
@@ -380,17 +380,22 @@
 !max %7C%7C 
-p
+checkP
 ort %3C ma
@@ -396,16 +396,17 @@
 t %3C max)
+)
  %7B%0A     
@@ -412,16 +412,26 @@
     
-port = p
+checkPort = checkP
 ort 
@@ -458,33 +458,38 @@
 ckServer.listen(
-p
+checkP
 ort);%0A      %7D el
@@ -811,17 +811,22 @@
 .listen(
-p
+checkP
 ort);%0A  

stop check at 65535