#!/usr/bin/perl
#< ratio.pl - 20130618 - given width and height show aspect ration
use strict;
use warnings;

sub prt($) { print shift; }

sub isdig($) {
    my $txt = shift;
    return 1 if ($txt =~ /^\d+$/);
    return 0;
}

sub show_help() {
    prt("Give image width x height, to show aspect ratio...\n");
    prt("If a target width also given with show the target sizes...\n");
    prt("Can be width x height [target], or wxh [target]\n");
    exit(0);
}

my @av = @ARGV;
my $width = 1;
my $height = 1;
my $ratio = 1;
my $targ_wid = 0;



if (@av) {
    my ($itm,@arr,$cnt,$acnt);
    $cnt = 0;
    foreach $itm (@av) {
        if ($itm =~ /^-/) {
            prt("Unknown parameter [$itm]. Showing help...\n");
            show_help();
        }
        if ($itm eq 'x') {
            # nothing to do
        } elsif ($itm =~ /x/) {
            @arr = split("x",$itm);
            $acnt = scalar @arr;
            if ($acnt == 2) {
                $width = $arr[0];
                $height = $arr[1];
                $ratio = $width / $height;
                $cnt = 2;
            } else {
                prt("Item [$itm] did NOT split  in two! Got $acnt\n");
            }
        } else {
            if (isdig($itm)) {
                if ($cnt == 0) {
                    $width = $itm;
                } elsif ($cnt == 1) {
                    $height = $itm;
                } else {
                    $targ_wid = $itm;
                }
                $cnt++;
            }
        }
    }
    $ratio = $width / $height;
    if ($targ_wid > 0) {
        my ($xwid,$yhgt);
        if ($ratio > 1) {   # width > height
            $xwid = $targ_wid; # set target width
            $yhgt = int($targ_wid / $ratio); # and calculate NEW height
	    } else {
			$xwid = int($targ_wid * $ratio); # calculate width
			$yhgt = $targ_wid; # and set target width as height
        }
        prt("Given w=$width, h=$height, ratio=$ratio target=$xwid".'x'."$yhgt\n");
    } else {
        prt("Given width=$width, and height=$height, the ratio is $ratio\n");
    }
} else {
    prt("Give image width x height, to show aspect ratio...\n");
}