#!/usr/bin/perl -w

use strict;
my $cnt = 0;

##############################

sub print_define( $ $ $ ) {
  my $sz = shift;
  my $name = shift;
  my $arr = shift;

  $name = "\U$name";
  if ($arr > 1) {
    printf "#define DAVIS_%-20s %2s // %s x %s\n", $name, $cnt, $sz, $arr;
  } else {
    printf "#define DAVIS_%-20s %2s // %s\n", $name, $cnt, $sz;
  }
};

sub pr_struct2( $ $ $ ) {
  my $sz = shift;
  my $name = shift;
  my $arr = shift;

  if ($sz == 2) {
    printf("  uint16_t %s;\n", $name, "\U$name");
  }
}

sub pr_struct1( $ $ $ ) {
  my $sz = shift;
  my $name = shift;
  my $arr = shift;

  if ($sz == 1) {
    if ($arr > 1) {
      printf("  uint8_t %s[%d];\n", $name, $arr);
    } else {
      printf("  uint8_t %s;\n", $name);
    }
  }
}

sub pr_cnv( $ $ $ ) {
  my $sz = shift;
  my $name = shift;
  my $arr = shift;

  if ($sz == 2) {
    printf("pkt->%-29s = davis_value_u16(buf+DAVIS_%s);\n", $name, "\U$name");
  } else {
    if ($arr == 1) {
      printf("pkt->%-29s = buf[DAVIS_%s];\n", $name, "\U$name");
    } else {
      printf("for (ix = 0; ix < %d; ++ix) {\n", $arr);
      my $str = "${name}[ix]";
      printf("  pkt->%-27s = buf[DAVIS_%s+ix];\n", $str, "\U$name");
      print "}\n";
    }
  }
}

sub pr_hdr( $ $ $ ) {
  my $sz = shift;
  my $name = shift;
  my $arr = shift;

  printf("  \"%s\",\n", $name );
}

sub pr_pr( $ $ $ ) {
  my $sz = shift;
  my $name = shift;
  my $arr = shift;

  if ($sz == 2) {
    printf("cnt = snprintf(bp, len, %s, pkt->%s);\nbp += cnt;\nlen -= cnt;\n", "\"%7d\"", $name);
  } else {
    if ($arr == 1) {
      printf("cnt = snprintf(bp, len, %s, pkt->%s);\nbp += cnt;\nlen -= cnt;\n", "\"%7d\"", $name);
    } else {
      printf("for (ix = 0; ix < %d; ++ix) {\n", $arr);
      my $str = "${name}[ix]";
      printf("cnt = snprintf(bp, len, %s, pkt->%s);\nbp += cnt;\nlen -= cnt;\n", "\"%7d\"", $str);
      print "}\n";
    }
  }
}

##############################

my $flag = 0;

while (<>) {
  if (!$flag) {
    if (m/^struct davis_loop_decoded/) {
      $flag = 1;
    }
    next;
  }
  if (m/^\}/) {
    last;
  }
  if (m/\/\//) { next; }
  if (m/\/\*/) { print; next; }
  if (m/\*\//) { print; next; }
  if (m/^[ \t]*$/) { print "\n"; next; }

  my $sz;
  my $name;
  my $arr;

  s/;.*//;
  m/uint(\d+)_t ([a-z_]+)\[?(\d)?\]?/;
  $sz = $1 == 8 ? 1 : 2;
  $name = $2;

  if (defined($3)) {
    $arr = $3;
  } else {
    $arr = 1;
  }

  #print_define($sz, $name, $arr);
  #pr_struct2($sz, $name, $arr);
  #pr_struct1($sz, $name, $arr);
  #pr_cnv($sz, $name, $arr);
  #pr_hdr($sz, $name, $arr);
  pr_pr($sz, $name, $arr);

  $cnt += $sz * $arr;
}
