#!/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 != 4);

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

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

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

  $ARGV[0] =~ s/\..*$//;
  $ARGV[1] =~ s/\..*$//;
  $ARGV[2] =~ s/\..*$//;

  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=".basename($ARGV[0])."_$nb1|".basename($ARGV[1])."_$nb2|".basename($ARGV[2])."_$nb3";
  $request   .= "&chtt=".basename($ARGV[0])."++U++".basename($ARGV[1])."+:+$comm12|";
  $request   .=          basename($ARGV[0])."++U++".basename($ARGV[2])."+:+$comm13|";
  $request   .=          basename($ARGV[1])."++U++".basename($ARGV[2])."+:+$comm23|";
  $request   .=          basename($ARGV[0])."++U++".basename($ARGV[1])."+++U+++".basename($ARGV[2])."+:+$comm123";

  `wget "$request" -O $ARGV[3].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 FILE1 FILE2 FILE3 OUTPUT_PREFIX

=head1 OPTIONS

        -h,--help
	
=cut
