#!/usr/bin/perl
use strict;
use warnings;
use Pod::Usage;
use Getopt::Long;
use File::Basename;

# main
main : {
  # options hash table
  my %h_options;

  Getopt::Long::Configure( "no_ignorecase" );
  Getopt::Long::Configure( "bundling" );

  # retrieve all options
  GetOptions (\%h_options,
	      'h|help'
	     ) or  pod2usage( -verbose => 1 , noperldoc => 1) ;
	
  # help
  pod2usage( -verbose => 1 , noperldoc => 1) if (exists $h_options{'h'});
	
  # test ARGV parameters
  pod2usage( -verbose => 2 , noperldoc => 1) if (@ARGV != 7);

  my $nb1 = `wc -l $ARGV[1] | cut -f1 -d " "`;
  my $nb2 = `wc -l $ARGV[3] | cut -f1 -d " "`;
  my $nb3 = `wc -l $ARGV[5] | cut -f1 -d " "`;

  my $comm12  = `comm -1 -2 $ARGV[1] $ARGV[3] | wc -l | cut -f1 -d " "`;
  my $comm13  = `comm -1 -2 $ARGV[1] $ARGV[5] | wc -l | cut -f1 -d " "`;
  my $comm23  = `comm -1 -2 $ARGV[3] $ARGV[5] | wc -l | cut -f1 -d " "`;
  my $comm123 = `comm -1 -2 $ARGV[1] $ARGV[3] | comm -1 -2 - $ARGV[5] | wc -l | cut -f1 -d " "`;

  chomp ($nb1, $nb2,$nb3, $comm12, $comm13, $comm23, $comm123);

  my $request = "http://chart.apis.google.com/chart?";
  $request   .= "cht=v&chds=a&chs=750x400&chts=000000,12,l&chds=a";
  $request   .= "&chd=t:$nb1,$nb2,$nb3,$comm12,$comm13,$comm23,$comm123";
  $request   .= "&chdl=$ARGV[0]_$nb1|$ARGV[2]_$nb2|$ARGV[4]_$nb3";
  $request   .= "&chtt=$ARGV[0]++U++$ARGV[2]+:+$comm12|";
  $request   .=       "$ARGV[0]++U++$ARGV[4]+:+$comm13|";
  $request   .=       "$ARGV[2]++U++$ARGV[4]+:+$comm23|";
  $request   .=       "$ARGV[0]++U++$ARGV[2]+++U+++$ARGV[4]+:+$comm123";

  `wget "$request" -O $ARGV[6].png`;
}

=pod

=head1 NAME

        lists2venn.pl - Build Venn diagram from 3 sorted list

=head1 DESCRIPTION

        Each file must be a one column file unix sorted (default)

=head1 SYNOPSIS

        lists2venn.pl NAME1 FILE1 NAME2 FILE2 NAME3 FILE3 OUTPUT_PREFIX

=head1 OPTIONS

        -h,--help
	
=cut
