/*
    0xFFFF - Open Free Fiasco Firmware Flasher
    Copyright (C) 2013  Pali Rohár <pali.rohar@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 3 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, see <http://www.gnu.org/licenses/>.

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NAME "0xFFFF"
#define INFO NAME " \\- Open Free Fiasco Firmware Flasher, version " VERSION
#define DESCRIPTION "0xFFFF is Open Free Fiasco Firmware Flasher for Maemo devices. It support generating and unpacking FIASCO images on local computer. Useful for editing Maemo firmware package for future flash. It support via USB flashing any image type to Maemo device and also \"cold\" flashing which means flashing dead device with erased bootloader. There is support for booting kernel via USB without flashing to NAND and also changing configuration of Maemo device (enable/disable R&D mode, changing HW revision strings, ...).\n\n0xFFFF is alternative tool to proprietary Nokia flasher-3.5 and fiasco-gen. 0xFFFF generate compatible FIASCO images and also accept FIASCO images generated by Nokia fiasco-gen."

#ifndef BUILD_DATE
#define BUILD_DATE __DATE__
#endif

int main() {

	FILE * pipe;
	char buf[1024];

	pipe = popen("./0xFFFF -h", "r");
	if ( ! pipe )
		return 1;

	puts(".TH " NAME " 1 \"" BUILD_DATE "\" \"" NAME " " VERSION "\"");
	puts("");

	puts(".SH NAME");
	puts(INFO);
	puts("");

	puts(".SH SYNOPSIS");
	puts(".B " NAME);
	puts(".I [options]");
	puts("");

	puts(".SH DESCRIPTION");
	puts(DESCRIPTION);

	while ( fgets(buf, sizeof(buf), pipe) ) {

		if ( ! buf[0] )
			continue;

		if ( buf[0] == ' ' && buf[2] == ' ' ) {

			char * ptr = buf;

			while ( *ptr && *ptr == ' ' )
				++ptr;

			if ( ! *ptr )
				continue;

			printf(".br\n%s", ptr);

		} else if ( buf[0] == ' ' ) {

			char * ptr = buf;
			char * ptr2;

			while ( *ptr && *ptr == ' ' )
				++ptr;

			if ( ! *ptr )
				continue;

			ptr2 = ptr;

			while ( *ptr2 && ( *ptr2 != ' ' || *(ptr2-1) != ' ' ) )
				++ptr2;

			*(ptr2-1) = 0;

			while ( *ptr2 && *ptr2 == ' ' )
				++ptr2;

			if ( *ptr2 )
				printf(".TP\n.B %s\n%s", ptr, ptr2);
			else
				printf(".br\n%s\n", ptr);

		} else if ( buf[strlen(buf)-2] == ':' ) {

			printf("\n.SH %s\n", buf);

		}

	}

	pclose(pipe);
	return 0;

}
