#!/usr/bin/ruby

require('Imager');
 
var (n=512, start=1, file='ulam.png');

ARGV.getopt(
    'n=i' => \n,
    's=i' => \start,
    'f=s' => \file,
);
 
func cell(n, x, y, start) {
    y -= (n   >> 1);
    x -= (n-1 >> 1);
    var l = 2*(x.abs > y.abs ? x.abs : y.abs);
    var d = (y > x  ? (l*3 + x + y) : (l - x - y));
    (l-1)**2 + d + start - 1;
}
 
var black = %s'Imager::Color'.new('#000000');
var white = %s'Imager::Color'.new('#FFFFFF');
 
var img = %s'Imager'.new(xsize => n, ysize => n, channels => 1);
img.box(filled => 1, color => white);
 
for y=(^n), x=(^n) {
    var v = cell(n, x, y, start);
    if (v.is_prime) {
        img.setpixel(x => x, y => y, color => black);
    }
}
 
img.write(file => file);
