#!/usr/bin/perl -w

# deaths,groupsize,95-CI mortalily% range
my @ha=(157,783,17.3,23.0);
my @h=(162,1202,11.6,15.5);
my @a=(33,147,16.0,30.1);
my @n=(108,409,22.2,31.0);

use GD;

my $mid=300;
my $th=1;
my $dim=$mid*2+$th;
my $fs=15;

$im = new GD::Image($dim,$dim);

$white = $im->colorAllocate(255,255,255);
$red = $im->colorAllocate(255,0,0);
$pink = $im->colorAllocate(255,127,127);
$black = $im->colorAllocate(0,0,0);

$im->setThickness($th);

plot_q(\@ha, 1, 1,'HCQ & Az');
plot_q(\@h, 1, 0,'HCQ only');
plot_q(\@a, 0, 1,'Az only');
plot_q(\@n, 0, 0,'No HCQ / No Az');
$im->rectangle(0,0,$dim-1,$dim-1,$black);
$im->line(0,$mid,$dim,$mid, $black);
$im->line($mid,0,$mid,$dim, $black);

binmode STDOUT;
print $im->png;

sub sqr
{
    my ($c,$r,$dx,$dy)=@_;
    my $size=$mid*$r**0.5;
    my ($x1,$y1,$x2,$y2)=(0,0,$dx*$size,$dy*$size);
    if($x2<0) { ($x1,$x2)=($x2,$x1); }
    if($y2<0) { ($y1,$y2)=($y2,$y1); }
    $im->filledRectangle($mid+$x1,$mid+$y1,$mid+$x2,$mid+$y2,$c);
}

sub line
{
    my ($c,$r,$dx,$dy)=@_;    
    my $size=$mid*$r**0.5;
    my ($x1,$y1,$x2,$y2)=(0,0,$dx*$size,$dy*$size);
    $im->line($mid+$x2,$mid+$y1,$mid+$x2,$mid+$y2,$c);
    $im->line($mid+$x1,$mid+$y2,$mid+$x2,$mid+$y2,$c);
}
	
sub plot_q
{
    my ($data,$hcq,$az)=@_;
    my ($dx,$dy)=(2*$hcq-1,2*$az-1);
    my $title='HCQ'x$hcq . ($hcq&&$az?' & ':'') . 'Az'x$az;
    $title.=' only' if($hcq!=$az);
    $title||='No HCQ / No Az';
    $title.=sprintf("\n(%d/%d=%2.1f%%)",$data->[0],$data->[1],100*$data->[0]/$data->[1]);
    sqr($white,1,$dx,$dy);
    sqr($pink,$data->[3]/100,$dx,$dy);
    sqr($red,$data->[2]/100,$dx,$dy);
    line($black,$data->[0]/$data->[1],$dx,$dy);
    $im->stringFT($black,'/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf',
		  $fs,0,
		  ($dx>0?$mid:0)+50,($dy>0?$dim-50-$fs:50),$title);

}
