
=head1 NAME

CFX5::CVFConverter - Convert a CVF file to a AVZ file using CFXViewer

=head1 SYNOPSIS

Utility functinos for converting Viewer CVF files ( setup_viewer and convert_cvf )

=cut

package CFX5::CVFConverter;

use strict;
use Exporter;

use vars qw(@ISA @EXPORT_OK);
@ISA = qw(Exporter);

@EXPORT_OK = qw(setup_viewer convert_cvf);

use CFX5::Config qw(%Config export_conf check_gui_support);
use CFX5::Commands qw(do_cmd handle_rv);
use CFX5::Output qw(:all);
use CFX5::PrintConfig;
use CFX5::System qw(assert_can_window);
use CFX5::CUEI;

CFX5::Config::read_config();

my $viewer_exe = undef;

sub setup_post {
    unless ( check_gui_support() ) {
        _error("Unable to run application on machines without GUI support");
    }
    CFX5::CUEI::export_post_conf();
}

sub setup_viewer_env {
    assert_can_window();
    export_conf(qw(ANSYS_COMMON_IMAGES_DIR));
    CFX5::PrintConfig::show_vars_by_verbosity();
}

sub setup_viewer_path {

    my $local = shift;

    my $viewerDir;

    if ($local) {
        $viewerDir = "./bin/$Config{CFX5OS}/";
    }
    else {
        $viewerDir = "$Config{CUE_VIEWER_DIR}/";
    }

    $viewer_exe = $viewerDir . $Config{CUE_VIEWER_EXE};

    CFX5::FileTests::execfile( $viewer_exe,
        "CFX-Viewer executable " . $Config{CUE_VIEWER_EXE} );
}

sub setup_viewer {

    my $local = shift;

    my @setup_list = ( \&setup_post, 
                       \&setup_viewer_env, 
                       \&setup_viewer_path,
                     );

    for my $setup (@setup_list) {
        $setup->($local);
        return 1 if error_pending();
    }

    return 0;
}

sub convert_cvf {

    return 0 unless @_;

    return 1 unless $viewer_exe;

    my @files = @_;

    my @cargs;
    push @cargs, '-c';
    push @cargs, 'avz';

    for my $file (@files) {

        my @args = @cargs;
        push @args, $file;

        my @runwith;

        my $rv = handle_rv( do_cmd( @runwith, $viewer_exe, @args ) );

        if ($rv) {
            _error("Failed to convert file $file");
            return $rv;
        }
    }

    return 0;
}

1;

