src/sn_{network,stage}.[ch]: Implement sn_network_unify().
[sort-networks.git] / src / sn-cut.c
1 /**
2  * libsortnetwork - src/sn-cut.c
3  * Copyright (C) 2008-2010  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <ff at octo.it>
20  **/
21
22 #include "config.h"
23
24 #ifndef _ISOC99_SOURCE
25 # define _ISOC99_SOURCE
26 #endif
27 #ifndef _POSIX_C_SOURCE
28 # define _POSIX_C_SOURCE 200809L
29 #endif
30 #ifdef _XOPEN_SOURCE
31 # define _XOPEN_SOURCE 700
32 #endif
33
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <strings.h>
38
39 #include "sn_network.h"
40
41 static void exit_usage (const char *name)
42 {
43   printf ("Usage: %s <num>[:min|max] [<num>[:min|max] ...]\n", name);
44   exit (EXIT_FAILURE);
45 }
46
47 static int do_cut (sn_network_t *n, int defs_num, char **defs)
48 {
49   int mask[SN_NETWORK_INPUT_NUM (n)];
50   int status;
51   int i;
52
53   memset (mask, 0, sizeof (mask));
54   for (i = 0; i < defs_num; i++)
55   {
56     char *endptr = NULL;
57     int pos;
58     int val = 1;
59
60     pos = (int) strtol (defs[i], &endptr, /* base = */ 0);
61     if (strcasecmp (":min", endptr) == 0)
62       val = -1;
63
64     if ((pos < 0) || (pos >= SN_NETWORK_INPUT_NUM (n)))
65     {
66       fprintf (stderr, "Invalid line number: %i\n", pos);
67       return (-1);
68     }
69
70     mask[pos] = val;
71   }
72
73   status = sn_network_cut (n, mask);
74   if (status != 0)
75   {
76     fprintf (stderr, "sn_network_cut failed with status %i.\n", status);
77     return (-1);
78   }
79
80   return (0);
81 } /* }}} int do_cut */
82
83 int main (int argc, char **argv)
84 {
85   sn_network_t *n;
86
87   if (argc < 2)
88     exit_usage (argv[0]);
89
90   n = sn_network_read (stdin);
91   if (n == NULL)
92   {
93     fprintf (stderr, "Unable to read network from STDIN.\n");
94     exit (EXIT_FAILURE);
95   }
96
97   do_cut (n, argc - 1, argv + 1);
98   sn_network_compress (n);
99
100   sn_network_write (n, stdout);
101
102   exit (EXIT_SUCCESS);
103 } /* int main */
104
105 /* vim: set shiftwidth=2 softtabstop=2 : */