#!/usr/bin/perl -W

###########################################################################
#   crwx-ng                                                               #
#   Copyright (C) 2023 Aleksey Chernov <valexlin@gmail.com>               #
#                                                                         #
#   This program is free software; you can redistribute it and/or         #
#   modify it under the terms of the GNU General Public License           #
#   as published by the Free Software Foundation; either version 2        #
#   of the License, or (at your option) any later version.                #
#                                                                         #
#   This program is distributed in the hope that it will be useful,       #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#   GNU General Public License for more details.                          #
#                                                                         #
#   You should have received a copy of the GNU General Public License     #
#   along with this program; if not, write to the Free Software           #
#   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,            #
#   MA 02110-1301, USA.                                                   #
###########################################################################

#
# This program is based on the crrcconv.cpp sources and uses its algorithms
# Copyright (C) 2007 Vadim Lopatin <coolreader.org@gmail.com>
#

use 5.010;
use strict;
use warnings;

if (scalar(@ARGV) < 3) {
    print("Resource converter converter\n");
    print("usage: $0 <infile.ext> <outfile.h> <VARNAME>\n");
    exit -1;
}

my $in_filename = $ARGV[0];
my $out_filename = $ARGV[1];
my $varname = $ARGV[2];

my $infh;
my $outfh;
if (!open($infh, "<", $in_filename)) {
    print "Cannot open file ${in_filename}\n";
    exit 1;
}
binmode $infh;
if (!open($outfh, ">", $out_filename)) {
    close($infh);
    print "Cannot create file ${out_filename}\n";
    exit 1;
}

print "$0: converting ${in_filename} to ${out_filename}...\n";

my ($buff, @array, $bytesRead, $ch, $sz);
printf $outfh ("// Binary representation of file: ${in_filename}\n");
printf $outfh ("// clang-format off\n");
printf $outfh ("static const unsigned char ${varname}[] = {\n");
$sz = 0;
while (1) {
    $bytesRead = read($infh, $buff, 16);
    if (defined($bytesRead) && $bytesRead > 0) {
        $sz += $bytesRead;
        @array = split //, $buff;
        printf $outfh ("    ");
        foreach $ch (@array) {
            printf $outfh ("0x%02x,", ord($ch));
        }
        print $outfh ("\n");
    } else {
        last;
    }
}
print $outfh ("};\n");
print $outfh ("static const int ${varname}_size = ${sz};\n");
printf $outfh ("// clang-format on\n");
close($outfh);
close($infh);
printf("done.\n");
