#!/usr/bin/perl

# This is pcb_get_element_cords.pl, a script which extracts coordinates of
# elements of gEDA PCB file.
#    Copyright (C) 2010  Levente Kovacs
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;

my $pcb_name = shift;
my $pcb_file;

my %null_point;
my %coords;
my $RefDes;
my $footprint;
my $value;

my $date=localtime();

%null_point=get_null_coordinates($pcb_name);

open ($pcb_file, "<", $pcb_name) or die "Can't open pcb file.\n";

print "#This is an XY file created by pcb_elements_cords.pl\n";
print "#Created at $date\n";
print "#Format is as follows:\n";
print "#RefDes,X[mil],Y[mil],footprint_name,value\n";

while (<$pcb_file>) {
	my $line=$_;
		if ($line=~/Element\["(.*)" "(.*)" "(.*)" "(.*)" (.+) (.+) (.+) (.+) (.+) (.+) "(.*)"\]/) {
			$footprint=$2;
			$RefDes=$3;
			$value=$4;
			@coords{x}=($5-@null_point{x})/100;
			@coords{y}=(@null_point{y}-$6)/100;
			print "\"$RefDes\",@coords{x},@coords{y},\"$footprint\",\"$value\"\n";
		}
}

sub get_null_coordinates {
	my $pcb_name = shift;
	my $pcb_file;

	my %coords;
	@coords{x}=0;
	@coords{y}=0;

	unless (open ($pcb_file, "<", $pcb_name) ) {
		print STDERR "Could not open pcb file: '$pcb_name'\n";
		return %coords;
	}
	while(<$pcb_file>) {
		my $line=$_;
		if ($line=~/Element\["(.*)" "__REFPOINT__" "(.*)" "(.*)" (.+) (.+) (.+) (.+) (.+) (.+) "(.*)"\]/) {
			@coords{x}=$4;
			@coords{y}=$5;
			last;
		}
	}
	close ($pcb_file);
	return %coords;
}
