File: netlist.c

package info (click to toggle)
xcircuit 2.0a6-3
  • links: PTS
  • area: main
  • in suites: slink
  • size: 1,960 kB
  • ctags: 3,202
  • sloc: ansic: 30,529; makefile: 51; sh: 2
file content (1274 lines) | stat: -rw-r--r-- 39,371 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
/*-------------------------------------------------------------------------*/
/* netlist.c --- xcircuit routines specific to the Pcb netlist generation  */
/*		 system							   */
/*-------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------*/
/*  Written by Chow Seong Hwai, 3/20/98 Leeds University, U.K.	   	   */
/*  Modifications by Tim Edwards, April-May 1998			   */
/*-------------------------------------------------------------------------*/

#include <stdio.h>
#include <string.h>
#include <malloc.h>

#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>

/*-------------------------------------------------------------------------*/
/* Local includes							   */
/*-------------------------------------------------------------------------*/

#include "cursors.h"
#include "colordefs.h"
#include "xcircuit.h"

/*-------------------------------------------------------------------------*/
/* Declaration of routines and their parameters				   */
/*-------------------------------------------------------------------------*/

void gennet(char *mode, char *suffix);
void gennetlist(objectptr cschem);
void genpinlist(objectptr cschem);
void gencalllist(objectptr cschem);
int onsegment(XPoint *af, XPoint *at, XPoint *bf, XPoint *bt, objectptr cschem);
int resolved(struct Netlist *netlist, polyptr poly);
void changenet(struct Netlist *netlist, int orignet, int newnet);
void linknet(struct Netlist **nethead, polyptr poly, int netid);
int whichnet(struct Netlist *netlist, XPoint *pinpoint);
void makepin(struct Pinlist **pinhead, labelptr pin, int netid);
void makecall(struct Calllist **callhead, objectptr callobj, labelptr callpin,
	int callid, int netid);
void writepcb(objectptr cschem, struct Calllist *cfrom, FILE *fp);
void writenet(objectptr cschem, char *mode, char *suffix);
void freenets(objectptr cschem);
void freeglobals();
char *nettopin(int netid, objectptr cschem, char *prefix);

extern char _STR[150];
extern Clientdata areastruct;

struct Pinlist *globallist;

int netindex;	/* count for labeling nets in the flattened netlist */
int devindex;   /* similarly for labeling devices		    */
int subindex;   /* similarly for labeling spice subcircuits	    */

/*-------------------------------------------------------------------------*/
#ifdef SCHEMA

/*-------------------------------------------------------------------------*/
/* gennet(): Generate netlist structures				   */
/*									   */
/* Result is the creation of three linked lists inside each object in the  */
/* circuit hierarchy:							   */
/*									   */
/*    1) the netlist:  assigns a net number to each polygon on the object  */
/*	 	       page.						   */
/*    2) the pinlist:  a list of every pin label in the object with their  */
/*		       net numbers.					   */
/*    3) the calllist: a list of calls made from the object to all sub-	   */
/*		       circuits.  Each link contains one parameter to one  */
/*		       call which can be used to link the net in the top   */
/*		       level to its corresponding net in the subcircuit	   */
/*		       (see structure definitions in xcircuit.h).	   */
/*-------------------------------------------------------------------------*/

void gennet(char *mode, char *suffix)
{
   gennetlist(objectdata);
   gencalllist(objectdata);
   genpinlist(objectdata);
   
   if (!strcmp(mode, "pcb")) {
      if (objectdata->pinlist != NULL) {
         writenet(objectdata, mode, suffix);
      }
   }
   else if (objectdata->netlist != NULL) {
      writenet(objectdata, mode, suffix);
   }
   else
      Wprintf("Error generating netlist: no file written");

   freenets(objectdata);
   freeglobals();
}

/*-------------------------------------------------------------------------*/
/* Resolve net 								   */
/*-------------------------------------------------------------------------*/

void gennetlist(objectptr cschem)
{
   genericptr *cgen, *tgen;
   polyptr cpoly, tpoly;
   objinstptr cobj;
   XPoint *tpt, *tpt2, *endpt, *endpt2;
   int orignet, curnet, nextnet = 1;
   struct Netlist *netptr;
   struct Netlist **nethead = &(cschem->netlist);
	
   for (cgen = cschem->plist; cgen < cschem->plist + cschem->parts; cgen++) {
      if ((*cgen)->type == POLYGON) {
 	 cpoly = TOPOLY(cgen);

	 if ((curnet = resolved(*nethead, cpoly)) == 0) {
	    curnet = nextnet;
	    linknet(nethead, cpoly, curnet);		
	    nextnet++;
	 }

	 /* Check for attachment of this segment to every other */
	 /* include the unlikely case that a net is made with a closed curve */

	 for (endpt = cpoly->points; endpt < cpoly->points
		+ cpoly->number; endpt++) {

	    endpt2 = endpt + 1;
	    if (endpt == cpoly->points + cpoly->number - 1) {
		if (!(cpoly->style & UNCLOSED))
	           endpt2 = cpoly->points;
	        else continue;
	    }

	    for (tgen = cgen + 1; tgen < cschem->plist + cschem->parts; tgen++) {
   	       if ((*tgen)->type == POLYGON) {
		  tpoly = TOPOLY(tgen);

	     	  /* check segments */

	     	  for (tpt = tpoly->points; tpt < tpoly->points
			+ tpoly->number; tpt++) {

		     tpt2 = tpt + 1;
	    	     if (tpt == tpoly->points + tpoly->number - 1) {
			if (!(tpoly->style & UNCLOSED)) 
	       	  	   tpt2 = tpoly->points;
	    	        else continue;
		     }

	     	     if (onsegment(endpt, endpt2, tpt, tpt2, cschem)) {
	     		if (orignet = resolved(*nethead, tpoly)) {
			   changenet(*nethead, orignet, curnet);
	     		}
	     		else {
			   linknet(nethead, tpoly, curnet);
	     		}
			/* found connected polygon; get the next one */
	     		break;
	     	     }
	     	  }
	       }
	    }
	 }
      }
   }
}

/*-------------------------------------------------------------------------*/
/* Check whether given polygon is already resolved into netlist 	   */
/* Return the net id if already resolved, 0 otherwise	        	   */
/*-------------------------------------------------------------------------*/

int resolved(struct Netlist *netlist, polyptr poly)
{
   for (netlist; netlist != NULL; netlist = netlist->next) {
      if (netlist->poly == poly) {
 	 return (netlist->netid);
      }
   }
   return 0;
}

/*-------------------------------------------------------------------------*/
/* Insert given polygon at top of netlist 				   */
/* Associate polygon with given net id    				   */ 
/*-------------------------------------------------------------------------*/

void linknet(struct Netlist **nethead, polyptr poly, int netid)
{
   struct Netlist *netptr = NULL;
	
   netptr = (struct Netlist *) malloc(sizeof(struct Netlist));
   if (netptr != NULL) {
      netptr->poly = poly;
      netptr->netid = netid;

      netptr->next = *nethead;
      *nethead = netptr;
   }
   else {
      fprintf(stderr, "Not enough memory\n");  /* debug printing */
   }
}

/*-------------------------------------------------------------------------*/

long zsign(long a, long b)
{
   if (a > b) return 1;
   else if (a < b) return -1;
   else return 0; 
}

/*-------------------------------------------------------------------------*/
/* Check whether two line segments attach to or cross each other	   */
/* Return 1 if attached, 0 otherwise					   */ 
/*-------------------------------------------------------------------------*/

#define ONDIST 2  /* "slack" in algorithm for almost-touching lines */

int onsegment(XPoint *af, XPoint *at, XPoint *bf, XPoint *bt, objectptr cschem)
{
   long w, v;
   genericptr *cgen;
   objinstptr cobj;
   long ddist;

   /* check if any endpoint connects to the other segment */

   w = finddist(af, at, bf);
   if (abs(w) <= ONDIST) return 1;
   w = finddist(af, at, bt);
   if (abs(w) <= ONDIST) return 1;
   w = finddist(bf, bt, af);
   if (abs(w) <= ONDIST) return 1;
   w = finddist(bf, bt, at);
   if (abs(w) <= ONDIST) return 1;

   v = zsign((at->x - bf->x)*(bt->y - bf->y), (at->y - bf->y)*(bt->x - bf->x))
     + zsign((bt->x - at->x)*(af->y - at->y), (bt->y - at->y)*(af->x - at->x))
     + zsign((af->x - bt->x)*(bf->y - bt->y), (af->y - bt->y)*(bf->x - bt->x))
     + zsign((bf->x - af->x)*(at->y - af->y), (bf->y - af->y)*(at->x - af->x));

   if (abs(v) == 4) {

      /* lines cross:  find crossing point and look for "dot" at that point; */
      /* look for any objects with name *dot* (* for wildcard) attaching     */
      /* to both line segments (using finddist())			     */

      for (cgen = cschem->plist; cgen < cschem->plist + cschem->parts; cgen++) {
         if ((*cgen)->type == OBJECT) {
	    cobj = TOOBJINST(cgen);
	    if (strstr(cobj->thisobject->name, "dot") != NULL) {
	       ddist = finddist(af, at, &(cobj->position)) +
			  finddist(bf, bt, &(cobj->position));
	       if (abs(ddist) <= ONDIST) {
		  /* lines are joined with a dot */
		  return 1;
	       }
            }
         }
      }
   }
	
   return 0;
}

/*--------------------------------------------------------------------------*/
/* Traverse along netlist and change nets of a given id to another given id */
/* Parameters: netlist - pointer to top of netlist                          */
/*	       orignet - original id to be changed			    */
/*	       newnet - new id to be changed to				    */	
/*--------------------------------------------------------------------------*/

void changenet(struct Netlist *netlist, int orignet, int newnet) 
{
   for (; netlist != NULL; netlist = netlist->next) {
      if (netlist->netid == orignet) {
	 netlist->netid = newnet;
      }
   }
}

/*--------------------------------------------------------------------------*/
/* Same as above, for the call list					    */
/* (changes net for both netlist and calllist)				    */
/*--------------------------------------------------------------------------*/

void changecall(objectptr cschem, int orignet, int newnet) 
{
   struct Calllist *calllist = cschem->calllist;
   struct Netlist *netlist = cschem->netlist;

   for (; calllist != NULL; calllist = calllist->next) {
      if (calllist->netid == orignet) {
	 calllist->netid = newnet;
      }
   }

   changenet(netlist, orignet, newnet);
}

/*--------------------------------------------------------------------------*/
/* Same as above, for the pin list					    */
/* (changes net for all of netlist, calllist, and pinlist		    */
/*--------------------------------------------------------------------------*/

void changepin(objectptr cschem, int orignet, int newnet) 
{
   struct Pinlist *pinlist = cschem->pinlist;
   struct Netlist *netlist = cschem->netlist;

   for (; pinlist != NULL; pinlist = pinlist->next) {
      if (pinlist->netid == orignet) {
	 pinlist->netid = newnet;
      }
   }
   changecall(cschem, orignet, newnet);
}

/*-------------------------------------------------------------------------*/
/* Remove a call from the call list					   */
/*-------------------------------------------------------------------------*/

void removecall(objectptr cschem, struct Calllist *callstart)
{
   struct Calllist **replace;
   struct Calllist *seeklist, *savelist;
   int callid;

   seeklist = cschem->calllist;
   if (seeklist == callstart) {
      replace = &(cschem->calllist);
   }
   else {
      while (seeklist->next != callstart) seeklist = seeklist->next;
      replace = &(seeklist->next);
   }

   seeklist = callstart;
   callid = seeklist->callno;

   while (seeklist->callno == callid) {
      savelist = seeklist;
      seeklist = seeklist->next;
      free (savelist);
      if (seeklist == NULL) break;
   }
   *replace = seeklist;
}

/*-------------------------------------------------------------------------*/
/* Resolve pins recursively						   */
/*-------------------------------------------------------------------------*/

void genpinlist(objectptr cschem)
{
   genericptr *pgen;
   objinstptr pobj;
   objectptr callobj;
   labelptr plabel;
   int netid, globals, callid, globnet, net1, net2;
   struct Pinlist **pinhead = &(cschem->pinlist), *ptst, *gtst;
   struct Netlist *netlist = cschem->netlist;
   struct Calllist *calllist = cschem->calllist, *savelist, *seeklist;
	
   if (netlist == NULL) return;

   /* recursively execute genpinlist() on all calls in the calllist */

   while (calllist != NULL) {
      callid = calllist->callno;
      if (calllist->callobj->pinlist == NULL)
	 genpinlist(calllist->callobj);

      savelist = calllist;
      while (calllist->callno == callid) {

	 /* 1) resolve connecting nets in "jumper"-type objects.  */
	 /*    Ignore unconnected pins (which may appear in 	  */
	 /*    "fundamental" low-level objects.			  */

	 net1 = pintonet(calllist->pin, calllist->callobj);
         if (net1 != 0) {
	    seeklist = calllist->next;
	    while (seeklist != NULL && seeklist->callno == callid) {
	       net2 = pintonet(seeklist->pin, calllist->callobj);
	       if (net2 == net1) {
	          printf("Combined nets %d and %d in %s call to %s\n",
		       seeklist->netid, calllist->netid, cschem->name,
		       calllist->callobj->name);

	          /* combine the two nets on the level above. 	  */
	          /* make the lowest-numbered net the remaining one. */

	          if (calllist->netid < seeklist->netid)
	             changecall(cschem, seeklist->netid, calllist->netid);
	          else
	             changecall(cschem, calllist->netid, seeklist->netid);
	       }
	       seeklist = seeklist->next;
	    }
	 }
	 calllist = calllist->next;
	 if (calllist == NULL) break;
      }

      calllist = savelist;
      while (calllist->callno == callid) {

         /* 2) resolve global nets upward from the hierchy bottom */

         if ((globnet = pintonet(calllist->pin, calllist->callobj)) < 0) {
	    printf("Changed net %d to global %d in %s\n",
		 calllist->netid, globnet, cschem->name);

	    /* change all references in local netlist and calllist */
	    changecall(cschem, calllist->netid, globnet);
	    
	    calllist->netid = globnet;
	 }
	 calllist = calllist->next;
	 if (calllist == NULL) break;
      }

      /* if the called object has no calls itself (contains only nets), */
      /* then remove the call now that the nets have been resolved.	*/

      if (savelist->callobj->calllist == NULL) {
	 if (savelist->callobj->schemtype != FUNDAMENTAL) {
	    printf("Removing call to %s in %s\n", 
	          savelist->callobj->name, cschem->name);
            removecall(cschem, savelist);
	 }
      }
   }

   /* Now for each pin-label in the object, update the pinlist. */

   for (pgen = cschem->plist; pgen < cschem->plist + cschem->parts; pgen++) {
      if ((*pgen)->type == LABEL) {
	 plabel = TOLABEL(pgen);
	 if (plabel->pin) {
	    netid = whichnet(netlist, &(plabel->position));

	    /* if a pin is declared global, compare it to the names in the */
	    /* global net list, adding to the list if it is not there.	   */
	    /* Change its own net to the global net number (designated by  */
	    /* negative numbers).					   */

	    if (plabel->pin == GLOBAL) {
	       printf("Global node %s found in %s\n", plabel->string + 2,
			cschem->name);
	       gtst = globallist;
	       while (gtst != NULL) {
		  if (!strcmp(gtst->pin->string + 2, plabel->string + 2)) {
	             changepin(cschem, netid, -(gtst->netid));
		     netid = -(gtst->netid);
		     break;
		  }
		  gtst = gtst->next;
	       }
	       if (gtst == NULL) {
		  if (globallist == NULL)
		     globals = 1;
	          else
		     globals = globallist->netid + 1;
	          changepin(cschem, netid, -globals);
	          netid = -globals;
	          makepin(&globallist, plabel, -netid);
	       }
	    }

	    /* if 2 pins share the same name in the object, connect their */
	    /* nets together. 					     */

	    for (ptst = *pinhead; ptst != NULL; ptst = ptst->next) {
	       if (!strcmp(ptst->pin->string + 2, plabel->string + 2)) {
		  printf("In %s linking nets %d and %d\n", cschem->name, 
			netid, ptst->netid); 
		  changepin(cschem, netid, ptst->netid);
		  netid = ptst->netid;
		  break;
	       }
	    }

	    /* add the pin to the pin list */

	    if (netid)
	       makepin(pinhead, plabel, netid);
	 }
      }
   }
}
				
/*-------------------------------------------------------------------------*/
/* Resolve subcircuit calls						   */
/*-------------------------------------------------------------------------*/

void gencalllist(objectptr cschem)
{
   genericptr *cgen, *ogen;
   objinstptr cobj;
   objectptr callobj, callsymb;
   labelptr olabel;
   int netid, callid = 1;
   struct Netlist **nethead = &(cschem->netlist);
   struct Calllist **callhead = &(cschem->calllist);
   XPoint xpos;
   Matrix locctm;

   for (cgen = cschem->plist; cgen < cschem->plist + cschem->parts; cgen++) {
      if ((*cgen)->type == OBJECT) {

      /* When encountering object instances, call gennetlist() on the object if    */
      /* it does not have a valid netlist, then recursively call gencalllist() */

 	 cobj = TOOBJINST(cgen);

	 /* Call gencalllist() recursively on subcircuits of the hierarchy.*/
	 /* ***However,*** an instance of the circuit's OWN symbol is      */
	 /* allowed on the schematic page for reference in the drawing;    */
	 /* don't be fooled into following this infinitely recursive path. */

	 if (cobj->thisobject->symschem != NULL)
	    callobj = cobj->thisobject->symschem;
	 else
	    callobj = cobj->thisobject;
	
	 /* object on its own schematic */
	 if (callobj == cschem) continue;

	 else {
	    if (callobj->netlist == NULL && callobj->schemtype != FUNDAMENTAL) {
	       gennetlist(callobj);
	       gencalllist(callobj);
	    }
	 }

	 /* for each pin-label in the subcircuit or symbol, translate the */
	 /* position to the level above and search for & link in any      */
	 /* connecting nets.						  */

	 callsymb = cobj->thisobject;
	 UResetCTM(&locctm);
	 UPreMultCTM(&locctm, cobj->position, cobj->scale, cobj->rotation);

	 for (ogen = callsymb->plist; ogen < callsymb->plist + callsymb->parts;
		  ogen++) {
	    if ((*ogen)->type == LABEL) {
	       olabel = TOLABEL(ogen);
	       if (olabel->pin) {
		
		  UTransformbyCTM(&locctm, &(olabel->position), &xpos, 1);  
	          netid = whichnet(*nethead, &xpos);
		  if (!netid) {
		     /* pin is not connected to a net.  However, it  */
		     /* may be connected directly to another object, */
		     /* so generate a "one-point" polygon and add it */
		     /* to the net list of the calling object.	     */

		     polyptr newpoly = (polyptr) malloc(sizeof(polygon));
		     newpoly->type = POLYGON;
		     newpoly->style = 0;	/* treat as CLOSED poly */
		     newpoly->number = 1;
		     newpoly->points = (XPoint *)malloc(sizeof(XPoint));
		     newpoly->points->x = xpos.x;
		     newpoly->points->y = xpos.y;
		     netid = (*nethead)->netid + 1;
	    	     linknet(nethead, newpoly, netid);		
		  }
	          makecall(callhead, callobj, olabel, callid, netid);
	       }
	    }
	 }
	 callid++;
      }
   }
}

/*-------------------------------------------------------------------------*/
/* Traverse netlist and return netid of polygon on which pin is located    */
/* If pin is not on any polygon, 0 returned                                */
/*-------------------------------------------------------------------------*/

int whichnet (struct Netlist *netlist, XPoint *testpoint) {
   XPoint *tpt, *tpt2;
	
   for (netlist; netlist != NULL; netlist = netlist->next) {
      for (tpt = netlist->poly->points; tpt < netlist->poly->points
		+ netlist->poly->number; tpt++) {

	 tpt2 = tpt + 1;
	 if (tpt == netlist->poly->points + netlist->poly->number - 1) {
	    if (!(netlist->poly->style & UNCLOSED))
	       tpt2 = netlist->poly->points;
	    else continue;
	 }

	 if (finddist(tpt, tpt2, testpoint) <= 1) {
	    return (netlist->netid);
	 }
      }
   }
   return 0;
}

/*-------------------------------------------------------------------------*/
/* Allocate momory for the new pin list element             		   */
/* Define the values for the new pin list element structure 		   */
/* Insert new pin into pin list and sort according to net id value	   */
/* Pin with greatest net id value goes to head of list              	   */
/*-------------------------------------------------------------------------*/

void makepin(struct Pinlist **pinhead, labelptr pin, int netid)
{
   struct Pinlist *pinptr, *pinpointer = *pinhead;
	
   pinptr = (struct Pinlist *) malloc(sizeof(struct Pinlist));
	
   if (pinptr != NULL) {
      pinptr->pin = pin;
      pinptr->pinx = NULL;
      pinptr->netid = netid;
      pinptr->next = NULL;
   }
   else {
      fprintf(stderr, "Not enough memory\n"); /* Debug printing */
      return;
   }

   if ((*pinhead == NULL)) {
      pinptr->next = *pinhead;
      *pinhead = pinptr;
   }
   else if ((*pinhead)->netid <= pinptr->netid) {
      pinptr->next = *pinhead;
      *pinhead = pinptr;
   }
   else {
      while (pinpointer->next != NULL) {
	 if (pinpointer->next->netid <= pinptr->netid) {
 	    break;
	 }
	 pinpointer = pinpointer->next;
      }
      pinptr->next = pinpointer->next;
      pinpointer->next = pinptr;
   }
}
		
/*-------------------------------------------------------------------------*/
/* Allocate momory for the new call list element             		   */
/* Define the values for the new call list element		   	   */
/* Insert new call into call list					   */
/* Preferable to keep the list in order of parameters calls		   */ 
/*-------------------------------------------------------------------------*/

void makecall(struct Calllist **callhead, objectptr callobj, labelptr callpin,
	int callid, int netid)
{
   struct Calllist *Callptr = NULL, *callpointer = *callhead;
	
   Callptr = (struct Calllist *) malloc(sizeof(struct Calllist));
	
   if (Callptr != NULL) {
      Callptr->callobj = callobj;
      Callptr->pin = callpin;
      Callptr->callno = callid;
      Callptr->netid = netid;
      Callptr->next = NULL;
   }
   else {
      fprintf(stderr, "Not enough memory\n"); /* Debug printing */
   }

   if ((*callhead == NULL)) {
      Callptr->next = *callhead;
      *callhead = Callptr;
   }
   else {
      while (callpointer->next != NULL)
         callpointer = callpointer->next;
      callpointer->next = Callptr;
   }
}
		
/*-------------------------------------------------------------------------*/
/* 									   */
/*-------------------------------------------------------------------------*/

void logpinx(char *pinxfrom, labelptr labto, objectptr cschem)
{
   struct Pinlist *pinlist = cschem->pinlist;
   int netid = pintonet(labto, cschem);

   while (pinlist != NULL) {
      if (netid == pinlist->netid) {
	 pinlist->pinx = pinxfrom;
	 break;
      }
      pinlist = pinlist->next;
   }
}

/*-------------------------------------------------------------------------*/
/* Write a low-level device						   */
/*-------------------------------------------------------------------------*/

void writedevice(FILE *fp, char *mode, objectptr cfrom, struct Calllist *clist,
	char *prefix)
{
   genericptr *pgen;
   labelptr plabel;
   int callid;
   char *pinstr, *strt, *fnsh;
   struct Calllist *calllist = clist;
   objectptr cschem = clist->callobj;

   if (calllist == NULL) {
      fprintf(fp, "error: null device\n");
      return;
   }

   /* Look for information labels in the object parts list. */
   /* (This is not very robust to errors---needs work! */

   for (pgen = cschem->plist; pgen < cschem->plist + cschem->parts; pgen++) {
      if ((*pgen)->type == LABEL) {
	 plabel = TOLABEL(pgen);
         if (!strncmp(plabel->string + 2, mode, strlen(mode))) {
	    if ((strt = strchr(plabel->string + 2, ':')) != NULL) {
	       for (++strt; *strt != '\0'; strt++) {
		  if (*strt == '%') {
		     strt++;
		     switch(*strt) {
			case 'i':
			   fprintf(fp, "%d", devindex++);
			   break;

			case 'p':
			   /* Pin name either has no spaces or is in quotes */
			   strt++;
			   if (*strt == '"') strt++;
			   if (*strt == '"' || *strt == '\0') break;
			   fnsh = strt + 1;
			   while (*fnsh != '\0' && !isspace(*fnsh) && 
					*fnsh != '"') fnsh++; 
			   strncpy(_STR, strt, (int)(fnsh - strt));
			   _STR[(int)(fnsh - strt)] = '\0';
			   strt = fnsh;
			   if (isspace(*fnsh) || *fnsh == '\0') strt--;

			   /* Compare this name against the calllist */
			   calllist = clist;
			   callid = calllist->callno;
			   while (calllist != NULL && calllist->callno ==
					callid) {
			      if (!strcmp(calllist->pin->string + 2, _STR)) {
	            		 fprintf(fp, "%s", nettopin(calllist->netid,	
					    cfrom, prefix));
			         break;
			      }
			      calllist = calllist->next;
			   }
			   if (calllist == NULL || calllist->callno != callid) {
			      sprintf(_STR, "No pin named %s in device %s",
				  _STR, cschem->name);
			      Wprintf(_STR);
			   }
			   break;

			default:
			   fprintf(fp, "%c", *strt);
		     }
		  }
		  else fprintf(fp, "%c", *strt);
	       }
	       fprintf(fp, "\n");
	       break;
	    }
	 }
      }
   }

   if (pgen == cschem->plist + cschem->parts) {

      /* No info about this netlist mode.  Flag a warning and print a default */
      /* type netlist.							   */

      sprintf(_STR, "No info for %s netlist in device %s", mode, cschem->name);
      Wprintf(_STR);

      callid = calllist->callno;
      pinstr = nettopin(calllist->netid, cfrom, prefix);
      fprintf(fp, "   %s (%s", cschem->name, pinstr);
      calllist = calllist->next;

      while (calllist != NULL && calllist->callno == callid) {
         pinstr = nettopin(calllist->netid, cfrom, prefix);
         fprintf(fp, ", %s", pinstr);
         calllist = calllist->next;
      }
      fprintf(fp, ")\n");
   }
}

/*-------------------------------------------------------------------------*/
/* Get rid of locally-defined pin names	 				   */ 
/*-------------------------------------------------------------------------*/

void clearpins(objectptr cschem)
{
   struct Pinlist *pinlist = cschem->pinlist;
  
   while (pinlist != NULL) {
      if (pinlist->pinx != NULL)
         free(pinlist->pinx);
      pinlist->pinx = NULL;
      pinlist = pinlist->next;
   }
}

/*-------------------------------------------------------------------------*/
/* Save netlist into a flattened sim file				   */
/*-------------------------------------------------------------------------*/

void writesimflat(objectptr cschem, struct Calllist *cfrom, 
	char *prefix, FILE *fp)
{
   struct Calllist *calllist = cschem->calllist, *seeklist;
   int callid, curcall, i, j, item = 1, netidx;
   char *newprefix = (char *)malloc(sizeof(char));

   netindex = 1;

   /* write all the subcircuits */

   while (calllist != NULL) {
      callid = calllist->callno;

      seeklist = calllist;
      if (seeklist->callobj->schemtype == FUNDAMENTAL) {
         writedevice(fp, "sim", cschem, seeklist, prefix);
	 while (seeklist != NULL && seeklist->callno == callid)
            seeklist = seeklist->next;
      }
      else {
         while (seeklist != NULL && seeklist->callno == callid) {
	    logpinx(nettopin(seeklist->netid, cschem, prefix),
		seeklist->pin, seeklist->callobj);
	    seeklist = seeklist->next;
         }
	 sprintf(_STR, "%s%d", calllist->callobj->name, item++);
	 newprefix = (char *)realloc(newprefix, sizeof(char) * (strlen(prefix)
		+ strlen(_STR) + 2));
	 sprintf(newprefix, "%s%s/", prefix, _STR);
	 netidx = netindex;
         writesimflat(calllist->callobj, calllist, newprefix, fp);
	 netindex = netidx;
      }
      calllist = seeklist;
   }
   clearpins(cschem);
   free(newprefix);
}

/*-------------------------------------------------------------------------*/
/* Write out the list of global nets and their pin names		   */
/*-------------------------------------------------------------------------*/

void writeglobals(objectptr cschem, FILE *fp)
{
   struct Pinlist *pinptr;

   pinptr = globallist;
   while (pinptr != NULL) {
      fprintf(fp, "%s = %d\n", pinptr->pin->string + 2, -pinptr->netid);
      pinptr = pinptr->next;
   }
   fprintf(fp, "\n");
}

/*-------------------------------------------------------------------------*/
/* Save netlist into a hierarchical file				   */
/*-------------------------------------------------------------------------*/

void writehierarchy(objectptr cschem, struct Calllist *cfrom, FILE *fp)
{
   struct Calllist *calllist = cschem->calllist, *clist;
   int curcall, netid;
   char *stsave;

   /* make sure that all the subcircuits have been written first */

   for (; calllist != NULL; calllist = calllist->next) {
      if (calllist->callobj->traversed == False) {
         calllist->callobj->traversed = True;
         writehierarchy(calllist->callobj, calllist, fp);
      }
   }

   /* write own subcircuit netlist */

   clist = cfrom;

   if (cschem->schemtype == FUNDAMENTAL)
      return;

   else if (clist != NULL) {
      curcall = clist->callno;
      fprintf(fp, ".subckt %s", cschem->name);

      /* list of parameters to subcircuit */

      for (; clist != NULL && clist->callno == curcall; clist = clist->next) {
         fprintf(fp, " %s", clist->pin->string + 2);
      }
      fprintf(fp, "\n");
   }

   calllist = cschem->calllist;
   while (calllist != NULL) {
      curcall = calllist->callno;

      /* The call is to a fundamental device. . . */

      if (calllist->callobj->schemtype == FUNDAMENTAL) {
         writedevice(fp, "spice", cschem, calllist, NULL);
	 while (calllist != NULL && calllist->callno == curcall)
	    calllist = calllist->next;
      }

      /* . . . or else is a call to a subcircuit */

      else {
         fprintf(fp, "X%d", subindex++);
	 stsave = calllist->callobj->name;
         for (; calllist != NULL && curcall == calllist->callno;
		 calllist = calllist->next) {
	    fprintf(fp, " %s", nettopin(calllist->netid, cschem, NULL));
         } 
         fprintf(fp, " %s\n", stsave);
      }
   }
   if (cfrom == NULL)
      fprintf(fp, ".end\n");
   else
      fprintf(fp, ".ends\n\n");
}

/*-------------------------------------------------------------------------*/

void writenet(objectptr cschem, char *mode, char *suffix)
{
   struct Calllist *calllist = cschem->calllist;
   char filename[100], *str;
   char *prefix, *cpos;
   FILE *fp;

   netindex = devindex = subindex = 1;
 
   if ((cpos = strchr(cschem->name, ':')) != NULL) *cpos = '\0';
   sprintf(filename, "%s.%s", cschem->name, suffix);
   if (cpos != NULL) *cpos = ':';

   if ((fp = fopen(filename, "w")) != NULL) {
      if (!strcmp(mode, "spice")) {
         /* writeglobals(cschem, fp); */
         fprintf(fp, "Spice circuit %s\n\n", cschem->name);
         writehierarchy(cschem, NULL, fp);
      }
      else if (!strcmp(mode, "sim")) {
         prefix = (char *)malloc(sizeof(char));
	 *prefix = '\0';
	 writesimflat(cschem, NULL, prefix, fp);
         free(prefix);
      }
      else if (!strcmp(mode, "pcb")) {
	 writepcb(cschem, NULL, fp);
      }
      fclose(fp);
      sprintf(_STR, "%s netlist saved as %s", mode, filename);
   }
   else {
      sprintf(_STR, "Could not open file %s for writing.", filename);
   }
   Wprintf(_STR);
}

/*-------------------------------------------------------------------------*/
/* Find a pin name for the given net number				   */
/* Either take the first pin name with the net, or generate a new pin,	   */
/* assigning it a net number for a string.				   */
/* prefix = NULL indicates spice netlist				   */
/*-------------------------------------------------------------------------*/

char *nettopin(int netid, objectptr cschem, char *prefix)
{
   struct Pinlist *pinlist = cschem->pinlist;
   char *newstring;
   labelptr newlabel;

   if (prefix == NULL) {   	/* spice netlist */
      if (netid < 0) {
         pinlist = globallist;
         netid = -netid;
      }
      while (pinlist != NULL) {
         if (pinlist->netid == netid) return pinlist->pin->string + 2;
         pinlist = pinlist->next;
      }

      /* Pinlist is NULL: make a new pin and assign a net ID number */

      newlabel = (labelptr) malloc(sizeof(label));
      newlabel->type = LABEL;
      newlabel->pin = False;
      sprintf(_STR, "net.%d", netindex++);
      newlabel->string = (char *)malloc((2 + sizeof(_STR)) *
	     sizeof(char));
      sprintf(newlabel->string, "%c%c%s", TEXT_ESC, FONT_START, _STR);
      makepin(&(cschem->pinlist), newlabel, netid);

      return (newlabel->string + 2);
   }

   /* sim netlist */

   if (netid < 0) {
      pinlist = globallist;
      netid = -netid;
   }
   while (pinlist != NULL) {
      if (pinlist->netid == netid) {
	 if (pinlist->pinx != NULL)
	    return pinlist->pinx;
	 else if (pinlist->pin && (pinlist->pin->pin == GLOBAL))
	    return (pinlist->pin->string + 2);
	 else 
	    break;
      }
      pinlist = pinlist->next;
   }

   /* Generate the string for the local instantiation of this pin	*/
   /* If this node does not have a pin, create one using the current	*/
   /* hierarchy prefix as the string.					*/

   if (pinlist != NULL)
      strcpy(_STR, pinlist->pin->string + 2);
   else
      sprintf(_STR, "net%d", netindex++);  /* for now. . . */

   newstring = (char *)malloc((strlen(_STR) + strlen(prefix) + 3)
		* sizeof(char));
   sprintf(newstring, "%s%s", prefix, _STR);

   /* If this is the first time at this point in the schematic,   */
   /* then the pinlist is NULL and a new pin needs to be created. */
   /* Use pin = False so that memory freeing routine knows to     */
   /* destroy the label after the netlist is written.		  */

   if (pinlist == NULL) {
      newlabel = (labelptr) malloc(sizeof(label));
      newlabel->type = LABEL;
      newlabel->pin = False;
      newlabel->string = (char *)malloc((2 + sizeof(_STR)) *
	  sizeof(char));
      sprintf(newlabel->string, "%c%c%s", TEXT_ESC, FONT_START, _STR);
      makepin(&(cschem->pinlist), newlabel, netid);
   }
   
   return newstring;
}

/*-------------------------------------------------------------------------*/
/* Find the net which connects to the given pin label			   */
/*-------------------------------------------------------------------------*/

int pintonet(labelptr testpin, objectptr cschem)
{
   struct Pinlist *pinlist = cschem->pinlist;


   while(pinlist != NULL) {
      if (pinlist->pin != NULL)
         if (pinlist->pin->string == testpin->string)
	    return pinlist->netid;
      pinlist = pinlist->next;
   }

   /* If there was no net found, try equating the strings themselves,   */
   /* i.e., otherwise unconnected I/O pin has same name as another pin. */

   pinlist = cschem->pinlist;
   while(pinlist != NULL) {
      if (!strcmp(pinlist->pin->string + 2, testpin->string + 2))
	  return pinlist->netid;
      pinlist = pinlist->next;
   }

   /* otherwise return 0 */

   return 0;
}

/*-------------------------------------------------------------------------*/
/* Flatten netlist and save into pcb-style file				   */
/*-------------------------------------------------------------------------*/

#define MAXPINON1LN 2

void writepcb(objectptr cschem, struct Calllist *cfrom, FILE *fp)
{
   struct Pinlist *pinlist = cschem->pinlist;
   struct Calllist *calllist = cschem->calllist;

   char *str;
   int count = 0; /* Number of pins already written on 1 line */
   int lastnetid = pinlist->netid, callid; 
   int unconnected = 1; /* Count of unconnected pins; used as 'net ID' */
	
   for (pinlist; pinlist != NULL; pinlist = pinlist->next) {
      if (pinlist->netid != 0) {
         /* If pin is not unconnected... */
 	 if (pinlist->netid != lastnetid) {
	    /* If pin not on same net as previous pin... */
	    lastnetid = pinlist->netid;
	    count = 1;
	    fprintf(fp, "\nNET%d\t", pinlist->netid);
	 }
	 else {
	    if (count == 0) {
	       /* If nothing written yet... */
	       count++;
	       fprintf(fp, "NET%d\t", pinlist->netid);
	    }	
	    else if (count < MAXPINON1LN) {
	       /* If still can write on same line... */
	       count++;
	    }
	    else {
	       /* If line already contains maximum pins... */
	       count = 1;
	       fprintf(fp, " \\\n\t\t");
	    }
	 }
      }
      else {
	 /* If pin is unconnected */
	 if (count != 0) {
	    /* If other pins are already written... */
	    fprintf(fp, "\n");
	 }
	 count = 1;
	 fprintf(fp, "UNCONNECTED%d\t", unconnected);
	 unconnected++;
      }

      /* Write pin label, discarding font information in the 1st 2 chars. */

      str = (char *)pinlist->pin->string;
      fprintf(fp, "\t%s", str + 2);

      /* now continue down into all subcircuits containing this net, */
      /* revising the net numbering of each subcircuit.		     */

      for (; calllist != NULL; calllist = calllist->next) {
	 callid = calllist->callno;
	 if (calllist->netid == pinlist->netid) {
	    /* revisenets(calllist->callobj, calllist); */
            writepcb(calllist->callobj, calllist, fp);
	 }
	 while (calllist->callno == callid) {
	    calllist = calllist->next;
	    if (calllist == NULL) break;
	 }
      }
   }
}

/*-------------------------------------------------------------------------*/
/* Free memory allocated for netlist 					   */
/*-------------------------------------------------------------------------*/

void freenets(objectptr cschem)
{
   struct Netlist *netlist = cschem->netlist, *nptr = netlist;
   struct Pinlist *pinlist = cschem->pinlist, *pptr = pinlist;
   struct Calllist *calllist = cschem->calllist, *cptr = calllist;
   genericptr *cgen;
   objinstptr cobj;
   objectptr callobj;
	
   /* Recursively call freenets() on all subobjects, a la gencalllist() */

   for (cgen = cschem->plist; cgen < cschem->plist + cschem->parts; cgen++) {
      if ((*cgen)->type == OBJECT) {
 	 cobj = TOOBJINST(cgen);

	 if (cobj->thisobject->symschem != NULL)
	    callobj = cobj->thisobject->symschem;
	 else
	    callobj = cobj->thisobject;
	
	 /* Don't infinitely recurse if object is on its own schematic */

	 if (callobj != cschem) freenets(callobj);
      }
   }

   /* Free the allocated structures for this object */

   while (cptr != NULL) {
      calllist = calllist->next;
      cptr->next = NULL;
      free(cptr);
      cptr = calllist;
   }

   while (nptr != NULL) {
      netlist = netlist->next;
      if (nptr->poly->number == 1) {   /* free single-point polys */
	 free (nptr->poly->points);
	 free (nptr->poly);
      }
      nptr->next = NULL;
      free (nptr);
      nptr = netlist;
   }

   while (pptr != NULL) {
      pinlist = pinlist->next;
      if (pptr->pin)
         if (pptr->pin->pin == False) {
	    if (pptr->pin->string != NULL) {
               free(pptr->pin->string);
               pptr->pin->string = NULL;
	    }
	    free(pptr->pin);
            pptr->pin = NULL;
         }
      pptr->next = NULL;
      free(pptr);
      pptr = pinlist;
   }

   cschem->netlist = NULL;
   cschem->pinlist = NULL;
   cschem->calllist = NULL;
   cschem->traversed = False;
}

/*-------------------------------------------------------------------------*/
/* Free the global pin list 					   	   */
/*-------------------------------------------------------------------------*/

void freeglobals()
{
   struct Pinlist *pinlist = globallist, *pptr = pinlist;

   while (pptr != NULL) {
      pinlist = pinlist->next;
      pptr->next = NULL;
      free(pptr);
      pptr = pinlist;
   }
   globallist = NULL;
}

#endif
/*-------------------------------------------------------------------------*/