#!/bin/bash

if [[ "$#" != 2 ]]; then
    echo "Usage: $0 MD_FILE HELP_FILE.h"
    exit 1
fi

mdfile="$1"
helpfile="$2"
newfile="$helpfile.new"
findfile="${helpfile/./\\.}"

sed -e '1,/^\[comment\].*'"$findfile"'/d' \
    -e '1,/^```/d' \
    -e '/^```/,$d' \
    -e 's/"/\\"/g' \
    -e 's/^/  rprintf(F,"/' \
    -e 's/$/\\n");/' \
    <"$mdfile" >"$newfile"

if [[ ! -s "$newfile" ]]; then
    rm "$newfile"
    echo "Discarding empty output for $helpfile file from $mdfile"
    exit 1
fi

(cat <<EOT
/* DO NOT EDIT THIS FILE!  It is auto-generated from the option list in $mdfile! */
 
EOT
cat "$newfile"
) >"$helpfile"
rm "$newfile"
