package SmilesScripts::OPSIN;

use strict;
use warnings;

use IPC::Open3;
use Symbol 'gensym';

sub new
{
    my( $class ) = @_;

    my $CHLD_ERR = gensym;
    my $pid = open3( my $CHLD_IN, my $CHLD_OUT, $CHLD_ERR, 'java -jar /usr/share/java/opsin.jar' );

    return bless { pid => $pid, stdin => $CHLD_IN, stdout => $CHLD_OUT }, $class;
}

sub IUPAC_to_SMILES
{
    my( $self, $IUPAC ) = @_;

    my $stdin = $self->{stdin};
    my $stdout = $self->{stdout};

    $IUPAC .= "\n" unless $IUPAC =~ /\n$/;

    local $\ = undef;
    print $stdin $IUPAC;
    my $SMILES = <$stdout>;
    $SMILES =~ s/\n$//;
    return $SMILES ? $SMILES : undef;
}

sub DESTROY
{
    my( $self ) = @_;
    my $stdin = $self->{stdin};
    close $stdin;
    waitpid $self->{pid}, 0;
}

1;
