#usage "<b>Print SMD coordinates for Top and Bottom</b>\n"
       "<p>"
       "Generates two files which contain the coordinates of the "
       "Smd pads in the layout. <i>Boardname.smt</i> for the Top layer, "
       "<i>boardname.smb</i> for Bottom layer. "
       "<p>"
       "<author>Author: support@cadsoft.de</author>"

// THIS PROGRAM IS PROVIDED AS IS AND WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED

/*  SMD-coordinate.ulp erzeugt eine Datei "boardname.smt" fuer die Koordinaten
    der SMD-Pads auf der Bestueckungsseite (TOP)und eine Datei
    "boardname.smb" fuer die Koordinaten der SMD-Pads auf der
    Loetseite (BOTTOM).
    08.02.2001  alf@cadsoft.de
 */

int uval = 3;

string Version = "1.0.1";

int smdx[], smdy[];    // size of smd
int x[], y[];          // coordinate of SMD
int tb[];              // top or bottom side
int index[];
int c = 0;  // counter
string Boardname;
string fileTop;
string fileBottom;

void header(void) {
  printf("This file was generated by %s %s, exported from:\n", filename(argv[0]), Version);
  printf("%s at %s;\n", Boardname, t2string(time()));
  printf("%s;\n\n", EAGLE_SIGNATURE);
  printf("%%\n");
}


real value (int v) {
  return u2mm(v) ;
}

void  smdxy(int x, int y) {
   printf("X%06.3f Y%06.3f mm\n", value(x), value(y) );
   return;
}

void genfiles(string file) {
  sort(c, index, tb, smdx, smdy, x, y);  // sortiere top/bottom, groesse, coord.

  for (int n = 0; n < c; n++) {
    if (tb[index[n]]) {
      smdxy(x[index[n]], y[index[n]]);
      }
    else {
      output(fileTop, "at") {
        smdxy(x[index[n]], y[index[n]]);
        }
      }
    }
  }

void  trailer(void) { printf("end\n"); }

// main

if (board) {
 board(B) {
  Boardname = B.name;

  fileTop = dlgFileSave("Save SMD coordinate for Top side", filesetext(B.name, ".smt"), "*.smt");
  if (fileTop == "") exit(0);

  fileBottom = dlgFileSave("Save SMD coordinate for Bottom side", filesetext(B.name, ".smb"), "*.smb");
  if (fileBottom == "") exit(0);

  output(fileTop, "wt") { header(); printf("Top\n"); }
  output(fileBottom, "wt") { header(); printf("Bottom\n");
    B.elements(E) {
      E.package.contacts(C) {
        if (C.smd) {

           // collect SMD-Pads
           smdx[c] = C.smd.dx;
           smdy[c] = C.smd.dy;
           x[c] = C.smd.x;
           y[c] = C.smd.y;
           tb[c] = E.mirror;
           c++;
        }
      }
    }

  genfiles(B.name);
  trailer();
  output(fileTop, "at") { trailer(); }
  }
 }
}

else {
   dlgMessageBox("\n    Start this ULP in a Board    \n");
   exit (0);
}
