\documentclass[a4paper,12pt]{scrartcl}

\usepackage{perltex}

\usepackage{graphicx}

\usepackage{colortbl}

\definecolor{title}{rgb}{0.86,0.86,0.86}
\definecolor{bit}{rgb}{0.8,0.86,0.8}
\definecolor{bitval}{rgb}{0.8,0.8,0.8}
\definecolor{names}{rgb}{0.86,0.93,0.86}

\arrayrulecolor{black}

\begin{document}

\perlnewcommand{\ins}[5]
{
	my $bits = $_[0];
	my $bline;
	#bit value line
	my $vline;
	my $nline;
	#print bit value line
	my $pvline;
	my @bitlist;
	my $tabular;


	$count = 0;
	@fields = split(/\|/, $_[3]);
	foreach my $field (@fields) {
		#remove heading and trailing spaces
		$field =~ s/^\s+//;
		$field =~ s/\s+$//;

		$count += $field;
		#$tabular .= $field." \\\\";
	}

	if($count != $bits) {
		return "Num of Fields not equal to Bits!";
	}
	$count = 0;
	@fieldnames = split(/\|/, $_[4]);

	if(scalar(@fields) != scalar(@fieldnames)) {
		return "Num of Fields != Num of Names";
	}

	$pvline = 0;
	foreach my $fieldn (@fieldnames) {
		#remove heading and trailing spaces
		$fieldn =~ s/^\s+//;
		$fieldn =~ s/\s+$//;

		if($fieldn =~ m/^[^\(.]*\(\s*([0-1]+)\s*\).*$/) {
			if(length($1) == $fields[$count]) {
				push(@bitlist,$1);
				$fieldn =~  s/\s?\(\s*[0-1]+\s*\)//;
				$pvline = 1;
			}
			else {
				$x = '';
				for($i = 1; $i <= $fields[$count]; $i++) {
					$x .= 'X';
				}
				push(@bitlist,$x);
			}
		}
		else {
			$x = '';
			for($i = 1; $i <= $fields[$count]; $i++) {
				$x .= 'X';
			}
			push(@bitlist,$x);
		}
		#$tabular .= $fieldn.": ". $bits." \\\\";
		$count++;
	}
	$bitlist = join("",@bitlist);

	#$tabular .= "\\textbf{names:} @fieldnames \n";
	#$tabular .= "\\textbf{bitlist:} $bitlist \n";

	$count = $bits-1;

	$tabular = "\\begin{center} \n \\resizebox{\\textwidth}{!}{\n";
	$tabular .= "\\begin{tabular}{|l|";
	for($i = $bits-1; $i >= 0; $i--) {
		#build table
		$tabular .= "c|";

		#build bitcount
		$bline .= $i;
		if($i != 0) {
			$bline .= " & ";
		}
		else {
			$bline .= "\\\\ \\hline \n";
		}

		#build bitvalue
		$vline .= substr($bitlist,($bits-1)-$i,1);
		if($i != 0) {
			$vline .= " & ";
		}
		else {
			$vline .= "\\\\ \\hline \n";
		}

		#build nameline
		#because of multicolumn we need to limit execution
		if($i == $count) {
			$nline .= "\\multicolumn{@fields[0]}{>{\\columncolor{names}}c|}{@fieldnames[0]}";

			#update count
			$count -= @fields[0];

			if($count <= 0) {
				$nline .= "\\\\ \\hline \n";
			}
			else {
				$nline .= " & ";
			}

			shift(@fieldnames);
			shift(@fields);
		}
	}
	$tabular .= "} \\hline \n";
	$tabular .= "\\multicolumn{".($bits+1)."}{|>{\\columncolor{title}}c|}{\\textbf{".$_[1]."} (".$_[2].")} \\\\ \\hline \n";
	$tabular .= "\\rowcolor{bit} \\cellcolor{title} &". $bline;
	if($pvline == 1) {
		$tabular .= "\\rowcolor{bitval} \\cellcolor{title}Values &". $vline;
	}
	$tabular .= "\\cellcolor{title}Field &". $nline;
	$tabular .= "\\end{tabular}\n}\n \\end{center}\n";


	return $tabular;
}

\input{isa_file}

\end{document}

