multiplexor.c 1.13 KB
#include <stdio.h>
#include <string.h>
#include "auxiliar.h"
#include <math.h>

int check_length(char **inputs, uint8_t num_inputs)
{
        int i;
        int length = strlen(inputs[0]);
        for(i = 1; i < num_inputs-1; i++)
        {
                if(strlen(inputs[i]) != length)
                {
                        return -1;
                }
        }
        int sel_length = strlen(inputs[num_inputs-1]);
        if(pow(2,sel_length) < (num_inputs-1))
        {
        	return -1;
        }
        return length;
}

int main(int argc, char **argv)
{
	int i;
	if(argc != 2)
	{
		error();
	}
	char *input = argv[1];
	if(!strcmp(input,"error"))
	{
		error();
	}
	char **inputs = comma_separate(input);
	if(inputs == NULL)
	{
		error();
	}
	int num_inputs = num_occurrences(input,',');
	int input_length = check_length(inputs,num_inputs);
	if(input_length == -1)
	{
		error();
	}
	int selected = bin2dec(inputs[num_inputs-1]);
	if(selected >= (num_inputs-1))
	{
		for(i = 0; i < input_length; i++)
		{
			printf("0");
		}
	}
	else
	{
		char *result = inputs[selected];
		printf("%s",result);
	}
	free_mem(inputs,num_inputs);
	return 0;
}