src/sn-tex.c: Add a program to format sort networks as tikz source.
[sort-networks.git] / src / sn-tex.c
1 #include <stdlib.h>
2 #include <stdio.h>
3
4 #define SCALE 0.7
5 #define INNER_SPACING 0.35
6 #define OUTER_SPACING 1.5
7
8 #include "sn_network.h"
9
10 static double x_offset = OUTER_SPACING;
11 static int next_vertex_number = 0;
12
13 static int tex_show_stage (sn_stage_t *s)
14 {
15   int lines[s->comparators_num];
16   int right[s->comparators_num];
17   int lines_used = 0;
18   int i;
19
20   for (i = 0; i < s->comparators_num; i++)
21   {
22     lines[i] = -1;
23     right[i] = -1;
24   }
25
26   for (i = 0; i < s->comparators_num; i++)
27   {
28     int j;
29     sn_comparator_t *c = s->comparators + i;
30
31     int min_num;
32     int max_num;
33
34     min_num = next_vertex_number;
35     next_vertex_number++;
36
37     max_num = next_vertex_number;
38     next_vertex_number++;
39
40     for (j = 0; j < lines_used; j++)
41       if (SN_COMP_LEFT (c) > right[j])
42         break;
43
44     lines[i] = j;
45     right[j] = SN_COMP_RIGHT (c);
46     if (j >= lines_used)
47       lines_used = j + 1;
48
49     printf ("\\node[vertex] (v%i) at (%.2f,%i) {};\n"
50         "\\node[vertex] (v%i) at (%.2f,%i) {};\n"
51         "\\path[comp] (v%i) -- (v%i);\n"
52         "\n",
53         min_num, x_offset + (j * INNER_SPACING), c->min,
54         max_num, x_offset + (j * INNER_SPACING), c->max,
55         min_num, max_num);
56   }
57
58   x_offset = x_offset + ((lines_used - 1) * INNER_SPACING) + OUTER_SPACING;
59
60   return (0);
61 } /* int tex_show_stage */
62
63 int main (int argc, char **argv)
64 {
65   sn_network_t *n;
66   FILE *fh = NULL;
67   int i;
68
69   if (argc == 1)
70     fh = stdin;
71   else if (argc == 2)
72     fh = fopen (argv[1], "r");
73
74   if (fh == NULL)
75   {
76     printf ("fh == NULL!\n");
77     return (1);
78   }
79
80   n = sn_network_read (fh);
81
82   if (n == NULL)
83   {
84     printf ("n == NULL!\n");
85     return (1);
86   }
87
88   printf ("\\begin{tikzpicture}[scale=%.2f,auto]\n", SCALE);
89
90   for (i = 0; i < SN_NETWORK_STAGE_NUM (n); i++)
91      tex_show_stage (SN_NETWORK_STAGE_GET (n, i));
92
93   for (i = 0; i < SN_NETWORK_INPUT_NUM (n); i++)
94     printf ("\\path[edge] (0,%i) -- (%.2f,%i);\n",
95         i, x_offset, i);
96
97   printf ("\\end{tikzpicture}\n");
98
99   return (0);
100 } /* int main */
101
102 /* vim: set shiftwidth=2 softtabstop=2 : */