% makescaff - make a Dalton-lab type scaffold

sw = 19;    % scaffold width
sh = 19;    % scaffold height
p = 0.3;    % pitch
lr = 1.0;   % loop radius
nh = floor((sh-2*lr)/p)+1
nv = floor((sw-2*lr)/p)+1
cx = sqrt(lr^2 - (p/2)^2);  % center of loop from end of line
lw = sw/2 - lr - cx;        % length of straight line before loop from 0,0
lv = sh/2 - lr - cx;
tstart = asin(p/(2*lr));
tend = 2*pi - tstart;
t = tstart: (tend-tstart)/12 : tend;
%t = pi/6 : pi/6 : 2*pi - pi/6;
nt = length(t);

loopx = -lr*cos(t);
loopy = -lr*sin(t);
%figure(1);
%plot(loopx,loopy)
loopdx = diff(loopx);
loopdy = diff(loopy);

lwh = (nh-1)*p/2;
hx = [-lw,   lw+loopx+cx,   -lw,    -lw-loopx-cx];
hy = [-lwh, -lwh+loopy+p/2, -lwh+p, -lwh+loopy+3*p/2];
figure(1);
plot(hx,hy);

lvh = (nv-1)*p/2;
vx = [-lvh, -lvh+loopy+p/2, -lvh+p, -lvh+loopy+3*p/2];
vy = [ lv,  -lv-loopx-cx, lv-cx, lv+loopx+cx];
figure(2);
plot(vx,vy);

nah = length(hx);          % number of elements in one pattern segment
nav = length(vx);
cnth = floor(nh/2);
cntv = floor(nv/2);
bigx = -99*ones(1,(cntv*nav+cnth*nah)); %(nv+nh)*na);
bigy = -99*ones(1,(cntv*nav+cnth*nah)); %(nv+nh)*na);
size(bigx)

cnth = floor(nh/2);
for l = 0:cnth-1
    bigx(l*nah+1:(l+1)*nah) = hx;
    bigy(l*nah+1:(l+1)*nah) = hy+l*p*2;
end
figure(3)
plot(bigx, bigy)
start = cnth * nah;
for l = 0:cntv-1
    bigx(l*nav+start+1:(l+1)*nav+start) = vx+2*p*l;
    bigy(l*nav+start+1:(l+1)*nav+start) = vy;
end

figure(4)
plot(bigx, bigy);

dbigxy = [diff(bigx); diff(bigy)];
f=fopen("bigxy.gcode","w");
fprintf(f, "G90\nG91\nG1 F500\n");
fprintf(f, "G1 X%f Y%f\n", bigx(1), bigy(1));
fprintf(f, "G1 X%f Y%f\n", dbigxy);
fprintf(f, "G1 X%f Y%f\n", -bigx(end), -bigy(end));

fclose(f);
