#!/usr/bin/perl -w
use strict;
use warnings;
use File::Slurp;

use HTML::FormatMarkdown;

if (@ARGV) {
	for my $html_file (@ARGV) {
		(my $md_file = $html_file) =~ s/\.html/.md/;
		if ($md_file eq $html_file) {
			warn "not a .html file: $html_file\n";
			next;
		}
		convert($html_file, $md_file);
	}
} else {
	convert(\*STDIN, \*STDOUT);
}

sub open_file {
	my ($file, $mode) = @_;
	$mode ||= "<";
	if (ref $file) {
		return $file;
	}
	if (-e $file && $mode ne "<") {
		die "file already exists: $file\n";
	}
	open my $fh, $mode, $file
		or die "open failed: $file: $!\n";
	return $fh;
}

sub convert {
	my ($from, $to) = @_;
	$from = open_file($from);
	$to = open_file($to, ">");
	print $to HTML::FormatMarkdown->format_file($from);
}
