#! /usr/bin/env perl
use strict;

# Silly little program to generate the help.c source file
# from the less.hlp text file.
# The output of this script is a C program defining a char array 
# whose content is the input to this script.

{
    my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($ENV{SOURCE_DATE_EPOCH} // time());
    printf "/* This file was generated by mkhelp.pl from less.hlp at %d:%02d on %d/%d/%d */\n",
        $hour, $min, $year+1900, $mon+1, $mday;
    print "#include \"less.h\"\n";
    print "constant char helpdata[] = {\n";
    my $ch = 0;
    my $prevch;
    for (;;) {
        $prevch = $ch;
        $ch = getc();
        last if not defined $ch;
        if ($ch eq "'") {
            print "'\\'',";
        } elsif ($ch eq "\\") {
            print "'\\\\',";
        } elsif ($ch eq "\b") {
            print "'\\b',";
        } elsif ($ch eq "\t") {
            print "'\\t',";
        } elsif ($ch eq "\n") {
            print "'\\n',\n" if $prevch ne "\r";
        } elsif ($ch eq "\r") {
            print "'\\n',\n" if $prevch ne "\n";
        } else {
            if (ord($ch) >= ord(' ') && ord($ch) < 0x7f) {
                print "'$ch',";
            } else {
                printf "0x%02x,", ord($ch);
            }
        }
    }
    # Add an extra null char to avoid having a trailing comma.
    print " 0 };\n";
    print "constant int size_helpdata = sizeof(helpdata) - 1;\n";
}
