/* p_util.c
 * Copyright (C) 1997-98 Thomas Merz. All rights reserved.
 *
 * PDFlib utility routines
 */

#include <math.h>
#include <string.h>

#include "p_intern.h"

/* 
 * Note: although PDF doesn't impose any restrictions on
 * the usable page size, Acrobat Reader and Exchange suffer
 * from an architectural limit which allows pages to
 * use sizes from 1 inch to 45 inches only (72-3240 pt, 2.54-114.3 cm).
 */

PDF_pagesize 
    a0		= {2380, 3368},		/* a0 is unusable in Acrobat 3! */
    a1		= {1684, 2380},
    a2		= {1190, 1684},
    a3		= {842, 1190},
    a4		= {595, 842},
    a5		= {421, 595},
    a6		= {297, 421},
    b5		= {501, 709},
    letter	= {612, 792},
    legal 	= {612, 1008},
    ledger	= {1224, 792},
    p11x17	= {792, 1224};

#define NO_OF_BUFS	6	/* number of static format buffers */

static char buf_array[NO_OF_BUFS][20];
static int current_buf = 0;

/* Format floating point numbers in a PDF compatible way.
 * This must be used for all floating output since PDF doesn't
 * allow %g exponential format and %f produces too many characters
 * in most cases.
 * PDF spec says "use four or five decimal places".
 *
 * WARNING: This function uses a small number of cyclically reused
 * static buffers. Don't use more than this number of pdf_float calls
 * inside printf() or other function calls!!!
 */

char *
pdf_float(float f)
{
    char *buf = buf_array[(current_buf++) % NO_OF_BUFS];

    if (fabs(f) < 0.00001)
	return "0";			/* force very small numbers to zero   */

    sprintf(buf, "%.4g", f);		/* try %g first and then check output */

    if (strchr(buf, 'e')) {		/* this format is not PDF compatible  */
	if (fabs(f) < 1)
	    sprintf(buf, "%1.5f", f);	/* 5 decimal places for small numbers */
	else if (fabs(f) < 1000)
	    sprintf(buf, "%1.2f", f);	/* 2 decimal places for medium numbers*/
	else
	    sprintf(buf, "%1.0f", f);	/* skip decimal places for big numbers*/
    }

    return buf;
}
