#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
#

subset Int   < Number {|n| n.is_int  }
subset Uint  < Int    {|n| n >= 0    }
subset Uint8 < Int    {|n| n ~~ ^256 }

struct Pixel {
    R < Uint8,
    G < Uint8,
    B < Uint8
}

class Bitmap(width < Uint, height < Uint) {
    has data = []

    method fill(Pixel p) {
        data = (width*height -> of { Pixel(p.R, p.G, p.B) })
    }

    method setpixel(i < Uint, j < Uint, Pixel p) {

        subset WidthLimit  < Uint { |n| n ~~ ^width  }
        subset HeightLimit < Uint { |n| n ~~ ^height }

        func (w < WidthLimit, h < HeightLimit) {
            data[w*height + h] = p
        }(i, j)
    }

    method p6 {
        "P6\n#{width} #{height}\n255\n" +
            data.map {|p| [p.R, p.G, p.B].pack('C3') }.join
    }
}

var b = Bitmap(width: 125, height: 125)

for i,j in (^b.height ~X ^b.width) {
    b.setpixel(i, j, Pixel(2*i, 2*j, 255 - 2*i))
}

var file = File("palette.ppm")
var fh = file.open('>:raw')
fh.print(b.p6)
fh.close
