#!/bin/bash

# constants
MAGIC=P3
WIDTH=250
HEIGHT=250
MAX=255

log() { printf >&2 "$@"; }
prn() { printf >>"$file" "$@"; }

render() {
    r_eq="${1:-0}"
    g_eq="${2:-0}"
    b_eq="${3:-0}"

    # what file to write to?
    i=1;
    while test -f "$i.ppm"; do
        i=$((i+1));
    done
    file="$i.ppm";
    log "$file"
    
    # header
    prn '%s %d %d %d\n' $MAGIC $WIDTH $HEIGHT $MAX
    
    # image
    for y in $(seq 0 $((HEIGHT - 1))); do
        log .
        for x in $(seq 0 $((WIDTH - 1))); do
            
            # update values
            r=$(((r_eq)%MAX))
            g=$(((g_eq)%MAX))
            b=$(((b_eq)%MAX))
            
            # print
            prn '%s %s %s\n' "$r" "$b" "$g"
        done
    done
}

rendergs() {
    log >&2 '(%s %s %s %s)' render "$1" "$1" "$1"; 
    render "$1" "$1" "$1";
}

#1 rendergs x
#2 rendergs y
#3 rendergs 'x&y'
#4 rendergs 'x^y'
#5 rendergs 'x|y'
#6 rendergs '(x+y)'
#7 rendergs '(x-y)'
#8 rendergs '(x*y)'
#9 rendergs '(x/(y+1))'

#10 render x y y
#11 render x y x
#12 render x 'x+r' 'x+g'
#13 render y 'x+r' 'y+g'
#14 render x 'x|r' 'y&r'
#15 render y 'y|r' 'x&r'

#16 render '(x*y)' '(r*x)' '(g/(r+1))'
#17 render '(b*g/(y-x==0?1:y-x))' '(y%((x*r)+1))' '(r|g)'

#18 render '(g+b?g+b:1)' '(r+b?r+b:1)' '(r+g?r+b:1)'
# okay, now we're getting somewhere

#19 render '(g-b?g-b:RANDOM%MAX)' '(r**2)' '(g-r|MAX)'

render '(g-b?g-b:1)' '(b-r?b-r:1)' '(g-r?g-r:1)'
