#!/usr/bin/perl -w
use POSIX qw(strftime);

undef $/;
my $content=<STDIN>;

my $PartName="unnamed";

if($content=~m/\(symbolDef "([^" ]*)"\s*/)
{
   $PartName=$1;
}

my @pins=();
my %pinname=();
my %pinx=();
my %piny=();
my %pinlength=();
my %pinorientation=();
my %pintype=();

my $content2=$content;

my %orientation=("Left"=>"L","Right"=>"R","Up"=>"U","Down"=>"D");

while($content2=~s/\n    \(pin (.*?)\n    \)/\n    /s)
{
  my $pin=$1;
  #print "PIN:\n***\n$1\n***\n";
  $id=$1 if($pin=~m/pinNum (\d+)/);
  push @pins,$id;
  $pinname{$id}= ($pin=~m/\(pinName \(text \(pt -?\d+ -?\d+\) "([^"]*)"/)?$1:"~";
  $pinx{$id}=$1 if($pin=~m/\(pinNum \d+\) \(pt (\-?\d+) (\-?\d+)\)/);
  $piny{$id}=$2 if($pin=~m/\(pinNum \d+\) \(pt (\-?\d+) (\-?\d+)\)/);
  $pinlength{$id}=$1 if($pin=~m/\(pinLength (\d+)\)/);
  $pinorientation{$id}=$orientation{$1} if($pin=~m/\(justify (Left|Right|Up|Down)\)/);
  
  if($content=~m/\(compPin "$id" .*? \(pinType ([^\)]*)\) \)/)
  {
    my $etype=$1;
	my %etypes=("Input"=>"I","Output"=>"O","Bidi"=>"B","Tristate"=>"T","Passive"=>"P","Unspecified"=>"U","PowerInput"=>"W","PowerOutput"=>"w","OpenCollector"=>"C","OpenEmmiter"=>"E","NotConnected"=>"N");
	$pintype{$id}="U";
	$pintype{$id}=$etypes{$etype} if(defined($etypes{$etype}));
  }
  
}

my $refDesPrefix="?"; $refDesPrefix=$1 if($content=~m/refDesPrefix "([^"]*)"/);

if($refDesPrefix=~m/^#/)
{
  print STDERR "Name Prefix $refDesPrefix starts with a #, therefore it will be 'virtual', and not output to netlost or BOM.\n";
}


my $timestamp=strftime("%d.%m.%Y %H:%M:%S",localtime);

if(!$ARGV[0])
{
  print <<EOF
EESchema-LIBRARY Version 2.3  Date: $timestamp
#encoding utf-8
#Converted by from Accel PCAD 2002 to 2006 format
EOF
  ;
}

print <<EOF
#
# $PartName
#
DEF $PartName $refDesPrefix 0 40 Y Y 1 F N
F0 "$refDesPrefix" 0 0 70 H V C CNN
F1 "$PartName" 0 100 70 H V C CNN
DRAW
EOF
;

if($content=~m/\n  \(symbolDef(.*?)\n  \)/s)
{
  my $sym=$1;
  if($sym=~m/\(line \(pt (\-?\d+) (\-?\d+)\) \(pt (\-?\d+) (\-?\d+)\) \)\s*\(line \(pt (\-?\d+) (\-?\d+)\) \(pt (\-?\d+) (\-?\d+)\) \)\s*\(line \(pt (\-?\d+) (\-?\d+)\) \(pt (\-?\d+) (\-?\d+)\) \)\s*\(line \(pt (\-?\d+) (\-?\d+)\) \(pt (\-?\d+) (\-?\d+)\) \)/s)
  {
    print "S $1 $2 $9 $10 0 1 0 N\n";
  }
  
}

foreach(@pins)
{
  print "X $pinname{$_} $_ $pinx{$_} $piny{$_} $pinlength{$_} $pinorientation{$_} 50 50 1 1 $pintype{$_} N\n";
}
print <<EOF;
ENDDRAW
ENDDEF
EOF
;

#sleep(5);
