//title: Sheet I-Cord Cast-On (javascript with knitout module)
// Casts on a sheet by knitting a small tube, leaving one stitch on the bed each time; slow but fancy.

//include knitout module:
const knitout = require('knitout'); //include knitout module
const K = new knitout.Writer({ carriers:['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] });
K.addHeader('Machine', 'SWGN2');

//Parameters:
let min = 1; //needle number of left edge
let max = 20; //needle number of right edge
let carrier = "3"; //carrier name
let cordWidth = 4; //cord width

//Bring in carrier:
K.inhook(carrier);
//Set stitch table entry for cast-on:
K.stitchNumber(101);

//On SWGN2 machines, carriers start on the right,
//so will start by making a closed tube bind-off for the cord on the right.

//All-needle closed-tube cast-on, with carrier ending on the left:
K.rack(-0.75);
for (let n = max; n >= max - cordWidth; n -= 1) {
	K.tuck("-", 'f' + n, carrier);
	K.tuck("-", 'b' + n, carrier);
}
K.rack(0);

//Set stitch table entry for knitting:
K.stitchNumber(105);

//Knit a small tube, leaving an extra stitch to the right and moving the stitches every course:
//Start first course of the tube:
for (let n = max - cordWidth; n <= max; n += 1) {
	K.knit("+", 'f' + n, carrier);
}
//send out yarn inserting hook; it is no longer needed to hold the yarn in place:
K.releasehook(carrier);
//Middle of tube:
for (let tubeMax = max; tubeMax >= min; tubeMax -= 1) {
	for (let n = tubeMax; n >= tubeMax - cordWidth; n -= 1) {
		K.knit("-", 'b' + n, carrier);
	}
	K.miss("-", 'b' + (tubeMax-cordWidth-1), carrier);
	for (let n = tubeMax - cordWidth; n <= tubeMax; n += 1) {
		K.xfer('f' + n, 'bs' + n);
	}
	K.rack(-1);
	for (let n = tubeMax - cordWidth; n <= tubeMax; n += 1) {
		K.xfer('bs' + n, 'f' + (n-1));
	}
	K.rack(0);
	for (let n = tubeMax - cordWidth; n <= tubeMax; n += 1) {
		K.knit("+", 'f' + (n-1), carrier);
	}
	K.tuck("+", 'f' + tubeMax, carrier);
	for (let n = tubeMax - cordWidth; n <= tubeMax; n += 1) {
		K.xfer('b' + n, 'fs' + n);
	}
	K.rack(1);
	for (let n = tubeMax - cordWidth; n <= tubeMax; n += 1) {
		K.xfer('fs' + n, 'b' + (n-1));
	}
	K.rack(0);
}
//Finish last course of tube (and get carrier to the left):
for (let n = min - 1; n >= min - cordWidth - 1; n -= 1) {
	K.knit("-", 'b' + n, carrier);
}

//Closed bind-off on the tube:
for (let n = min - cordWidth - 1; n <= min - 1; n += 1) {
	K.xfer('b' + n, 'f' + n);
	K.knit("+", 'f' + n, carrier);
	K.rack(-1);
	K.xfer('f' + n, 'b' + (n+1));
	K.knit("+", 'b' + (n+1), carrier);
	K.rack(0);
}
K.xfer('b' + min, 'f' + min);

//Knit regular course to get carrier to the right:
for (let n = min; n <= max; n += 1) {
	K.knit("+", 'f' + n, carrier);
}

//...now can knit on [min,max].

K.write('sheet-i-cord-cast-on.swgn2.k');
