aboutsummaryrefslogtreecommitdiffstats
path: root/sdk/other/picture.c
blob: 3ff2dbada7fba40fcf129fbb6bdff7d0aadcef50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
 * String formatting of numeric data.
 * $Id$
 * Copyright (c) 1997 by Tycho Softworks.
 * For conditions of distribution and reuse see product license.
 */

#include <std/string.h>

char	*picture(char *buf, const char *pict, long value)
{
	char	*bp = buf, *tp;
	long	shift = 0;
	int	sign = 0;
	int	zfill = 0;
	int	digit;
	int	currency = 0;
	int	digits = 0;
	
	if(value < 0)
	{
		++sign;
		value = -value;
	}
	
	while(*pict)
	{
		switch(*pict)
		{
		case '$':
			++currency;
			*(bp++) = ' ';
			++pict;
			break;
		case '+':
			if(sign)
				*(bp++) = ' ';
			else
				*(bp++) = '+';
			++pict;
			break;
		case '-':
			if(sign)
				*(bp++) = '-';
			else
				*(bp++) = ' ';
			++pict;
			break;
		case '9':
		case '0':
			shift *= 10;
			if(!shift)
				shift = 1;
		default:
			*(bp++) = *(pict++);
		}
	}
	if(value >= shift * 10)
	{				
		bp = buf;
		while(*bp)
		{
			if(isdigit(*bp))
				*bp = '#';
			++bp;
		}
		return buf;
	}
	bp = tp = buf;
	while(*bp)
	{
		switch(*bp)
		{
		case ',':
			if(*(bp - 1) == '#')
			{
				*bp = '#';
				break;
			}
			if(!zfill)
				*bp = ' ';
			break;
		case '#':
			if(!digits)
				if(shift > value)
					break;	
		case '0':
			++zfill;
		case '9':
			++digits;
			digit = (int)(value / shift);
			if((digit > 0) || (shift == 1))
				++zfill;
			if(!zfill && !digit)
				digit = (int)(' ' - '0');				
			*bp = (char)('0' + digit);
			if(isdigit(*bp) && currency)
			{
				currency = 0;
				*(tp - 1) = '$';
			}
			value %= shift;
			shift /= 10;
		}
		if(*bp != '#')
			*(tp++) = *bp;
		++bp;
	}
	*tp = 0;
	return buf;
}