#!/usr/bin/env perl
# Find a value at given point by linear interpolation of 
# pairs of (x,y) data points
# Rok Zitko, rok.zitko@ijs.is, March 2009

use warnings;
use strict;

if (@ARGV != 2) {
  print "Determines f(value).\n";
  die "Usage: valueatlin <filename> <value>\n";
}

my $fn = shift;
my $value = shift;

open (F, "<$fn") or die "Can't open $fn, stopped";

my ($xprev, $yprev);

while (<F>) {
    if (/^#/) {
	next;
    }
    
    chomp;
    my @v = split(' ', $_);
    if (@v < 2) {
	die "Error: at least two numbers per line are expected, stopped";
    }
    my $x = $v[0];
    my $y = $v[1];
    
    if (!defined($xprev)) {
	$xprev = $x;
	$yprev = $y;
	next;
    }
    
    if ($xprev <= $value && $value <= $x) {
	# Value is bracketed
	my $slope = ($yprev-$y)/($xprev-$x);
	my $dy = ($value-$xprev)*$slope;
	my $solution = $yprev + $dy;
	print "$solution\n";
	exit(1);
    }
    
    $xprev = $x;
    $yprev = $y;
}

die "No solution.\n";
