#!/usr/bin/env perl

## Real world metal-film resistor at RF equivalent circuit
## Experimental. This might not be accurate

## This file Copyright 2000 <contact@gbppr.org> under the GPL
## NO WARRANTY. Please send bug reports / patches / reports.

use Math::Complex;

sub Print {
print  "\33[H\33[J".
       "  Real world metal-film resistor at RF equivalent circuit   \n\n".
       "  L = lead inductance, C = stray shunt capacitance, R = resistance\n".
       "                                                            \n".
       "            L                 R                L            \n\n";
printf "          +j %.2f ohms      %.3f Kohms   +j %.2f ohms\n\n", $xl, $res/1000, $xl;
print  "  >----+--()()()----------/\\/\\/\\----------()()()--+----->\n".
       "       |                                          |         \n".
       "       |                                          |         \n".
       "       |                     C                    |         \n".
       "       |                                          |         \n".
       "       +--------------------| |-------------------+         \n\n";
printf "                        -j %.3f ohms                        \n\n", $xc;
}

sub Get {
undef $_; undef $val; undef $rad;
while (!m/^([0-9.]+)(mm|MM|cm|CM|in|IN+)$/) {
	print "\nmm = millimeters\n".
	       "cm = centimeters\n".
	       "in = inches\n\n".
	       "Enter a resistor lead $VAL  [value][mm,cm,in]: ";
	chomp($_ = <STDIN>);
}

if (m/^([0-9.]+)(mm|MM|cm|CM|in|IN+)$/) {
        $val = $1;
        $unit = $2;
}
if ($unit =~ /cm/i) {
        $rad = $val / 2.54;
}
elsif ($unit =~ /mm/i) {
	$rad = $val / 25.4;
}
elsif ($unit =~ /in/i)  {
	$rad = $val;
 }
}


&Print;

&Get($VAL = "RADIUS");
$radi = $rad;

&Get($VAL = "LENGTH");
$len = $rad;

print "\n";

while (!$c) {
	print "Enter total stray shunt capacitance (C in pF): ";
	chomp($c = <STDIN>);
	$c =~ tr/0-9.//csd;
}

print "\n";

while (!$res) {
	print "Enter resistor value (R in ohms): ";
	chomp($res = <STDIN>);
	$res =~ tr/0-9.//csd;
}

print "\n";

while (!$frq) {
	print "Enter frequency of circuit (in MHz): ";
	chomp($frq = <STDIN>);
	$frq =~ tr/0-9.//csd;
}

$ind = (0.00508 * $len) * ((log ((2 * $len) / $radi)) - 0.75);
$xl = 2 * pi * ($frq * 1000000) * ($ind / 1000000);

if ($xl > ($res * 0.01)) {
    printf  "\n\n\tResistor lead inductance is too high for this circuit to".
            "\n\toperate properly at %s MHz (+j%.6f ohms)\n\n", $frq, $xl;
	    
    exit 1;
}

$xc = 1 / (2 * pi * ($frq * 1000000) * ($c / 1000000000000));
$z = ($res * $xc) / (sqrt (($res ** 2) + ($xc ** 2)));

&Print;

printf "\n  Each resistor lead inductace : %.6f uH\n".
       "                               : %.6f nH\n".
       "          Frequency of circuit : %s MHz\n", $ind, $ind * 1000, $frq;
printf "     Actual resistor impedance : %.3f ohms\n\n".
       " Lead inductance is insignificant in this circuit.\n\n", $z;
