# CALL: perl svg_from_pedfile.pl PEDFILE.ped
# returns PEDFILE.ped.FAM_ID.svg

use strict;
use 5.10.0;
use LWP::UserAgent ();
my $drawped_url="https://www.genecascade.org/ped-cgi/pedigree.cgi";
my $ua = LWP::UserAgent->new(timeout => 20);
# $ua->env_proxy; # enable if required

my $pedfile=shift;
open (IN,'<',$pedfile) or die ("Cannot open ped file '$pedfile': $!");
my %pedigrees=();
while (<IN>) {
	chomp;
	my ($fam,$id,$fid,$mid,$sex,$aff)=split /\s+/;
	$pedigrees{$fam}.=join ("\t",$id,$fid,$mid,$sex,$aff)."\n" if $id;
}
close IN;

foreach my $fam (keys %pedigrees) {
	my $outfile=$pedfile.'.'.$fam.'.svg';
	say "Family $fam -> $outfile";
	my $response = $ua->post($drawped_url,{svg=>1, pedigree => $pedigrees{$fam}, family_id => $fam});
	if ($response->is_success) {
		$_=$response->decoded_content;
		die ("ERROR: ".$_) unless (/^<svg/);
		open (OUT,'>',$outfile) or die ($!);
		print OUT $_;
		close OUT;
		say "$outfile written.";
	}
	else {
		die $response->status_line;
	}
}
