5 inline int clip(int v, int mn, int mx) { return v<mn ? mn : v>mx ? mx : v; }
7 void hist_eq(unsigned char *dp, int len)
9 int hist[256], map[256];
10 for( int i=0; i<256; ++i ) hist[i] = 0, map[i] = -1;
11 unsigned char *bp = dp;
12 for( int i=len; --i>=0; ++bp ) ++hist[*bp];
13 double v = 0, dv = len/256.;
14 for( int i=0,j=0,t=0; i<256; ++i ) {
16 while( t < k ) { map[j] = i; t += hist[j++]; }
18 //for( int i=0; i<256; ++i ) fprintf(stderr,"%d\n",map[i]);
19 for( int i=len; --i>=0; ++dp ) *dp = map[*dp];
22 int main(int ac, char **av)
24 FILE *ifp = !strcmp(av[1],"-") ? stdin : fopen(av[1],"r");
25 FILE *ofp = !strcmp(av[2],"-") ? stdout : fopen(av[2],"w");
27 fgets(line,sizeof(line),ifp); fputs(line,ofp);
28 fgets(line,sizeof(line),ifp); fputs(line,ofp);
29 int w, h; if( sscanf(line,"%d %d\n",&w,&h) != 2 ) exit(1);
30 fgets(line,sizeof(line),ifp); fputs(line,ofp);
32 unsigned char data[len], *bp = data;
33 for( int ch, i=len; --i>=0 && (ch=getc(ifp)) >= 0; ++bp ) *bp = ch;
34 for( int i=1; --i>=0; ) hist_eq(data,len);
36 for( int i=len; --i>=0; ++bp ) putc(*bp,ofp);
38 if( ifp != stdin ) fclose(ifp);
39 if( ofp != stdout ) fclose(ofp);