#!/usr/bin/perl -w
use strict;

# http://www1.elfa.se/data1/wwwroot/assets/datasheets/04315305.pdf
# Hsuan Mao Technology co., part no. C3000-XXSLXB00R
my $prefix = "Hsuan_Mao_C3000";

my @table = (
  # A = total length of connector
  # B = distance between mounting holes
  # C = distance between first and last column of pins ( = (#pins/2 - 1)*2.54mm )
  # pins, A,     B,     C  [mm]
  [ 10, 32.00, 27.94, 10.16 ],
  [ 14, 37.08, 33.02, 15.24 ],
  [ 16, 39.62, 35.56, 17.78 ],
  [ 20, 44.70, 40.64, 22.86 ],
  [ 24, 49.78, 45.72, 27.94 ],
  [ 26, 52.32, 48.26, 30.48 ],
  [ 30, 57.40, 53.34, 35.56 ],
  [ 34, 62.48, 58.42, 40.64 ],
  [ 40, 70.10, 66.04, 48.26 ],
  [ 50, 82.80, 78.74, 60.96 ],
);
my $H = 8.20; # width of connector
my $W = 4.30; # width of keying slot in them middle

sub Pin($) {
  my $num = shift;
  my $x = "    0";
  if ($num%2 == 0) { $x = "10000"; }
  my $y = int(($num-1)/2) * 10000;
  if ($y == 0 ) { $y = "    0"; } # wider, to make it line up in output file
  my $flg = '';
  if ($num == 1) {
    $flg = "square";
  }

  print FH "  Pin[ $x $y  2.0mm 0.3mm 2.2mm 1.0mm  \"$num\"  \"$num\" \"$flg\"]\n";
}

sub fp($) {
  my $ix = shift;
  my $sz = $$ix[0];
  my $A = $$ix[1];
  my $B = $$ix[2];
  my $C = $$ix[3];
  my $file = "${prefix}_$sz";
  if (!open(FH, ">$file.fp")) {
    warn("Cannot open $file");
    return;
  }
  print FH "Element[\"\" \"$file\" \"X?\" \"\" 0 0 0 -15000 0 100 \"\"]\n(\n";

  my $pin;
  for ($pin = 1; $pin <= $sz; ++$pin) {
    Pin($pin);
  }
  print FH "\n";

  {
    # mounting holes
    my $up = - ( $B - $C ) / 2;
    my $dw = $up + $B;
    my $num = $sz + 1;
    print FH "\n#  Mounting holes\n";
    # M3   head diameter 5.5mm
    # M2.5 head diameter 4.3mm
    print FH "  Pin[ 5000 ${up}mm 5.5mm 0.5mm 5.7mm 2.5mm  \"$num\"  \"$num\" \"\"]\n";
    $num++;
    print FH "  Pin[ 5000 ${dw}mm 5.5mm 0.5mm 5.7mm 2.5mm  \"$num\"  \"$num\" \"\"]\n";
  }

  {
    # silk
    my $x1 = -( $H - 2.54 )/2;
    my $x2 = $x1 + $H;
    my $y1 = -($A - $C)/2;
    my $y2 = $y1 + $A;
    print FH "\n";
    print FH "  # outline\n";
    print FH "  ElementLine[ ${x1}mm ${y1}mm ${x2}mm ${y1}mm 1500 ]\n";
    print FH "  ElementLine[ ${x2}mm ${y1}mm ${x2}mm ${y2}mm 1500 ]\n";
    print FH "  ElementLine[ ${x2}mm ${y2}mm ${x1}mm ${y2}mm 1500 ]\n";
    print FH "  ElementLine[ ${x1}mm ${y2}mm ${x1}mm ${y1}mm 1500 ]\n";

    $y2 = $y1 + $A/2 + $W/2;
    $y1 = $y2 - $W;
    $x2 = $x1 + 1.5;
    print FH "  # key\n";
    print FH "  ElementLine[ ${x1}mm ${y1}mm ${x2}mm ${y1}mm 1500 ]\n";
    print FH "  ElementLine[ ${x2}mm ${y1}mm ${x2}mm ${y2}mm 1500 ]\n";
    print FH "  ElementLine[ ${x2}mm ${y2}mm ${x1}mm ${y2}mm 1500 ]\n";
  }
  print FH ")\n";
  close FH;
}

my $ix;

for $ix (@table) {
  #if (  ($$ix[0] / 2 - 1) * 2.54, != $$ix[3] ) {
    # error in table
  #}
  #if ( 2*($$ix[0] / 2) != $$ix[0] ) {
  #  print "error in table\n"
  #}
  fp($ix);
}
