#!/usr/bin/perl
use strict;

package main;
    my $line;
    my $name;
    my $size;
    my $description;

    (open INFILE, "<inttypes.h") or die "Cannot open inttypes.h: $!\n";

    while ($line = <INFILE>) {
        
        if ($line =~ m@^#\s*define (\S+) (\C*?)$@) {
            $name = $1;
            my $name2;
            my $description2;
            my $scanf = '';
            my $realname; # Actual name of the .hsf
            
            # This file contains only macros without arguments
            warn "$name\n" if ($name !~ m@(PRI|SCN)(d|i|u|x|X)(\d{1,2}|LEAST\d{1,2}|FAST\d{1,2}|PTR)@);
        
            if ($1 eq 'PRI') {
                $description = 'Format specifier for printing an integer of type ';
            }
            else {
                $description = 'Format specifier for scanning an integer of type ';
                $scanf = ' written';
            }

            $name2 = lc($3);
            if ((index($3, 'LEAST') != -1) || (index($3, 'FAST') != -1)) {
                $name2 = '_' . $name2;
            }
            $name2 = 'int' . $name2 . '_t';

            $description = $description . $name2 . ' or u' . $name2;

            $realname = $name; # not necessarily equal to $name, due to name clash between uppercase and lowercase on case-insensitive filesystems.
            if (($2 eq 'd') || ($2 eq 'i')) {
                $description = $description . $scanf . ' as a signed decimal integer'
            }
            elsif ($2 eq 'u') {
                $description = $description . $scanf . ' as an unsigned decimal integer'
            }
            elsif ($2 eq 'x') {
                $description = $description . $scanf . ' as an unsigned hexadecimal (lowercase) integer'
            }
            elsif ($2 eq 'X') {
                $description = $description . $scanf . ' as an unsigned hexadecimal (uppercase) integer';
                $realname =~ y@X@Z@;
            }

            $description2 = '';

            $name2 = $name;
            if ($2 eq 'd') {
                $name2 =~ y@d@i@;
                $description2 = 'This definition is the same as <A HREF="$$LINK(inttypes.h/' . $name2 . ')">' . $name2 . "</A>.";
            }
            elsif ($2 eq 'i') {
                $name2 =~ y@i@d@;
                $description2 = 'This definition is the same as <A HREF="$$LINK(inttypes.h/' . $name2 . ')">' . $name2 . "</A>.";
            }

            $description2 = $description2 . "\r\nDefinition mandated by the C99 standard.";

            $line =~ s/\n//g; # Swallow newline.
            open OUTFILE, "+>trunk/tigcc/doc/System/Include/inttypes.h/$realname.hsf";
            print OUTFILE <<EOF
[Main]\r
Name=$name\r
Type=Constant\r
Header Files=inttypes.h\r
Definition=$line\r
\r
[Description]\r
$description.\r
\r
[Explanation]\r
$description2\r
EOF
;
            close OUTFILE;
            }
    }

