use strict;
use Math::Trig;

my $in_osm = $ARGV[0];#osm地圖檔名
my $O_Lon = $ARGV[1];#目標地經度
my $O_Lat = $ARGV[2];#目標地緯度
my $in_net = $ARGV[3];#net檔名
my $diffDis = $ARGV[4];#比對最大距離
my $T_dis;#暫存離目標地最近的node距離
my $dis = 2*pi*12742000;#用地球圓周長作為預設距離
my @nodeID;#估計出所有點的node id
my @nodeDIS;#估計出所有點的距離
my $wayID;#估計出最佳點的way id
my $osm;#osm文件的內容
my $net;#net FILE
my @waylist;#可用的way list
my @edgelist;#可用的edge list
my @nodelist;#可用的nodelist

#開啟地圖檔
open FILE, "$in_osm" or die "Loading .osm error!";
while (<FILE>){
	#存下osm的所有內容
	$osm .=$_;
	#取出包含node id的行
	if($_ =~ /node id="([0-9]+)"\slat="([\+\-0-9.]+)"\slon="([\+\-0-9.]+)"/){
		#計算出原點與地圖檔中node的距離
		$T_dis = &caldis($O_Lat,$O_Lon,$2,$3);
		#距離差異內存入list
		if ($T_dis<$diffDis) {
			push @nodeID, $1;
			push @nodeDIS, $T_dis;
		}
	}
}
close FILE;

#依據距離小到大排序node list
my @idx = sort {$nodeDIS[$a] <=> $nodeDIS[$b]} 0..$#nodeDIS;
@nodeID = @nodeID[@idx];
@nodeDIS = @nodeDIS[@idx];

#重複搜尋直到找到node id對應的way id或是nodeID都不適用
while(@nodeID){
	#找出way id內<nd ref部份包含相同的node id，並且跳出迴圈
	if($osm =~ /<way id='?"?([0-9]+)'?"?>[ndref0-9\s\n\t=<>"\/]*<nd ref="(@nodeID[$#nodeID])"\/>/){
		#print "NodeID: $2\n";
		#print "WayID: $1\n";
		push @waylist, $1;
		push @nodelist, $2;
	}
	pop @nodeID;
}

#存入net file資訊
open my $fh, "$in_net" or die "Loading .net error!";
local $/;
$net = <$fh>;
close FILE;

#這部份將wayid轉為edgeid
while(@waylist){
	#取得node id為起始點的edge id
	if($net =~ /edge id=\"([\+\-]?$waylist[$#waylist]\s?[#_0-9]*)\"\sfrom=\"[cluster_0-9]*(@nodelist[$#nodelist])[0-9_]*\"/){
		#print "$1 $2\n";
		push @edgelist, $1;
	}
	#取得node id為終點的edge id
	if($net =~ /edge id=\"([\+\-]?$waylist[$#waylist]\s?[#_0-9]*)\"\s\S*\sto=\"[cluster_0-9]*(@nodelist[$#nodelist])[0-9_]*\"/){
		#print "$1 $2\n";
		push @edgelist, $1;
	}
		pop @waylist;
		pop @nodelist
}

print "@edgelist[0]";

#利用公式計算兩點經緯度的距離
sub caldis{
	my $Lat1 = @_[0];
	my $Lon1 = @_[1];
	my $Lat2 = @_[2];
	my $Lon2 = @_[3];
	my $radLat1 = deg2rad($Lat1);
	my $radLat2 = deg2rad($Lat2);
	my $a = $radLat1-$radLat2;
	my $b = deg2rad($Lon1) - deg2rad($Lon2);
	my $s = 2*asin(sqrt(sin($a*0.5)**2 + cos($radLat1)*cos($radLat2)*sin($b*0.5)**2));
	$s = $s*6378137;
	return $s;
}
