#include <stdarg.h>
#include <stdio.h>
#include "c-pair.h"
#include "c-print.h"

void print_string(FILE* out, const char* x) { fprintf(out, "%s", x); }

void print_bool(FILE* out, _Bool x) { fprintf(out, "%s", x ? "true" : "false"); }

void print_char(FILE* out, char x) {
	if ( 0x20 <= x && x <= 0x7E ) { fprintf(out, "'%c'", x); }
	else { fprintf(out, "'\\%x'", x); }
}

void print_int(FILE* out, int x) { fprintf(out, "%d", x); }

void print_fmt(FILE* out, char fmt, void* p) {
	switch( fmt ) {
	case 's': print_string(out, (const char*)p); break; /***/
	case 'b': print_bool(out, *(_Bool*)p); break; /***/
	case 'c': print_char(out, *(char*)p); break; /***/
	case 'd': print_int(out, *(int*)p); break; /***/
	}
}

void print(FILE* out, const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);
	for (const char* it = fmt; *it; ++it) {
		switch( *it ) {
		case 's': print_string(out, va_arg(args, const char*)); break; /***/
		case 'b': print_bool(out, va_arg(args, int)); break; /***/
		case 'c': print_char(out, va_arg(args, int)); break; /***/
		case 'd': print_int(out, va_arg(args, int)); break; /***/
		case 'p': {
			const struct pair x = va_arg(args, const struct pair); /***/
			fprintf(out, "[");
			print_fmt(out, *++it, x.first); /***/
			fprintf(out, ", ");
			print_fmt(out, *++it, x.second); /***/
			fprintf(out, "]");
			break;
		}
		}
	}
	va_end(args);
}
