#!/usr/bin/perl -w
#
# generate big and litte endian unions filled with bit-value-structs
use strict;

die "$0 <reg-pl-file>" if @ARGV != 1;

my $fn = shift @ARGV;

our ($basename) = split(/\./,$fn);
$basename =~ s/\-/\_/g;
our $BASENAME = uc($basename);
our @indent = ();

our $copyright;
our $regs;
require $fn;

create_le();
create_be();

sub open_file
{
	my ($t) = @_;
	my $T = uc($t);

	open(FH,">".$basename."_$t.h");

	print FH <<EOL;
$copyright
/* This file is automatically generated, do not edit things here. */
#ifndef __$BASENAME\_INCLUDED__
#define __$BASENAME\_INCLUDED__

typedef union {
	u32 raw;
EOL
	push @indent,"\t";
	return *FH;
}

sub close_file
{
	*FH = shift;
	pop @indent;
	print FH <<EOL;
} $basename;

#endif
EOL

}

sub array
{
	my ($a,$f,$o) = @_;

	my @array = @{$a};

	@array = reverse @array if $o == 1;

	push @indent,"\t";
	for (my $i = 0; $i < scalar @array; $i+=2) {
		# if type ...
		printf $f join("",@indent)."u32 %-30s :%2d;\n",$array[$i+$o],$array[$i-$o+1];
	}
	pop @indent;
}


sub create_le
{
	*FH = open_file("le");
	for (my $i = 0; $i < scalar @{$regs}; $i+=2) {
		print FH "\n".join("",@indent)."struct {\n";
		array($regs->[$i+1],*FH,0);
		print FH join("",@indent)."} ".$regs->[$i].";\n";

	}
	close_file(*FH);
}

sub create_be
{
	*FH = open_file("be");
	for (my $i = 0; $i < scalar @{$regs}; $i+=2) {
		print FH "\n".join("",@indent)."struct {\n";
		array($regs->[$i+1],*FH,1);
		print FH join("",@indent)."} ".$regs->[$i].";\n";

	}
	close_file(*FH);
}


