Check-in [1c8063223f]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Added Dithering and General Dithering algorithms...
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:1c8063223fd76cef7213631f0dd3ff7277b3a996
User & Date: user 2014-02-02 18:58:40
Context
2014-02-02
19:00
Added missed files for last commit check-in: 5a4be18db7 user: user tags: trunk
18:58
Added Dithering and General Dithering algorithms... check-in: 1c8063223f user: user tags: trunk
2013-09-29
20:08
Changed matrix in morph. edges (test14.scm) check-in: 24f89f1403 user: user tags: trunk
Changes

Changes to Makefile.

6
7
8
9
10
11
12




13
14
15
16
17
18
19
20
21
22
23
24
25

$(SIOD_LIB): $(SIOD_OBJS)
	ar rcs -o $(SIOD_LIB) $?

imsh: imsh.o $(SIOD_LIB) -lfreeimage
	$(CC) -o $@ $^





.PHONY: test
tests = $(wildcard test[0-9]*.scm)
test: imsh
	@echo "Do tests:"
	@echo "========="
	@$(foreach f,$(tests),./imsh $f;)

.PHONY: cleanout
cleanout:
	-$(RM) out/*.*

.PHONY: clean
clean:







>
>
>
>





|







6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

$(SIOD_LIB): $(SIOD_OBJS)
	ar rcs -o $(SIOD_LIB) $?

imsh: imsh.o $(SIOD_LIB) -lfreeimage
	$(CC) -o $@ $^

test%: imsh
	@echo ">>> Do $@.scm..."
	@./imsh $@.scm

.PHONY: test
tests = $(wildcard test[0-9]*.scm)
test: imsh
	@echo "Do tests:"
	@echo "========="
	@$(foreach f,$(tests),echo ">>> Do $f..."; ./imsh $f;)

.PHONY: cleanout
cleanout:
	-$(RM) out/*.*

.PHONY: clean
clean:

Deleted conv.scm.

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
(define blur-matrix '(1 1 1 1 1 1 1 1 1))
(define blur-div 9)
(define blur-shift 0)

(define motion-matrix
  '(1 0 0 0 0 0 0 0 0
    0 1 0 0 0 0 0 0 0
    0 0 1 0 0 0 0 0 0
    0 0 0 1 0 0 0 0 0
    0 0 0 0 1 0 0 0 0
    0 0 0 0 0 1 0 0 0
    0 0 0 0 0 0 1 0 0
    0 0 0 0 0 0 0 1 0
    0 0 0 0 0 0 0 0 1))
(define motion-div 10)
(define motion-shift 0)

(define edge-matrix '(-1 -1 -1 -1 8 -1 -1 -1 -1))
(define edge-div 1)
(define edge-shift 0)

(define edge1-matrix '(0 1 0 1 -4 1 0 1 0))
(define edge1-div 1)
(define edge1-shift 0)

(define edge2-matrix '(0 9 0 9 -36 9 0 9 0))
(define edge2-div 9)
(define edge2-shift 0)

(define sharpen-matrix '(-1 -1 -1 -1 9 -1 -1 -1 -1))
(define sharpen-div 1)
(define sharpen-shift 0)

(define dilat-matrix '(0 1 0 1 1 1 0 1 0))
(define dilat-div 1)
(define dilat-shift 0)

(define sharpen1-matrix '(0 -3 0 -3 21 -3 0 -3 0))
(define sharpen1-div 9)
(define sharpen1-shift 0)

(define sharpen2-matrix '(1 1 1 1 -7 1 1 1 1))
(define sharpen2-div 1)
(define sharpen2-shift 0)

(define lighten-matrix '(0 0 0 0 12 0 0 0 0))
(define lighten-div 9)
(define lighten-shift 0)

(define darken-matrix '(0 0 0 0 6 0 0 0 0))
(define darken-div 9)
(define darken-shift 0)

(define unsharpen-matrix '(-1 -1 -1 -1 17 -1 -1 -1 -1))
(define unsharpen-div 9)
(define unsharpen-shift 0)

(define emboss-matrix '(-2 0 0 0 1 0 0 0 2))
(define emboss-div 1)
(define emboss-shift 0)

(define emboss1-matrix '(-2 -1 0 -1 1 1 0 1 2))
(define emboss1-div 1)
(define emboss1-shift 0)

(define gauss-matrix
  '(2 4 5 4 2
    4 9 12 9 4
    5 12 15 12 5
    4 9 12 9 4
    2 4 5 4 1))
(define gauss-div 159)
(define gauss-shift 0)
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































Changes to imsh.c.

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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
...
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648


















































































































































































































































































































































649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878























































879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005


1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <stdint.h>
#include <stdbool.h>
#include <siod.h>
#include <freeimage.h>

#ifdef __GNUC__
#define MIN(a,b) \
   ({ __typeof__ (a) _a = (a); \
       __typeof__ (b) _b = (b); \
     _a > _b ? _b : _a; })
#define MAX(a,b) \
   ({ __typeof__ (a) _a = (a); \
       __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })
#else
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif



// TODO check all return values of FreeImage_*()

typedef FIBITMAP IMG;
typedef struct pt2_t pt2_t;


/// Point coordinates in 2D
struct pt2_t {
        int x;
        int y;






};

/// Type of IMG Lisp object
long tc_img = 0;

/// Some functions' declarations
static IMG* LISP2IMG(LISP ptr);
static void polygon_coords(unsigned int n, int cx, int cy, unsigned int r, int angle, pt2_t *coords);

static void init_imsh_version(void) {
        setvar(cintern("*imsh-version*"),
               cintern("$Id: imsh.c,v 1.0 2013/08/26 py-dev $"),
               NIL);








}

// Image processing algorithms {{{
// ---------------------------------------------------------------------------

/** Calculates coordinates of each node of regular polygon
 */
static void polygon_coords(unsigned int n, int cx, int cy, unsigned int r,
                int angle, pt2_t *coords)
{
        int i;
        for (i=0; i<n-1; i++) {
                coords[i].x = cx + r*cos(angle + 2*M_PI*i/n);
                coords[i].y = cy + r*sin(angle + 2*M_PI*i/n);
        }
}


/// Length of RGB vector
#define RGBLEN(RGBQ) sqrt( \
                + ((RGBQ)->rgbRed)*((RGBQ)->rgbRed) \
                + ((RGBQ)->rgbGreen)*((RGBQ)->rgbGreen) \
                + ((RGBQ)->rgbBlue)*((RGBQ)->rgbBlue))

/// Initialize RGB with colors components
#define RGBINIT(RGBQ, R, G, B) do { \
        (RGBQ)->rgbRed = (R); \
        (RGBQ)->rgbGreen = (G); \
        (RGBQ)->rgbBlue = (B); \
} while (0)

/// Initialize RGB with 255-colors components
#define RGBNEG256(RGBQ) do { \
        (RGBQ)->rgbRed = 255 - (RGBQ)->rgbRed; \
        (RGBQ)->rgbGreen = 255 - (RGBQ)->rgbGreen; \
        (RGBQ)->rgbBlue = 255 - (RGBQ)->rgbBlue; \
} while (0)

/// Selectors
#define RGB_R(RGBQ) ((RGBQ)->rgbRed)
#define RGB_G(RGBQ) ((RGBQ)->rgbGreen)
#define RGB_B(RGBQ) ((RGBQ)->rgbBlue)

















const RGBQUAD RGB_WHITE = {.rgbRed=255, .rgbGreen=255, .rgbBlue=255};
const RGBQUAD RGB_BLACK = {.rgbRed=0, .rgbGreen=0, .rgbBlue=0};
























/** Convert image to black-white
 * @param threshold the threshold of brightness in percents
 * @return 0 on success
 */
int algo_bw(IMG *img, int threshold)
{
        RGBQUAD rgb;
        unsigned int row, col, width, height;
        double rgbl, maxrgbl;

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height);

        maxrgbl = sqrt(255.*255. + 255.*255. + 255.*255.);

        for (row = 0; row < height; row++) {
                for (col = 0; col < width; col++) {
                        FreeImage_GetPixelColor(img, col, row, &rgb);
                        rgbl = RGBLEN(&rgb);
                        if (rgbl*100/maxrgbl > threshold) {
                                // light
                                FreeImage_SetPixelColor(img, col, row, (RGBQUAD*)&RGB_WHITE);
                        } else {
                                // dark
                                FreeImage_SetPixelColor(img, col, row, (RGBQUAD*)&RGB_BLACK);
                        }
                }
        }
        return (0);
}

/** grayscale image
 * @return 0 on success
 */
int algo_gr(IMG *img)
{
        RGBQUAD rgb;
        unsigned int row, col, width, height;
        double rgbl;
        uint8_t c;

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height);

        for (row = 0; row < height; row++) {
                for (col = 0; col < width; col++) {
                        FreeImage_GetPixelColor(img, col, row, &rgb);
                        rgbl = RGBLEN(&rgb);
                        c = rgbl/sqrt(3.);
                        RGBINIT(&rgb, c, c, c);
                        FreeImage_SetPixelColor(img, col, row, &rgb);
                }
        }
        return (0);
}

/** Negative
 */
int algo_neg(IMG *img)
{
        RGBQUAD rgb;
        unsigned int row, col, width, height;

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height);

        for (row = 0; row < height; row++) {
                for (col = 0; col < width; col++) {
                        FreeImage_GetPixelColor(img, col, row, &rgb);
                        RGBNEG256(&rgb);
                        FreeImage_SetPixelColor(img, col, row, &rgb);
                }
        }
        return (0);
}

/** Apply conv. matrix with size sideXside, use division, shifting, normalization.
 */
int algo_conv(IMG *img, int *matrix, int side, int div, int shift)
{
        RGBQUAD rgb;
        unsigned int row, col, i, j, width, height, cx, cy;
        uint8_t *res[3] = {NULL}; // Tmp working copies of bitmap for 3 chans
        int r1, g1, b1, margin, mi;

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height && div && matrix && side>2 && side%2);

        margin = side/2; // process central area, without margin
        // allocate tmp copies of channels
        for (i=0; i<3; i++) {
                res[i] = malloc(width*height*sizeof (uint8_t));
                if (!res[i]) {
                        while (i >= 0) free(res[i--]);
                        return (1);
                }
        }
        // processing
        for (row = margin; row < height-margin; row++) {
                for (col = margin; col < width-margin; col++) {
                        r1 = g1 = b1 = 0;
                        for (j = 0; j < side; j++) {
                                cy = row - margin + j;
                                for (i = 0; i < side; i++) {
                                        cx = col - margin + i;
                                        FreeImage_GetPixelColor(img, cx, cy, &rgb);
                                        mi = j*side + i;
                                        r1 += RGB_R(&rgb) * matrix[mi];
                                        g1 += RGB_G(&rgb) * matrix[mi];
                                        b1 += RGB_B(&rgb) * matrix[mi];
                                }
                        }
#define __NORM_RGB(C) (C)=shift+(C)/div; (C)=(C)<0? 0 : (C)>255? 255 : (C)
                        __NORM_RGB(r1);
                        __NORM_RGB(g1);
                        __NORM_RGB(b1);
#undef __NORM_RGB
                        mi = row*width + col;
                        *(res[0] + mi) = (uint8_t)r1;
                        *(res[1] + mi) = (uint8_t)g1;
                        *(res[2] + mi) = (uint8_t)b1;
                }
        }
        // copy to original img data from tmp copies, margin is unchanged
        for (row = margin; row < height-margin; row++) {
                for (col = margin; col < width-margin; col++) {
                        RGBINIT(&rgb,
                                        *(res[0] + row*width + col),
                                        *(res[1] + row*width + col),
                                        *(res[2] + row*width + col));
                        FreeImage_SetPixelColor(img, col, row, &rgb);
                }
        }
        // free tmp copies
        for (i=0; i<3; i++) free(res[i]);
        return (0);
}

/** Select only channels with bit-mask: chans is -----RGB byte,
 * so 7 select 3 chans
 */
int algo_ch(IMG *img, int chans)
{
        RGBQUAD rgb;
        unsigned int row, col, width, height;
        uint32_t mask;
        uint32_t rgb32;
        uint8_t r, g, b;

#define _R_ RGB_R(&rgb)
#define _G_ RGB_G(&rgb)
#define _B_ RGB_B(&rgb)

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height);

        // 00RRGGBB, so 1 is chans bits are '...RGB'
        mask = ((chans & 4)? 0xFF0000 : 0)
             | ((chans & 2)? 0xFF00 : 0)
             | ((chans & 1)? 0xFF : 0);
        for (row = 0; row < height; row++) {
                for (col = 0; col < width; col++) {
                        FreeImage_GetPixelColor(img, col, row, &rgb);
                        rgb32 = mask & ((_R_<<16)|(_G_<<8)|_B_);
                        _R_ = (rgb32 & 0xFF0000)>>16;
                        _G_ = (rgb32 & 0xFF00)>>8;
                        _B_ = rgb32 & 0xFF;
                        FreeImage_SetPixelColor(img, col, row, &rgb);
                }
        }
        return (0);

#undef _R_
#undef _G_
#undef _B_
}

/** Convert image to gray levels
 * @param nlevels is number of levels (gradation)
 */
int algo_grl(IMG *img, int nlevels)
{
        RGBQUAD rgb;
        unsigned int row, col, width, height,
                     rgbl, maxrgbl, band;
        uint8_t c;

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height && nlevels>=2);

        maxrgbl = sqrt(255.*255. + 255.*255. + 255.*255.);
        band = maxrgbl/nlevels;

        for (row = 0; row < height; row++) {
                for (col = 0; col < width; col++) {
                        FreeImage_GetPixelColor(img, col, row, &rgb);
                        rgbl = (int)RGBLEN(&rgb);
                        rgbl = band*(rgbl/band);
                        c = rgbl/sqrt(3.);
                        RGBINIT(&rgb, c, c, c);
                        FreeImage_SetPixelColor(img, col, row, &rgb);
                }
        }
        return (0);
}

/** Pixalization of image.
 * @param side is side of square-pixel
 * @param color is 1 or 0 to generate color or black-and-white "pixels"
 * @return 0 on success
 */
int algo_pix(IMG *img, int side, int color)
{
        RGBQUAD rgb;
        unsigned int row, col, irow, icol, width, height;
        unsigned long rs, gs, bs, pixarea, maxrgbl_2;

#define _R_ RGB_R(&rgb)
#define _G_ RGB_G(&rgb)
#define _B_ RGB_B(&rgb)

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height && side>0);

        pixarea = side*side;
        if (!color) maxrgbl_2 = sqrt(255.*255. + 255.*255. + 255.*255.)/2;
        for (row = 0; row < height; row += side) {
                for (col = 0; col < width; col += side) {
                        rs = gs = bs = 0;
                        for (irow = row; irow < row+side; irow++) {
                                for (icol = col; icol < col+side; icol++) {
                                        FreeImage_GetPixelColor(img, icol, irow, &rgb);
                                        rs += _R_;
                                        gs += _G_;
                                        bs += _B_;
                                }
                        }
                        _R_ = rs / pixarea;
                        _G_ = gs / pixarea;
                        _B_ = bs / pixarea;
                        if (!color) {
                                if (RGBLEN(&rgb) > maxrgbl_2) {
                                        rgb = (RGBQUAD)RGB_WHITE;
                                } else {
                                        rgb = (RGBQUAD)RGB_BLACK;
                                }

                        }
                        for (irow = row; irow < row+side; irow++) {
                                for (icol = col; icol < col+side; icol++) {
                                        FreeImage_SetPixelColor(img, icol, irow, &rgb);
                                }
                        }
                }
        }
        return (0);

#undef _R_
#undef _G_
#undef _B_
}

static int _median_cmpf(void const *x, void const *y)
{
        return (*(uint8_t*)x - *(uint8_t*)y);
}

/** Median filter with specified side
 */
int algo_med(IMG *img, int side)
{
        RGBQUAD rgb;
        unsigned int row, col, i, j, k, width, height, cx, cy;
        // Tmp working copies of bitmap for 3 chans and buffer for sorting (win)
        uint8_t *res[3] = {NULL}, *win[3] = {NULL};
        int margin, middle, result = 0, mi;

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height && side>2 && side%2);

        margin = side/2; // process central area, without margin
        middle = 1 + side*side/2; // middle element in sorted buffer (win[i])
        // allocate tmp copies of channels
        for (i=0; i<3; i++) {
                res[i] = malloc(width*height*sizeof (uint8_t));
                if (!res[i]) {
                        result = 1;
                        goto free_bufs;
                }
        }
        // allocate win buffers
        for (i=0; i<3; i++) {
                win[i] = malloc(side*side*sizeof (uint8_t));
                if (!win[i]) {
                        result = 1;
                        goto free_bufs;
                }
        }
        // processing
        for (row = margin; row < height-margin; row++) {
                for (col = margin; col < width-margin; col++) {
                        k = 0;
                        for (j = 0; j < side; j++) {
                                cy = row - margin + j;
                                for (i = 0; i < side; i++) {
                                        cx = col - margin + i;
                                        FreeImage_GetPixelColor(img, cx, cy, &rgb);
                                        *(win[0] + k) = RGB_R(&rgb);
                                        *(win[1] + k) = RGB_G(&rgb);
                                        *(win[2] + k) = RGB_B(&rgb);
                                        k++;
                                }
                        }
                        qsort(win[0], k, sizeof win[0][0], _median_cmpf);
                        qsort(win[1], k, sizeof win[1][0], _median_cmpf);
                        qsort(win[2], k, sizeof win[2][0], _median_cmpf);
                        mi = row*width + col;
                        *(res[0] + mi) = win[0][middle];
                        *(res[1] + mi) = win[1][middle];
                        *(res[2] + mi) = win[2][middle];
                }
        }
        // copy to original img data from tmp copies, margin is unchanged
        for (row = margin; row < height-margin; row++) {
                for (col = margin; col < width-margin; col++) {
                        mi = row*width + col;
                        RGBINIT(&rgb, *(res[0] + mi), *(res[1] + mi), *(res[2] + mi));
                        FreeImage_SetPixelColor(img, col, row, &rgb);
                }
        }
free_bufs:
        for (i=0; i<3; i++) {
                if (res[i]) {
                        free(res[i]);
                        res[i] = NULL;
                }
                if (win[i]) {
                        free(win[i]);
                        win[i] = NULL;
                }
        }
        return (result);
}

/** Binary dilate and erode generic implementation */
#define _ERODE_DILATE_GENERIC_ALGO() do { \
        RGBQUAD rgb; \
        unsigned int row, col, i, j, width, height, cx, cy; \
        uint8_t *res[3] = {NULL}; /* Tmp working copies of bitmap for 3 chans */ \
        int margin, mi; \
        bool detected; \
	width = FreeImage_GetWidth(img); \
	height = FreeImage_GetHeight(img); \
 \
        assert(img && width && height && matrix && side>2 && side%2); \
 \
        /* Process central area, without margin. Also margin is middle point, for side=5, middle is 2: 0,1,[2],3,4 */ \
        margin = side/2; \
        /* allocate tmp copies of channels */ \
        for (i=0; i<3; i++) { \
                res[i] = malloc(width*height*sizeof (uint8_t)); \
                if (!res[i]) { \
                        while (i >= 0) free(res[i--]); \
                        return (1); \
                } \
        } \
        /* processing */ \
        for (row = margin; row < height-margin; row++) { \
                for (col = margin; col < width-margin; col++) { \
                        detected = false; \
                        for (j = 0; j < side; j++) { \
                                cy = row - margin + j; \
                                for (i = 0; i < side; i++) { \
                                        cx = col - margin + i; \
                                        if (j == margin && i == margin) { \
                                                /* if center point */ \
                                                continue; \
                                        } else { \
                                                mi = j*side + i; \
                                                FreeImage_GetPixelColor(img, cx, cy, &rgb); \
                                                if (matrix[mi] \
                                                        && (__ISCOND(RGB_R(&rgb)) \
                                                            || __ISCOND(RGB_G(&rgb)) \
                                                            || __ISCOND(RGB_B(&rgb)))) { \
                                                        detected = true; \
                                                        goto _detected; \
                                                } \
                                        } \
                                } \
                        } \
_detected: \
                        mi = row*width + col; \
                        if (detected) { \
                                *(res[0] + mi) = *(res[1] + mi) = *(res[2] + mi) = __RESYES; \
                        } else { \
                                *(res[0] + mi) = (-1==__RESNO)? RGB_R(&rgb) : __RESNO; \
                                *(res[1] + mi) = (-1==__RESNO)? RGB_G(&rgb) : __RESNO; \
                                *(res[2] + mi) = (-1==__RESNO)? RGB_B(&rgb) : __RESNO; \
                        } \
                } \
        } \
        /* copy to original img data from tmp copies, margin is unchanged */ \
        for (row = margin; row < height-margin; row++) { \
                for (col = margin; col < width-margin; col++) { \
                        RGBINIT(&rgb, \
                                        *(res[0] + row*width + col), \
                                        *(res[1] + row*width + col), \
                                        *(res[2] + row*width + col)); \
                        FreeImage_SetPixelColor(img, col, row, &rgb); \
                } \
        } \
        /* free tmp copies */ \
        for (i=0; i<3; i++) free(res[i]); \
} while (0)

/**
 * Binary dilate
 */
int algo_bindilate(IMG *img, int *matrix, int side)
{
#define __RESYES 255
#define __RESNO 0
#define __ISCOND(X) ((X)!=0)

        _ERODE_DILATE_GENERIC_ALGO();
        return (0);

#undef __RESYES
#undef __RESNO
#undef __ISCOND
}

/**
................................................................................
 */
int algo_binerode(IMG *img, int *matrix, int side)
{
#define __RESYES 0
#define __RESNO 255
#define __ISCOND(X) ((X)==0)

        _ERODE_DILATE_GENERIC_ALGO();
        return (0);

#undef __RESYES
#undef __RESNO
#undef __ISCOND
}

/** For binary operations on pixels as sets */

/* all channels should has the same values */
#define __GETBIT(Q) ((RGB_R(Q)!=0)?(-1):0)
#define __SETBIT(Q, B) do { \
        if (B) { \
                RGBINIT(Q, 255, 255, 255); \
        } else  { \
                RGBINIT(Q, 0, 0, 0); \
        } \
} while (0)

/**
 * Binary monadic not operation. img is in/out.
 */
int algo_binnot(IMG *img)
{
        RGBQUAD rgb;
        unsigned int row, col, width, height;

	width = FreeImage_GetWidth(img);
	height = FreeImage_GetHeight(img);

        assert(img && width && height);

        // processing
        for (row = 0; row < height; row++) {
                for (col = 0; col < width; col++) {
                        FreeImage_GetPixelColor(img, col, row, &rgb);
                        __SETBIT(&rgb, ~__GETBIT(&rgb));
                        FreeImage_SetPixelColor(img, col, row, &rgb);
                }
        }
        return (0);
}

/**
 * Binary dyadic operations, result set to first.
 * op is:
 *      & - AND
 *      | - OR
 *      ^ - XOR
 *      / - SUB (X but not Y)
 */
int algo_binop2(char op, IMG *img1, IMG *img2)
{
        RGBQUAD rgb1, rgb2;
        unsigned int row, col, width1, height1, width2, height2,
                     wbound, hbound;

	width1 = FreeImage_GetWidth(img1);
	height1 = FreeImage_GetHeight(img1);

	width2 = FreeImage_GetWidth(img2);
	height2 = FreeImage_GetHeight(img2);

        assert(img1 && img2 && width1 && height1 && width2 && height2);

        wbound = MIN(width1, width2);
        hbound = MIN(height1, height2);

        // processing
        for (row = 0; row < hbound; row++) {
                for (col = 0; col < wbound; col++) {
                        FreeImage_GetPixelColor(img1, col, row, &rgb1);
                        FreeImage_GetPixelColor(img2, col, row, &rgb2);
                        switch (op) {
                                case '&':
                                        __SETBIT(&rgb1, __GETBIT(&rgb1) & __GETBIT(&rgb2));
                                break;

                                case '|':
                                        __SETBIT(&rgb1, __GETBIT(&rgb1) | __GETBIT(&rgb2));
                                break;

                                case '^':
                                        __SETBIT(&rgb1, __GETBIT(&rgb1) ^ __GETBIT(&rgb2));
                                break;

                                case '/':
                                        __SETBIT(&rgb1, __GETBIT(&rgb1) & (__GETBIT(&rgb1) ^ __GETBIT(&rgb2)));
                                break;
                        }
                        FreeImage_SetPixelColor(img1, col, row, &rgb1);
                }
        }
        return (0);
}

#undef __GETBIT
#undef __SETBIT



















































































































































































































































































































































// ---------------------------------------------------------------------------
// }}}

// Algorithms wrappers {{{
// ---------------------------------------------------------------------------

LISP img_bw(LISP img, LISP threshold)
{
        IMG *_img = NULL;
        long _threshold;

        _img = LISP2IMG(img);
        _threshold = get_c_long(threshold);
        if (!algo_bw(_img, (int)_threshold))
                return (a_true_value());
        else return (NIL);
}

LISP img_gr(LISP img)
{
        IMG *_img = NULL;

        _img = LISP2IMG(img);
        if (!algo_gr(_img))
                return (a_true_value());
        else return (NIL);
}

LISP img_neg(LISP img)
{
        IMG *_img = NULL;

        _img = LISP2IMG(img);
        if (!algo_neg(_img))
                return (a_true_value());
        else return (NIL);
}

LISP img_conv(LISP img, LISP matrix, LISP div, LISP shift)
{
        IMG *_img = NULL;
        LISP res, l;
        long _div, _shift;
        int *_matrix = NULL, matrix_len, side, i;

        matrix_len = nlength(matrix);
        side = sqrt(matrix_len);
        _matrix = malloc(matrix_len*sizeof(int));
        if (!_matrix) {
                res = err(__func__, llast_c_errmsg(-1));
                goto end;
        }
        for (l=matrix, i=0; i<matrix_len /*&& NNULLP(l)*/; l=cdr(l), i++) {
                _matrix[i] = get_c_long(car(l));
        }
        _img = LISP2IMG(img);
        _div = get_c_long(div);
        _shift = get_c_long(shift);
        if (!algo_conv(_img, _matrix, side, (int)_div, (int)_shift)) {
                res = a_true_value();
                goto free_matrix;
        } else {
                res = NIL;
                goto free_matrix;
        }
free_matrix:
        free(_matrix);
end:
        return (res);
}

LISP img_ch(LISP img, LISP channels)
{
        IMG *_img = NULL;
        long _channels;

        _img = LISP2IMG(img);
        _channels = get_c_long(channels);
        if (!algo_ch(_img, (int)_channels))
                return (a_true_value());
        else return (NIL);
}

LISP img_grl(LISP img, LISP nlevels)
{
        IMG *_img = NULL;
        long _nlevels;

        _img = LISP2IMG(img);
        _nlevels = get_c_long(nlevels);
        if (!algo_grl(_img, (int)_nlevels))
                return (a_true_value());
        else return (NIL);
}

LISP img_pix(LISP img, LISP side, LISP color)
{
        IMG *_img = NULL;
        long _side, _color;

        _img = LISP2IMG(img);
        _side = get_c_long(side);
        _color = get_c_long(color);
        if (!algo_pix(_img, (int)_side, (int)_color))
                return (a_true_value());
        else return (NIL);
}

LISP img_med(LISP img, LISP side)
{
        IMG *_img = NULL;
        long _side;

        _img = LISP2IMG(img);
        _side = get_c_long(side);
        if (!algo_med(_img, (int)_side))
                return (a_true_value());
        else return (NIL);
}

LISP img_bindilate(LISP img, LISP matrix)
{
        IMG *_img = NULL;
        LISP res, l;
        int *_matrix = NULL, matrix_len, side, i;

        matrix_len = nlength(matrix);
        _matrix = malloc(matrix_len*sizeof(int));
        if (!_matrix) {
                res = err(__func__, llast_c_errmsg(-1));
                goto end;
        }
        side = sqrt(matrix_len);
        for (l=matrix, i=0; i<matrix_len; l=cdr(l), i++) {
                _matrix[i] = get_c_long(car(l));
        }
        _img = LISP2IMG(img);
        if (!algo_bindilate(_img, _matrix, side)) {
                res = a_true_value();
                goto free_matrix;
        } else {
                res = NIL;
                goto free_matrix;
        }
free_matrix:
        free(_matrix);
end:
        return (res);
}

LISP img_binerode(LISP img, LISP matrix)
{
        IMG *_img = NULL;
        LISP res, l;
        int *_matrix = NULL, matrix_len, side, i;

        matrix_len = nlength(matrix);
        _matrix = malloc(matrix_len*sizeof(int));
        if (!_matrix) {
                res = err(__func__, llast_c_errmsg(-1));
                goto end;
        }
        side = sqrt(matrix_len);
        for (l=matrix, i=0; i<matrix_len; l=cdr(l), i++) {
                _matrix[i] = get_c_long(car(l));
        }
        _img = LISP2IMG(img);
        if (!algo_binerode(_img, _matrix, side)) {
                res = a_true_value();
                goto free_matrix;
        } else {
                res = NIL;
                goto free_matrix;
        }
free_matrix:
        free(_matrix);
end:
        return (res);
}

#define _GENERAL_BINOP() do { \
        IMG *_img1 = NULL, *_img2 = NULL; \
\
        _img1 = LISP2IMG(img1); \
        _img2 = LISP2IMG(img2); \
        if (!algo_binop2(__OP, _img1, _img2)) \
                return (a_true_value()); \
        else \
                return (NIL); \
} while (0)

// and or xor sub
LISP img_binand(LISP img1, LISP img2)
{
#define __OP '&'
        _GENERAL_BINOP();
#undef __OP
}

LISP img_binor(LISP img1, LISP img2)
{
#define __OP '|'
        _GENERAL_BINOP();
#undef __OP
}

LISP img_binxor(LISP img1, LISP img2)
{
#define __OP '^'
        _GENERAL_BINOP();
#undef __OP
}

LISP img_binsub(LISP img1, LISP img2)
{
#define __OP '/'
        _GENERAL_BINOP();
#undef __OP
}

LISP img_binnot(LISP img)
{
        IMG *_img = NULL;

        _img = LISP2IMG(img);
        if (!algo_binnot(_img))
                return (a_true_value());
        else
                return (NIL);
}
























































// ---------------------------------------------------------------------------
// }}}

// Common IMG wrappers {{{
// ---------------------------------------------------------------------------

/** Convert internal lisp object to stored there IMG pointer
 */
static IMG* LISP2IMG(LISP ptr)
{
        if (NTYPEP(ptr, tc_img)) err("not a IMG", ptr);
        if (!ptr->storage_as.string.data) err("IMG deallocated", ptr);
        else return ((IMG*)ptr->storage_as.string.data);
}

void _img_gc_free(LISP ptr)
{
        IMG *img;
        if ((img = LISP2IMG(ptr)))
                FreeImage_Unload(img);
        ptr->storage_as.string.data = NULL;
}

void _img_print(LISP ptr, struct gen_printio *f)
{
        char buf[16];
        IMG *img;
        img = LISP2IMG(ptr);
        sprintf(buf, "#<IMG %p>", img);
        gput_st(f, buf);
}

/** Load IMG from file
 */
LISP img_open(LISP fname)
{
        IMG *img = NULL;
        LISP res;
        long intflag;
        char *_fname;
        FREE_IMAGE_FORMAT fif;
        
        _fname = get_c_string(fname);

        intflag = no_interrupt(1);
        fif = FreeImage_GetFileType(_fname, 0);
        if (fif == FIF_UNKNOWN) {
                fif = FreeImage_GetFIFFromFilename(_fname);
                if (fif == FIF_UNKNOWN) {
                        // fif can not be determined
                        res = err(__func__, llast_c_errmsg(-1));
                        goto end;
                }
        }
        img = FreeImage_Load(fif, _fname, 0);
        if (!img) {
                res = err(__func__, llast_c_errmsg(-1));
        } else {
                res = cons(NIL, NIL);
                res->type = tc_img;
                res->storage_as.string.data = (char*)img;
        }
end:
        no_interrupt(intflag);
        return (res);
}

/** Save IMG to file
 */
LISP img_save(LISP img, LISP fname)
{
        IMG *_img = NULL;
        LISP res;
        long intflag;
        char *_fname;
        FREE_IMAGE_FORMAT fif;
        
        _img = LISP2IMG(img);
        _fname = get_c_string(fname);

        intflag = no_interrupt(1);
        fif = FreeImage_GetFIFFromFilename(_fname);
        if (fif == FIF_UNKNOWN) {
                res = err(__func__, llast_c_errmsg(-1));
                goto end;
        }
        if (!FreeImage_Save(fif, _img, _fname, 0)) {
                res = err(__func__, llast_c_errmsg(-1));
                goto end;
        } else {
                res = a_true_value();
        }
end:
        no_interrupt(intflag);
        return (res);
}

/** Initialize IMG module
 */
void _img_init(void)
{
        long _kind;
        tc_img = allocate_user_tc();
        set_gc_hooks(tc_img, NULL, NULL, NULL, _img_gc_free, &_kind);
        set_print_hooks(tc_img, _img_print);
        init_storage();
        init_subrs();
        init_trace();
        init_imsh_version();
        init_subr_1("img_open", img_open);
        init_subr_2("img_save", img_save);
        init_subr_2("img_bw", img_bw);
        init_subr_1("img_gr", img_gr);
        init_subr_1("img_neg", img_neg);
        init_subr_4("img_conv", img_conv);
        init_subr_2("img_ch", img_ch);
        init_subr_2("img_grl", img_grl);
        init_subr_3("img_pix", img_pix);
        init_subr_2("img_med", img_med);
        init_subr_2("img_bindilate", img_bindilate);
        init_subr_2("img_binerode", img_binerode);
        init_subr_2("img_binand", img_binand);
        init_subr_2("img_binor", img_binor);
        init_subr_2("img_binxor", img_binxor);
        init_subr_2("img_binsub", img_binsub);
        init_subr_1("img_binnot", img_binnot);


}

// ---------------------------------------------------------------------------
// }}}

// Main entry {{{
// ---------------------------------------------------------------------------

int main(int argc, char **argv)
{
        const char _wrapper[] = "(*catch 'errobj (begin ";
// size of _wrapper array without trailing '\0'
#define _WRAPPER_SIZE (sizeof _wrapper - 1)
        long retval = -1;
        int i;

        //FIBITMAP *bitmap = FreeImage_Load(FIF_IMG, "ngirl.img", IMG_DEFAULT);
        //FreeImage_Save(FIF_JPEG, bitmap, "mybitmap.jpg", 0);
        //FreeImage_Unload(bitmap);

        _img_init();
        if (1 == argc) {
                // REPL loop
                retval = repl_driver(1, 1, NULL);
        } else {
                FILE *fp = NULL;
                char *buf = NULL;
                long filesize;

                // XXX b - to prevent translating \r\n to \n!
                fp = fopen(argv[1], "rb");
                if (!fp) {
                        fprintf(stderr, "Can not open '%s'!\n", argv[1]);
                        retval = 255;
                        goto closefile;
                }
                fseek(fp, 0, SEEK_END);
                buf = malloc((filesize=ftell(fp)) + _WRAPPER_SIZE + 10); // add for wrapper
                if (!buf) {
                        fprintf(stderr, "Not enought memory!\n");
                        retval = 255;
                        goto freebuf;
                }
                // all is OK here
                strcpy(buf, _wrapper);
                fseek(fp, 0, SEEK_SET);
                fread(buf + _WRAPPER_SIZE, sizeof (char), filesize, fp);
                for (i = _WRAPPER_SIZE; i < _WRAPPER_SIZE + filesize; i++) {
                        if (buf[i] == '\n' || buf[i] == '\r')
                                buf[i] = ' ';
                }
                strcpy(buf + i, "))");
                retval = repl_c_string(buf, 1, 1, 1);
freebuf:
                free(buf);
                buf = NULL;
closefile:
                fclose(fp);
                fp = NULL;
        }
        printf("done with %d\n", retval);
        return (retval);
}

// }}}





>







|
|


|
|





>
>





>



|
|
>
>
>
>
>
>










|
|
|
>
>
>
>
>
>
>
>





|
<
<
<
<
<
<
<
<
<
<
>



|
|
|



|
|
|




|
|
|







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|
|
|

|
|

|

|

|
|
|
|
|
|
|
|
|
|
|
|
|
|







|
|
|
|

|
|

|

|
|
|
|
|
|
|
|
|
|



|


|
|

|
|

|

|
|
|
|
|
|
|
|



|


|
|
|
|

|
|

|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







|
|
|
|
|





|
|

|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|











|
|
|
|

|
|

|

|
|

|
|
|
|
|
|
|
|
|
|
|









|
|
|





|
|

|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|








|



|


|
|
|
|
|

|
|

|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|











|
|







 







|
|











|
|
|
|
|







|
|

|
|

|

|
|
|
|
|
|
|
|
|












|
|
|

|
|

|
|

|

|
|

|
|
|
|
|
|
|
|
|

|
|
|

|
|
|

|
|
|
|
|
|
|
|





>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|
|

|
|
|
|
|




|

|
|
|
|




|

|
|
|
|




|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|

|




|
|

|
|
|
|
|




|
|

|
|
|
|
|




|
|

|
|
|
|
|
|




|
|

|
|
|
|
|




|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|

|




|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|

|



|
|
|
|
|
|
|
|






|






|






|






|





|

|
|
|
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|


|
|
|




|
|
|
|




|
|
|
|
|



|


|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|



|


|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|

|
|



|


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>










|
|

|
|

|
|
|

|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|

|
|
|
|
|



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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
...
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <stdint.h>
#include <stdbool.h>
#include <siod.h>
#include <freeimage.h>

#ifdef __GNUC__
#define MIN(a,b) \
    ({ __typeof__ (a) _a = (a); \
     __typeof__ (b) _b = (b); \
     _a > _b ? _b : _a; })
#define MAX(a,b) \
    ({ __typeof__ (a) _a = (a); \
     __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })
#else
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif

#define sizeofarray(A) (sizeof(A)/sizeof(A[0]))

// TODO check all return values of FreeImage_*()

typedef FIBITMAP IMG;
typedef struct pt2_t pt2_t;
typedef struct dithpt_t dithpt_t;

/// Point coordinates in 2D
struct pt2_t {
    int x;
    int y;
};

/// Dithering point coefficient (for dithering matrix)
struct dithpt_t {
    int x, y;
    float k;
};

/// Type of IMG Lisp object
long tc_img = 0;

/// Some functions' declarations
static IMG* LISP2IMG(LISP ptr);
static void polygon_coords(unsigned int n, int cx, int cy, unsigned int r, int angle, pt2_t *coords);

static void init_imsh_version(void) {
    setvar(cintern("*imsh-version*"),
            cintern("$Id: imsh.c,v 1.0 2013/08/26 py-dev $"),
            NIL);
}

int random_range(int a, int b)
{
    time_t sec;
    time(&sec);
    srand((unsigned int)sec);
    return (rand() % (b - a + 1) + a);
}

// Image processing algorithms {{{
// ---------------------------------------------------------------------------

#define RGB(R, G, B) (RGBQUAD){(uint8_t)R, (uint8_t)G, (uint8_t)B}










#define RGB1(X) (RGBQUAD){(uint8_t)X, (uint8_t)X, (uint8_t)X}

/// Length of RGB vector
#define RGBLEN(RGBQ) sqrt( \
        + ((RGBQ)->rgbRed)*((RGBQ)->rgbRed) \
        + ((RGBQ)->rgbGreen)*((RGBQ)->rgbGreen) \
        + ((RGBQ)->rgbBlue)*((RGBQ)->rgbBlue))

/// Initialize RGB with colors components
#define RGBINIT(RGBQ, R, G, B) do { \
    (RGBQ)->rgbRed = (R); \
    (RGBQ)->rgbGreen = (G); \
    (RGBQ)->rgbBlue = (B); \
} while (0)

/// Initialize RGB with 255-colors components
#define RGBNEG256(RGBQ) do { \
    (RGBQ)->rgbRed = 255 - (RGBQ)->rgbRed; \
    (RGBQ)->rgbGreen = 255 - (RGBQ)->rgbGreen; \
    (RGBQ)->rgbBlue = 255 - (RGBQ)->rgbBlue; \
} while (0)

/// Selectors
#define RGB_R(RGBQ) ((RGBQ)->rgbRed)
#define RGB_G(RGBQ) ((RGBQ)->rgbGreen)
#define RGB_B(RGBQ) ((RGBQ)->rgbBlue)

/// Operations on RGB
#define __MUL(X, Y) ((X) * (Y))
#define __DIV(X, Y) ((X) / (Y))
#define __ADD(X, Y) ((X) + (Y))
#define __SUB(X, Y) ((X) - (Y))

#define RGBCOP(OP, RGBQ, X) \
    (RGBQUAD) { OP(RGB_R(RGBQ), X), \
        OP(RGB_G(RGBQ), X), \
        OP(RGB_B(RGBQ), X) }

#define RGBOP(OP, RGBQ1, RGBQ2) \
    (RGBQUAD) { OP(RGB_R(RGBQ1), RGB_R(RGBQ2)), \
        OP(RGB_G(RGBQ1), RGB_G(RGBQ2)), \
        OP(RGB_B(RGBQ1), RGB_B(RGBQ2)) }

const RGBQUAD RGB_WHITE = (const RGBQUAD){.rgbRed=255, .rgbGreen=255, .rgbBlue=255};
const RGBQUAD RGB_BLACK = (const RGBQUAD){.rgbRed=0, .rgbGreen=0, .rgbBlue=0};

static inline int brightness(RGBQUAD *rgb)
{
    /*int max = 0, min = 255, i, a[] = {RGB_R(rgb), RGB_G(rgb), RGB_G(rgb)};
    for (i=0; i<3; i++) {
        if (a[i] > max) max = a[i];
        if (a[i] < min) min = a[i];
    }
    return (max + min)/2;*/
    return ((RGB_R(rgb) + RGB_G(rgb) + RGB_B(rgb))/3);
}

/** Calculates coordinates of each node of regular polygon
*/
static void polygon_coords(unsigned int n, int cx, int cy, unsigned int r,
        int angle, pt2_t *coords)
{
    int i;
    for (i=0; i<n-1; i++) {
        coords[i].x = cx + r*cos(angle + 2*M_PI*i/n);
        coords[i].y = cy + r*sin(angle + 2*M_PI*i/n);
    }
}

/** Convert image to black-white
 * @param threshold the threshold of brightness in percents
 * @return 0 on success
 */
int algo_bw(IMG *img, int threshold)
{
    RGBQUAD rgb;
    unsigned int row, col, width, height;
    double rgbl, maxrgbl;

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    maxrgbl = sqrt(255.*255. + 255.*255. + 255.*255.);

    for (row = 0; row < height; row++) {
        for (col = 0; col < width; col++) {
            FreeImage_GetPixelColor(img, col, row, &rgb);
            rgbl = RGBLEN(&rgb);
            if (rgbl*100/maxrgbl > threshold) {
                // light
                FreeImage_SetPixelColor(img, col, row, (RGBQUAD*)&RGB_WHITE);
            } else {
                // dark
                FreeImage_SetPixelColor(img, col, row, (RGBQUAD*)&RGB_BLACK);
            }
        }
    }
    return (0);
}

/** grayscale image
 * @return 0 on success
 */
int algo_gr(IMG *img)
{
    RGBQUAD rgb;
    unsigned int row, col, width, height;
    double rgbl;
    uint8_t c;

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    for (row = 0; row < height; row++) {
        for (col = 0; col < width; col++) {
            FreeImage_GetPixelColor(img, col, row, &rgb);
            rgbl = RGBLEN(&rgb);
            c = rgbl/sqrt(3.);
            RGBINIT(&rgb, c, c, c);
            FreeImage_SetPixelColor(img, col, row, &rgb);
        }
    }
    return (0);
}

/** Negative
*/
int algo_neg(IMG *img)
{
    RGBQUAD rgb;
    unsigned int row, col, width, height;

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    for (row = 0; row < height; row++) {
        for (col = 0; col < width; col++) {
            FreeImage_GetPixelColor(img, col, row, &rgb);
            RGBNEG256(&rgb);
            FreeImage_SetPixelColor(img, col, row, &rgb);
        }
    }
    return (0);
}

/** Apply conv. matrix with size sideXside, use division, shifting, normalization.
*/
int algo_conv(IMG *img, int *matrix, int side, int div, int shift)
{
    RGBQUAD rgb;
    unsigned int row, col, i, j, width, height, cx, cy;
    uint8_t *res[3] = {NULL}; // Tmp working copies of bitmap for 3 chans
    int r1, g1, b1, margin, mi;

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height && div && matrix && side>2 && side%2);

    margin = side/2; // process central area, without margin
    // allocate tmp copies of channels
    for (i=0; i<3; i++) {
        res[i] = malloc(width*height*sizeof (uint8_t));
        if (!res[i]) {
            while (i >= 0) free(res[i--]);
            return (1);
        }
    }
    // processing
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            r1 = g1 = b1 = 0;
            for (j = 0; j < side; j++) {
                cy = row - margin + j;
                for (i = 0; i < side; i++) {
                    cx = col - margin + i;
                    FreeImage_GetPixelColor(img, cx, cy, &rgb);
                    mi = j*side + i;
                    r1 += RGB_R(&rgb) * matrix[mi];
                    g1 += RGB_G(&rgb) * matrix[mi];
                    b1 += RGB_B(&rgb) * matrix[mi];
                }
            }
#define __NORM_RGB(C) (C)=shift+(C)/div; (C)=(C)<0? 0 : (C)>255? 255 : (C)
            __NORM_RGB(r1);
            __NORM_RGB(g1);
            __NORM_RGB(b1);
#undef __NORM_RGB
            mi = row*width + col;
            *(res[0] + mi) = (uint8_t)r1;
            *(res[1] + mi) = (uint8_t)g1;
            *(res[2] + mi) = (uint8_t)b1;
        }
    }
    // copy to original img data from tmp copies, margin is unchanged
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            RGBINIT(&rgb,
                    *(res[0] + row*width + col),
                    *(res[1] + row*width + col),
                    *(res[2] + row*width + col));
            FreeImage_SetPixelColor(img, col, row, &rgb);
        }
    }
    // free tmp copies
    for (i=0; i<3; i++) free(res[i]);
    return (0);
}

/** Select only channels with bit-mask: chans is -----RGB byte,
 * so 7 select 3 chans
 */
int algo_ch(IMG *img, int chans)
{
    RGBQUAD rgb;
    unsigned int row, col, width, height;
    uint32_t mask;
    uint32_t rgb32;
    uint8_t r, g, b;

#define _R_ RGB_R(&rgb)
#define _G_ RGB_G(&rgb)
#define _B_ RGB_B(&rgb)

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    // 00RRGGBB, so 1 is chans bits are '...RGB'
    mask = ((chans & 4)? 0xFF0000 : 0)
        | ((chans & 2)? 0xFF00 : 0)
        | ((chans & 1)? 0xFF : 0);
    for (row = 0; row < height; row++) {
        for (col = 0; col < width; col++) {
            FreeImage_GetPixelColor(img, col, row, &rgb);
            rgb32 = mask & ((_R_<<16)|(_G_<<8)|_B_);
            _R_ = (rgb32 & 0xFF0000)>>16;
            _G_ = (rgb32 & 0xFF00)>>8;
            _B_ = rgb32 & 0xFF;
            FreeImage_SetPixelColor(img, col, row, &rgb);
        }
    }
    return (0);

#undef _R_
#undef _G_
#undef _B_
}

/** Convert image to gray levels
 * @param nlevels is number of levels (gradation)
 */
int algo_grl(IMG *img, int nlevels)
{
    RGBQUAD rgb;
    unsigned int row, col, width, height,
                 rgbl, maxrgbl, band;
    uint8_t c;

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height && nlevels>=2);

    maxrgbl = sqrt(255.*255. + 255.*255. + 255.*255.);
    band = maxrgbl/nlevels;

    for (row = 0; row < height; row++) {
        for (col = 0; col < width; col++) {
            FreeImage_GetPixelColor(img, col, row, &rgb);
            rgbl = (int)RGBLEN(&rgb);
            rgbl = band*(rgbl/band);
            c = rgbl/sqrt(3.);
            RGBINIT(&rgb, c, c, c);
            FreeImage_SetPixelColor(img, col, row, &rgb);
        }
    }
    return (0);
}

/** Pixalization of image.
 * @param side is side of square-pixel
 * @param color is 1 or 0 to generate color or black-and-white "pixels"
 * @return 0 on success
 */
int algo_pix(IMG *img, int side, int color)
{
    RGBQUAD rgb;
    unsigned int row, col, irow, icol, width, height;
    unsigned long rs, gs, bs, pixarea, maxrgbl_2;

#define _R_ RGB_R(&rgb)
#define _G_ RGB_G(&rgb)
#define _B_ RGB_B(&rgb)

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height && side>0);

    pixarea = side*side;
    if (!color) maxrgbl_2 = sqrt(255.*255. + 255.*255. + 255.*255.)/2;
    for (row = 0; row < height; row += side) {
        for (col = 0; col < width; col += side) {
            rs = gs = bs = 0;
            for (irow = row; irow < row+side; irow++) {
                for (icol = col; icol < col+side; icol++) {
                    FreeImage_GetPixelColor(img, icol, irow, &rgb);
                    rs += _R_;
                    gs += _G_;
                    bs += _B_;
                }
            }
            _R_ = rs / pixarea;
            _G_ = gs / pixarea;
            _B_ = bs / pixarea;
            if (!color) {
                if (RGBLEN(&rgb) > maxrgbl_2) {
                    rgb = (RGBQUAD)RGB_WHITE;
                } else {
                    rgb = (RGBQUAD)RGB_BLACK;
                }

            }
            for (irow = row; irow < row+side; irow++) {
                for (icol = col; icol < col+side; icol++) {
                    FreeImage_SetPixelColor(img, icol, irow, &rgb);
                }
            }
        }
    }
    return (0);

#undef _R_
#undef _G_
#undef _B_
}

static int _median_cmpf(void const *x, void const *y)
{
    return (*(uint8_t*)x - *(uint8_t*)y);
}

/** Median filter with specified side
*/
int algo_med(IMG *img, int side)
{
    RGBQUAD rgb;
    unsigned int row, col, i, j, k, width, height, cx, cy;
    // Tmp working copies of bitmap for 3 chans and buffer for sorting (win)
    uint8_t *res[3] = {NULL}, *win[3] = {NULL};
    int margin, middle, result = 0, mi;

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height && side>2 && side%2);

    margin = side/2; // process central area, without margin
    middle = 1 + side*side/2; // middle element in sorted buffer (win[i])
    // allocate tmp copies of channels
    for (i=0; i<3; i++) {
        res[i] = malloc(width*height*sizeof (uint8_t));
        if (!res[i]) {
            result = 1;
            goto free_bufs;
        }
    }
    // allocate win buffers
    for (i=0; i<3; i++) {
        win[i] = malloc(side*side*sizeof (uint8_t));
        if (!win[i]) {
            result = 1;
            goto free_bufs;
        }
    }
    // processing
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            k = 0;
            for (j = 0; j < side; j++) {
                cy = row - margin + j;
                for (i = 0; i < side; i++) {
                    cx = col - margin + i;
                    FreeImage_GetPixelColor(img, cx, cy, &rgb);
                    *(win[0] + k) = RGB_R(&rgb);
                    *(win[1] + k) = RGB_G(&rgb);
                    *(win[2] + k) = RGB_B(&rgb);
                    k++;
                }
            }
            qsort(win[0], k, sizeof win[0][0], _median_cmpf);
            qsort(win[1], k, sizeof win[1][0], _median_cmpf);
            qsort(win[2], k, sizeof win[2][0], _median_cmpf);
            mi = row*width + col;
            *(res[0] + mi) = win[0][middle];
            *(res[1] + mi) = win[1][middle];
            *(res[2] + mi) = win[2][middle];
        }
    }
    // copy to original img data from tmp copies, margin is unchanged
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            mi = row*width + col;
            RGBINIT(&rgb, *(res[0] + mi), *(res[1] + mi), *(res[2] + mi));
            FreeImage_SetPixelColor(img, col, row, &rgb);
        }
    }
free_bufs:
    for (i=0; i<3; i++) {
        if (res[i]) {
            free(res[i]);
            res[i] = NULL;
        }
        if (win[i]) {
            free(win[i]);
            win[i] = NULL;
        }
    }
    return (result);
}

/** Binary dilate and erode generic implementation */
#define _ERODE_DILATE_GENERIC_ALGO() do { \
    RGBQUAD rgb; \
    unsigned int row, col, i, j, width, height, cx, cy; \
    uint8_t *res[3] = {NULL}; /* Tmp working copies of bitmap for 3 chans */ \
    int margin, mi; \
    bool detected; \
    width = FreeImage_GetWidth(img); \
    height = FreeImage_GetHeight(img); \
    \
    assert(img && width && height && matrix && side>2 && side%2); \
    \
    /* Process central area, without margin. Also margin is middle point, for side=5, middle is 2: 0,1,[2],3,4 */ \
    margin = side/2; \
    /* allocate tmp copies of channels */ \
    for (i=0; i<3; i++) { \
        res[i] = malloc(width*height*sizeof (uint8_t)); \
        if (!res[i]) { \
            while (i >= 0) free(res[i--]); \
            return (1); \
        } \
    } \
    /* processing */ \
    for (row = margin; row < height-margin; row++) { \
        for (col = margin; col < width-margin; col++) { \
            detected = false; \
            for (j = 0; j < side; j++) { \
                cy = row - margin + j; \
                for (i = 0; i < side; i++) { \
                    cx = col - margin + i; \
                    if (j == margin && i == margin) { \
                        /* if center point */ \
                        continue; \
                    } else { \
                        mi = j*side + i; \
                        FreeImage_GetPixelColor(img, cx, cy, &rgb); \
                        if (matrix[mi] \
                                && (__ISCOND(RGB_R(&rgb)) \
                                    || __ISCOND(RGB_G(&rgb)) \
                                    || __ISCOND(RGB_B(&rgb)))) { \
                            detected = true; \
                            goto _detected; \
                        } \
                    } \
                } \
            } \
_detected: \
            mi = row*width + col; \
            if (detected) { \
                *(res[0] + mi) = *(res[1] + mi) = *(res[2] + mi) = __RESYES; \
            } else { \
                *(res[0] + mi) = (-1==__RESNO)? RGB_R(&rgb) : __RESNO; \
                *(res[1] + mi) = (-1==__RESNO)? RGB_G(&rgb) : __RESNO; \
                *(res[2] + mi) = (-1==__RESNO)? RGB_B(&rgb) : __RESNO; \
            } \
        } \
    } \
    /* copy to original img data from tmp copies, margin is unchanged */ \
    for (row = margin; row < height-margin; row++) { \
        for (col = margin; col < width-margin; col++) { \
            RGBINIT(&rgb, \
                    *(res[0] + row*width + col), \
                    *(res[1] + row*width + col), \
                    *(res[2] + row*width + col)); \
            FreeImage_SetPixelColor(img, col, row, &rgb); \
        } \
    } \
    /* free tmp copies */ \
    for (i=0; i<3; i++) free(res[i]); \
} while (0)

/**
 * Binary dilate
 */
int algo_bindilate(IMG *img, int *matrix, int side)
{
#define __RESYES 255
#define __RESNO 0
#define __ISCOND(X) ((X)!=0)

    _ERODE_DILATE_GENERIC_ALGO();
    return (0);

#undef __RESYES
#undef __RESNO
#undef __ISCOND
}

/**
................................................................................
 */
int algo_binerode(IMG *img, int *matrix, int side)
{
#define __RESYES 0
#define __RESNO 255
#define __ISCOND(X) ((X)==0)

    _ERODE_DILATE_GENERIC_ALGO();
    return (0);

#undef __RESYES
#undef __RESNO
#undef __ISCOND
}

/** For binary operations on pixels as sets */

/* all channels should has the same values */
#define __GETBIT(Q) ((RGB_R(Q)!=0)?(-1):0)
#define __SETBIT(Q, B) do { \
    if (B) { \
        RGBINIT(Q, 255, 255, 255); \
    } else  { \
        RGBINIT(Q, 0, 0, 0); \
    } \
} while (0)

/**
 * Binary monadic not operation. img is in/out.
 */
int algo_binnot(IMG *img)
{
    RGBQUAD rgb;
    unsigned int row, col, width, height;

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    // processing
    for (row = 0; row < height; row++) {
        for (col = 0; col < width; col++) {
            FreeImage_GetPixelColor(img, col, row, &rgb);
            __SETBIT(&rgb, ~__GETBIT(&rgb));
            FreeImage_SetPixelColor(img, col, row, &rgb);
        }
    }
    return (0);
}

/**
 * Binary dyadic operations, result set to first.
 * op is:
 *      & - AND
 *      | - OR
 *      ^ - XOR
 *      / - SUB (X but not Y)
 */
int algo_binop2(char op, IMG *img1, IMG *img2)
{
    RGBQUAD rgb1, rgb2;
    unsigned int row, col, width1, height1, width2, height2,
                 wbound, hbound;

    width1 = FreeImage_GetWidth(img1);
    height1 = FreeImage_GetHeight(img1);

    width2 = FreeImage_GetWidth(img2);
    height2 = FreeImage_GetHeight(img2);

    assert(img1 && img2 && width1 && height1 && width2 && height2);

    wbound = MIN(width1, width2);
    hbound = MIN(height1, height2);

    // processing
    for (row = 0; row < hbound; row++) {
        for (col = 0; col < wbound; col++) {
            FreeImage_GetPixelColor(img1, col, row, &rgb1);
            FreeImage_GetPixelColor(img2, col, row, &rgb2);
            switch (op) {
                case '&':
                    __SETBIT(&rgb1, __GETBIT(&rgb1) & __GETBIT(&rgb2));
                    break;

                case '|':
                    __SETBIT(&rgb1, __GETBIT(&rgb1) | __GETBIT(&rgb2));
                    break;

                case '^':
                    __SETBIT(&rgb1, __GETBIT(&rgb1) ^ __GETBIT(&rgb2));
                    break;

                case '/':
                    __SETBIT(&rgb1, __GETBIT(&rgb1) & (__GETBIT(&rgb1) ^ __GETBIT(&rgb2)));
                    break;
            }
            FreeImage_SetPixelColor(img1, col, row, &rgb1);
        }
    }
    return (0);
}

#undef __GETBIT
#undef __SETBIT

#define __DITH_FNDCLOSEST(RGBQ) (brightness(RGBQ)<128? RGB_BLACK:RGB_WHITE)
#define __DITH_GET(X, Y) (FreeImage_GetPixelColor(img, X, Y, &oldrgb), &oldrgb)
#define __DITH_SET(X, Y, C) (newrgb = (C), FreeImage_SetPixelColor(img, X, Y, &newrgb))

/// Atkinson dithering
int algo_atkinson_dith(IMG *img)
{
    RGBQUAD newrgb, oldrgb;
    float qerr, c;
    unsigned int x, y, row, col, i, width, height;
    uint8_t *tmp = NULL;
    static const int
        s = 1, // step
        margin = 0; //process central area, without margin

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    i = width*height*sizeof (uint8_t);
    tmp = (uint8_t*)malloc(i);
    if (!tmp) return (1);
    memset(tmp, 0, i);

    for (row = margin; row < height-margin; row+=s) {
        for (col = margin; col < width-margin; col+=s) {
            FreeImage_GetPixelColor(img, col, row, &oldrgb);
            newrgb = __DITH_FNDCLOSEST(&oldrgb);
            qerr = brightness(&oldrgb) - brightness(&newrgb);
            FreeImage_SetPixelColor(img, col, row, &newrgb);
            *(tmp + sizeof (uint8_t)*(row*width + col)) = RGB_R(&newrgb);

            struct { int x, y; }
                mat[] = {{col+s, row},   {col-s, row+s},   {col, row+s},
                         {col+s, row+s}, {col+2*s, row}, {col, row+2*s}};

            for (i = 0; i < sizeofarray(mat); i++) {
                x = mat[i].x; y = mat[i].y;
                __DITH_SET(x, y, RGB1(brightness(__DITH_GET(x, y)) + 1./8*qerr));
            }
        }
    }

    // copy to original img data from tmp copies, margin is unchanged
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            newrgb = RGB1(*(tmp + sizeof (uint8_t)*(row*width + col)));
            FreeImage_SetPixelColor(img, col, row, &newrgb);
        }
    }

    free(tmp);
    return (0);
}

int algo_general_dith(IMG *img, dithpt_t *pts, int npts)
{
    RGBQUAD newrgb, oldrgb;
    float qerr, k;
    unsigned int x, y, row, col, i, width, height;
    uint8_t *tmp = NULL;
    static const int
        s = 1, // step
        margin = 0; //process central area, without margin

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    i = width*height*sizeof (uint8_t);
    tmp = (uint8_t*)malloc(i);
    if (!tmp) return (1);
    memset(tmp, 0, i);

    for (row = margin; row < height-margin; row+=s) {
        for (col = margin; col < width-margin; col+=s) {
            FreeImage_GetPixelColor(img, col, row, &oldrgb);
            newrgb = __DITH_FNDCLOSEST(&oldrgb);
            qerr = brightness(&oldrgb) - brightness(&newrgb);
            FreeImage_SetPixelColor(img, col, row, &newrgb);
            *(tmp + sizeof (uint8_t)*(row*width + col)) = RGB_R(&newrgb);

            /*struct { int x, y; float k; }
                mat[] = {{col+s, row, 8./42}, {col+2*s, row, 4./42},
                         {col-2*s, row+s, 2./42}, {col-s, row+s, 4./42},
                         {col, row+s, 8./42}, {col+s, row+s, 4./42},
                         {col+2*s, row+s, 2./42}, {col-2*s, row+2*s, 1./42},
                         {col-s, row+2*s, 2./42}, {col, row+2*s, 4./42},
                         {col+s, row+2*s, 2./42}, {col+2*s, row+2*s, 1./42}};*/

            for (i = 0; i < npts; i++) {
                x = col + s*pts[i].x;
                y = row + s*pts[i].y;
                k = pts[i].k*qerr;
                __DITH_SET(x, y, RGB1(brightness(__DITH_GET(x, y)) + k));
            }
        }
    }

    // copy to original img data from tmp copies, margin is unchanged
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            newrgb = RGB1(*(tmp + sizeof (uint8_t)*(row*width + col)));
            FreeImage_SetPixelColor(img, col, row, &newrgb);
        }
    }

    free(tmp);
    return (0);
}

/// Stucki dithering
int algo_stucki_dith(IMG *img)
{
    RGBQUAD newrgb, oldrgb;
    float qerr, k;
    unsigned int x, y, row, col, i, width, height;
    uint8_t *tmp = NULL;
    static const int
        s = 1, // step
        margin = 0; //process central area, without margin

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    i = width*height*sizeof (uint8_t);
    tmp = (uint8_t*)malloc(i);
    if (!tmp) return (1);
    memset(tmp, 0, i);

    for (row = margin; row < height-margin; row+=s) {
        for (col = margin; col < width-margin; col+=s) {
            FreeImage_GetPixelColor(img, col, row, &oldrgb);
            newrgb = __DITH_FNDCLOSEST(&oldrgb);
            qerr = brightness(&oldrgb) - brightness(&newrgb);
            FreeImage_SetPixelColor(img, col, row, &newrgb);
            *(tmp + sizeof (uint8_t)*(row*width + col)) = RGB_R(&newrgb);

            struct { int x, y; float k; }
                mat[] = {{col+s, row, 8./42}, {col+2*s, row, 4./42},
                         {col-2*s, row+s, 2./42}, {col-s, row+s, 4./42},
                         {col, row+s, 8./42}, {col+s, row+s, 4./42},
                         {col+2*s, row+s, 2./42}, {col-2*s, row+2*s, 1./42},
                         {col-s, row+2*s, 2./42}, {col, row+2*s, 4./42},
                         {col+s, row+2*s, 2./42}, {col+2*s, row+2*s, 1./42}};

            for (i = 0; i < sizeofarray(mat); i++) {
                x = mat[i].x; y = mat[i].y; k = mat[i].k*qerr;
                __DITH_SET(x, y, RGB1(brightness(__DITH_GET(x, y)) + k));
            }
        }
    }

    // copy to original img data from tmp copies, margin is unchanged
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            newrgb = RGB1(*(tmp + sizeof (uint8_t)*(row*width + col)));
            FreeImage_SetPixelColor(img, col, row, &newrgb);
        }
    }

    free(tmp);
    return (0);
}

/// Floyd-Steinberg dithering
int algo_floyd_steinberg_dith(IMG *img)
{
    RGBQUAD newrgb, oldrgb;
    float qerr, c, k;
    unsigned int x, y, row, col, i, width, height;
    uint8_t *tmp = NULL;
    static const int
        s = 1, // step
        margin = 0; //process central area, without margin

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    i = width*height*sizeof (uint8_t);
    tmp = (uint8_t*)malloc(i);
    if (!tmp) return (1);
    memset(tmp, 255, i);

    for (row = margin; row < height-margin; row+=s) {
        for (col = margin; col < width-margin; col+=s) {
            FreeImage_GetPixelColor(img, col, row, &oldrgb);
            newrgb = __DITH_FNDCLOSEST(&oldrgb);
            qerr = brightness(&oldrgb) - brightness(&newrgb);
            FreeImage_SetPixelColor(img, col, row, &newrgb);
            *(tmp + sizeof (uint8_t)*(row*width + col)) = RGB_R(&newrgb);

            struct { int x, y; float k; }
                mat[] = {{col+s, row, 7./16}, {col-s, row+s, 3./16},
                         {col, row+s, 5./16}, {col+s, row+s, 1./16}};

            for (i = 0; i < sizeofarray(mat); i++) {
                x = mat[i].x; y = mat[i].y; k = mat[i].k*qerr;
                __DITH_SET(x, y, RGB1(brightness(__DITH_GET(x, y)) + k));
            }
        }
    }

    // copy to original img data from tmp copies, margin is unchanged
    for (row = margin; row < height-margin; row++) {
        for (col = margin; col < width-margin; col++) {
            newrgb = RGB1(*(tmp + sizeof (uint8_t)*(row*width + col)));
            FreeImage_SetPixelColor(img, col, row, &newrgb);
        }
    }

    free(tmp);
    return (0);
}

/// Ordered dithering
int algo_ordered_dith(IMG *img)
{
    RGBQUAD newrgb, oldrgb;
    static const float mratio = 1./17, mfactor = 255./5;
    int matrix[][4] = {{1, 9, 3, 11}, {13, 5, 15, 7},
                      {4, 12, 2, 10}, {16, 8, 14, 6}};
    unsigned int row, col, width, height;
    static const int
        s = 1, // step
        margin = 0; //process central area, without margin

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    for (row = margin; row < height-margin; row+=s) {
        for (col = margin; col < width-margin; col+=s) {
            FreeImage_GetPixelColor(img, col, row, &oldrgb);
            newrgb = RGB1(brightness(&oldrgb) + mratio*matrix[col%4][row%4]*mfactor);
            newrgb = __DITH_FNDCLOSEST(&newrgb);
            FreeImage_SetPixelColor(img, col, row, &newrgb);
        }
    }

    return (0);
}

/// Random dithering
int algo_random_dith(IMG *img)
{
    RGBQUAD newrgb, oldrgb;
    float qerr, c;
    unsigned int x, y, row, col, width, height;
    static const int
        s = 1, // step
        margin = 0; //process central area, without margin

    width = FreeImage_GetWidth(img);
    height = FreeImage_GetHeight(img);

    assert(img && width && height);

    for (row = margin; row < height-margin; row+=s) {
        for (col = margin; col < width-margin; col+=s) {
            FreeImage_GetPixelColor(img, col, row, &oldrgb);
            newrgb = RGB1(brightness(&oldrgb) + random_range(-64, 64));
            newrgb = __DITH_FNDCLOSEST(&newrgb);
            FreeImage_SetPixelColor(img, col, row, &newrgb);
        }
    }

    return (0);
}

#undef __DITH_FNDCLOSEST
#undef __DITH_GET
#undef __DITH_SET
/** Thining algorithm of Zhang-Suen
*/
/*int algo_zhs(IMG *img)
  {
  RGBQUAD rgb;
  unsigned int row, col, i, j, k, width, height, cx, cy;
// Tmp working copies of bitmap for 3 chans and buffer for sorting (win)
uint8_t *preimg = NULL;
int margin, middle, result = 0, mi;
static const int
margin = 1, //process central area, without margin
middle = 1; // middle element in sorted buffer (win[i])

width = FreeImage_GetWidth(img);
height = FreeImage_GetHeight(img);

assert(img && width && height);

// allocate tmp copies of channels
preimg = malloc(width*height*sizeof (uint8_t));
if (!preimg) {
result = 1;
goto free_bufs;
}
// processing
for (row = margin; row < height-margin; row++) {
for (col = margin; col < width-margin; col++) {
k = 0;
for (j = 0; j < 3; j++) {
cy = row - margin + j;
for (i = 0; i < side; i++) {
cx = col - margin + i;
FreeImage_GetPixelColor(img, cx, cy, &rgb);
 *(win[0] + k) = RGB_R(&rgb);
 *(win[1] + k) = RGB_G(&rgb);
 *(win[2] + k) = RGB_B(&rgb);
 k++;
 }
 }
 mi = row*width + col;
 *(res[0] + mi) = win[0][middle];
 *(res[1] + mi) = win[1][middle];
 *(res[2] + mi) = win[2][middle];
 }
 }
// copy to original img data from tmp copies, margin is unchanged
for (row = margin; row < height-margin; row++) {
for (col = margin; col < width-margin; col++) {
mi = row*width + col;
RGBINIT(&rgb, *(res[0] + mi), *(res[1] + mi), *(res[2] + mi));
FreeImage_SetPixelColor(img, col, row, &rgb);
}
}
free_bufs:
free(preimg);
return (result);
}*/

// ---------------------------------------------------------------------------
// }}}

// Algorithms wrappers {{{
// ---------------------------------------------------------------------------

LISP img_bw(LISP img, LISP threshold)
{
    IMG *_img = NULL;
    long _threshold;

    _img = LISP2IMG(img);
    _threshold = get_c_long(threshold);
    if (!algo_bw(_img, (int)_threshold))
        return (a_true_value());
    else return (NIL);
}

LISP img_gr(LISP img)
{
    IMG *_img = NULL;

    _img = LISP2IMG(img);
    if (!algo_gr(_img))
        return (a_true_value());
    else return (NIL);
}

LISP img_neg(LISP img)
{
    IMG *_img = NULL;

    _img = LISP2IMG(img);
    if (!algo_neg(_img))
        return (a_true_value());
    else return (NIL);
}

LISP img_conv(LISP img, LISP matrix, LISP div, LISP shift)
{
    IMG *_img = NULL;
    LISP res, l;
    long _div, _shift;
    int *_matrix = NULL, matrix_len, side, i;

    matrix_len = nlength(matrix);
    side = sqrt(matrix_len);
    _matrix = malloc(matrix_len*sizeof(int));
    if (!_matrix) {
        res = err(__func__, llast_c_errmsg(-1));
        goto end;
    }
    for (l=matrix, i=0; i<matrix_len /*&& NNULLP(l)*/; l=cdr(l), i++) {
        _matrix[i] = get_c_long(car(l));
    }
    _img = LISP2IMG(img);
    _div = get_c_long(div);
    _shift = get_c_long(shift);
    if (!algo_conv(_img, _matrix, side, (int)_div, (int)_shift)) {
        res = a_true_value();
        goto free_matrix;
    } else {
        res = NIL;
        goto free_matrix;
    }
free_matrix:
    free(_matrix);
end:
    return (res);
}

LISP img_ch(LISP img, LISP channels)
{
    IMG *_img = NULL;
    long _channels;

    _img = LISP2IMG(img);
    _channels = get_c_long(channels);
    if (!algo_ch(_img, (int)_channels))
        return (a_true_value());
    else return (NIL);
}

LISP img_grl(LISP img, LISP nlevels)
{
    IMG *_img = NULL;
    long _nlevels;

    _img = LISP2IMG(img);
    _nlevels = get_c_long(nlevels);
    if (!algo_grl(_img, (int)_nlevels))
        return (a_true_value());
    else return (NIL);
}

LISP img_pix(LISP img, LISP side, LISP color)
{
    IMG *_img = NULL;
    long _side, _color;

    _img = LISP2IMG(img);
    _side = get_c_long(side);
    _color = get_c_long(color);
    if (!algo_pix(_img, (int)_side, (int)_color))
        return (a_true_value());
    else return (NIL);
}

LISP img_med(LISP img, LISP side)
{
    IMG *_img = NULL;
    long _side;

    _img = LISP2IMG(img);
    _side = get_c_long(side);
    if (!algo_med(_img, (int)_side))
        return (a_true_value());
    else return (NIL);
}

LISP img_bindilate(LISP img, LISP matrix)
{
    IMG *_img = NULL;
    LISP res, l;
    int *_matrix = NULL, matrix_len, side, i;

    matrix_len = nlength(matrix);
    _matrix = malloc(matrix_len*sizeof(int));
    if (!_matrix) {
        res = err(__func__, llast_c_errmsg(-1));
        goto end;
    }
    side = sqrt(matrix_len);
    for (l=matrix, i=0; i<matrix_len; l=cdr(l), i++) {
        _matrix[i] = get_c_long(car(l));
    }
    _img = LISP2IMG(img);
    if (!algo_bindilate(_img, _matrix, side)) {
        res = a_true_value();
        goto free_matrix;
    } else {
        res = NIL;
        goto free_matrix;
    }
free_matrix:
    free(_matrix);
end:
    return (res);
}

LISP img_binerode(LISP img, LISP matrix)
{
    IMG *_img = NULL;
    LISP res, l;
    int *_matrix = NULL, matrix_len, side, i;

    matrix_len = nlength(matrix);
    _matrix = malloc(matrix_len*sizeof(int));
    if (!_matrix) {
        res = err(__func__, llast_c_errmsg(-1));
        goto end;
    }
    side = sqrt(matrix_len);
    for (l=matrix, i=0; i<matrix_len; l=cdr(l), i++) {
        _matrix[i] = get_c_long(car(l));
    }
    _img = LISP2IMG(img);
    if (!algo_binerode(_img, _matrix, side)) {
        res = a_true_value();
        goto free_matrix;
    } else {
        res = NIL;
        goto free_matrix;
    }
free_matrix:
    free(_matrix);
end:
    return (res);
}

#define _GENERAL_BINOP() do { \
    IMG *_img1 = NULL, *_img2 = NULL; \
    \
    _img1 = LISP2IMG(img1); \
    _img2 = LISP2IMG(img2); \
    if (!algo_binop2(__OP, _img1, _img2)) \
    return (a_true_value()); \
    else \
    return (NIL); \
} while (0)

// and or xor sub
LISP img_binand(LISP img1, LISP img2)
{
#define __OP '&'
    _GENERAL_BINOP();
#undef __OP
}

LISP img_binor(LISP img1, LISP img2)
{
#define __OP '|'
    _GENERAL_BINOP();
#undef __OP
}

LISP img_binxor(LISP img1, LISP img2)
{
#define __OP '^'
    _GENERAL_BINOP();
#undef __OP
}

LISP img_binsub(LISP img1, LISP img2)
{
#define __OP '/'
    _GENERAL_BINOP();
#undef __OP
}

LISP img_binnot(LISP img)
{
    IMG *_img = NULL;

    _img = LISP2IMG(img);
    if (!algo_binnot(_img))
        return (a_true_value());
    else
        return (NIL);
}

LISP img_gendith(LISP img, LISP matrix)
{
    IMG *_img = NULL;
    dithpt_t *_matrix = NULL;
    LISP res, l;
    double d;
    int matrix_len, i;

    matrix_len = nlength(matrix)/3;
    _matrix = (dithpt_t*)malloc(matrix_len*sizeof(dithpt_t));
    if (!_matrix) {
        res = err(__func__, llast_c_errmsg(-1));
        goto end;
    }
    for (l=matrix, i=0; i<matrix_len; l=cdr(l), i++) {
        d = get_c_double(car(l));
        switch (i%3) {
            case 0: _matrix[i/3].x = (int)d; break;
            case 1: _matrix[i/3].y = (int)d; break;
            default: _matrix[i/3].k = d; break;
        }
    }
    _img = LISP2IMG(img);
    if (!algo_general_dith(_img, _matrix, matrix_len/3)) {
        res = a_true_value();
        goto free_matrix;
    } else {
        res = NIL;
        goto free_matrix;
    }
free_matrix:
    free(_matrix);
end:
    return (res);
}

LISP img_dith(LISP img, LISP alg)
{
    IMG *_img = NULL;
    long _alg;
    int (*pfn[])(IMG *img) = {
        algo_atkinson_dith, algo_floyd_steinberg_dith, algo_ordered_dith,
        algo_random_dith, algo_stucki_dith
    };

    _img = LISP2IMG(img);
    _alg = get_c_long(alg);
    if (_alg < 0 || _alg >= sizeofarray(pfn)) return (NIL);
    else {
        if (!pfn[_alg](_img)) return (a_true_value());
        else return (NIL);
    }
}


// ---------------------------------------------------------------------------
// }}}

// Common IMG wrappers {{{
// ---------------------------------------------------------------------------

/** Convert internal lisp object to stored there IMG pointer
*/
static IMG* LISP2IMG(LISP ptr)
{
    if (NTYPEP(ptr, tc_img)) err("not a IMG", ptr);
    if (!ptr->storage_as.string.data) err("IMG deallocated", ptr);
    else return ((IMG*)ptr->storage_as.string.data);
}

void _img_gc_free(LISP ptr)
{
    IMG *img;
    if ((img = LISP2IMG(ptr)))
        FreeImage_Unload(img);
    ptr->storage_as.string.data = NULL;
}

void _img_print(LISP ptr, struct gen_printio *f)
{
    char buf[16];
    IMG *img;
    img = LISP2IMG(ptr);
    sprintf(buf, "#<IMG %p>", img);
    gput_st(f, buf);
}

/** Load IMG from file
*/
LISP img_open(LISP fname)
{
    IMG *img = NULL;
    LISP res;
    long intflag;
    char *_fname;
    FREE_IMAGE_FORMAT fif;

    _fname = get_c_string(fname);

    intflag = no_interrupt(1);
    fif = FreeImage_GetFileType(_fname, 0);
    if (fif == FIF_UNKNOWN) {
        fif = FreeImage_GetFIFFromFilename(_fname);
        if (fif == FIF_UNKNOWN) {
            // fif can not be determined
            res = err(__func__, llast_c_errmsg(-1));
            goto end;
        }
    }
    img = FreeImage_Load(fif, _fname, 0);
    if (!img) {
        res = err(__func__, llast_c_errmsg(-1));
    } else {
        res = cons(NIL, NIL);
        res->type = tc_img;
        res->storage_as.string.data = (char*)img;
    }
end:
    no_interrupt(intflag);
    return (res);
}

/** Save IMG to file
*/
LISP img_save(LISP img, LISP fname)
{
    IMG *_img = NULL;
    LISP res;
    long intflag;
    char *_fname;
    FREE_IMAGE_FORMAT fif;

    _img = LISP2IMG(img);
    _fname = get_c_string(fname);

    intflag = no_interrupt(1);
    fif = FreeImage_GetFIFFromFilename(_fname);
    if (fif == FIF_UNKNOWN) {
        res = err(__func__, llast_c_errmsg(-1));
        goto end;
    }
    if (!FreeImage_Save(fif, _img, _fname, 0)) {
        res = err(__func__, llast_c_errmsg(-1));
        goto end;
    } else {
        res = a_true_value();
    }
end:
    no_interrupt(intflag);
    return (res);
}

/** Initialize IMG module
*/
void _img_init(void)
{
    long _kind;
    tc_img = allocate_user_tc();
    set_gc_hooks(tc_img, NULL, NULL, NULL, _img_gc_free, &_kind);
    set_print_hooks(tc_img, _img_print);
    init_storage();
    init_subrs();
    init_trace();
    init_imsh_version();
    init_subr_1("img_open", img_open);
    init_subr_2("img_save", img_save);
    init_subr_2("img_bw", img_bw);
    init_subr_1("img_gr", img_gr);
    init_subr_1("img_neg", img_neg);
    init_subr_4("img_conv", img_conv);
    init_subr_2("img_ch", img_ch);
    init_subr_2("img_grl", img_grl);
    init_subr_3("img_pix", img_pix);
    init_subr_2("img_med", img_med);
    init_subr_2("img_bindilate", img_bindilate);
    init_subr_2("img_binerode", img_binerode);
    init_subr_2("img_binand", img_binand);
    init_subr_2("img_binor", img_binor);
    init_subr_2("img_binxor", img_binxor);
    init_subr_2("img_binsub", img_binsub);
    init_subr_1("img_binnot", img_binnot);
    init_subr_2("img_dith", img_dith);
    init_subr_2("img_gendith", img_gendith);
}

// ---------------------------------------------------------------------------
// }}}

// Main entry {{{
// ---------------------------------------------------------------------------

int main(int argc, char **argv)
{
    const char _wrapper[] = "(*catch 'errobj (begin ";
    // size of _wrapper array without trailing '\0'
#define _WRAPPER_SIZE (sizeof _wrapper - 1)
    long retval = -1;
    int i;

    //FIBITMAP *bitmap = FreeImage_Load(FIF_IMG, "ngirl.img", IMG_DEFAULT);
    //FreeImage_Save(FIF_JPEG, bitmap, "mybitmap.jpg", 0);
    //FreeImage_Unload(bitmap);

    _img_init();
    if (1 == argc) {
        // REPL loop
        retval = repl_driver(1, 1, NULL);
    } else {
        FILE *fp = NULL;
        char *buf = NULL;
        long filesize;

        // XXX b - to prevent translating \r\n to \n!
        fp = fopen(argv[1], "rb");
        if (!fp) {
            fprintf(stderr, "Can not open '%s'!\n", argv[1]);
            retval = 255;
            goto closefile;
        }
        fseek(fp, 0, SEEK_END);
        buf = malloc((filesize=ftell(fp)) + _WRAPPER_SIZE + 10); // add for wrapper
        if (!buf) {
            fprintf(stderr, "Not enought memory!\n");
            retval = 255;
            goto freebuf;
        }
        // all is OK here
        strcpy(buf, _wrapper);
        fseek(fp, 0, SEEK_SET);
        fread(buf + _WRAPPER_SIZE, sizeof (char), filesize, fp);
        for (i = _WRAPPER_SIZE; i < _WRAPPER_SIZE + filesize; i++) {
            if (buf[i] == '\n' || buf[i] == '\r')
                buf[i] = ' ';
        }
        strcpy(buf + i, "))");
        retval = repl_c_string(buf, 1, 1, 1);
freebuf:
        free(buf);
        buf = NULL;
closefile:
        fclose(fp);
        fp = NULL;
    }
    printf("done with %d\n", retval);
    return (retval);
}

// }}}

Changes to test12.scm.

1
2
3
4
5
6
(load "conv.scm")
(define b (img_open "boo.jpg"))
(img_conv b edge-matrix 3 60)
(img_bw b 50)
(img_save b "out/booedge.jpg")

|





1
2
3
4
5
6
(load "imsh.scm")
(define b (img_open "boo.jpg"))
(img_conv b edge-matrix 3 60)
(img_bw b 50)
(img_save b "out/booedge.jpg")

Changes to test2.scm.

1
2
3
4
(load "conv.scm")
(define b (img_open "ngirl.jpg"))
(img_conv b emboss-matrix emboss-div emboss-shift)
(img_save b "out/emboss.jpg")
|



1
2
3
4
(load "imsh.scm")
(define b (img_open "ngirl.jpg"))
(img_conv b emboss-matrix emboss-div emboss-shift)
(img_save b "out/emboss.jpg")

Changes to test4.scm.

1
2
3
4
(load "conv.scm")
(define b (img_open "ngirl.jpg"))
(img_conv b edge-matrix 3 60)
(img_save b "out/edge.jpg")
|



1
2
3
4
(load "imsh.scm")
(define b (img_open "ngirl.jpg"))
(img_conv b edge-matrix 3 60)
(img_save b "out/edge.jpg")

Changes to test5.scm.

1
2
3
4
(load "conv.scm")
(define b (img_open "ngirl.jpg"))
(img_grl b 6)
(img_save b "out/grl.jpg")
|



1
2
3
4
(load "imsh.scm")
(define b (img_open "ngirl.jpg"))
(img_grl b 6)
(img_save b "out/grl.jpg")

Changes to test6.scm.

1
2
3
4
5
(load "conv.scm")
(define b (img_open "ngirl.jpg"))
(img_bw b 50)
(img_conv b edge-matrix 3 40)
(img_save b "out/bwedge.jpg")
|




1
2
3
4
5
(load "imsh.scm")
(define b (img_open "ngirl.jpg"))
(img_bw b 50)
(img_conv b edge-matrix 3 40)
(img_save b "out/bwedge.jpg")

Changes to test7.scm.

1
2
3
4
5
6
(load "conv.scm")
(define b (img_open "ngirl.jpg"))
(img_bw b 60)
(img_conv b dilat-matrix dilat-div dilat-shift)
(img_conv b dilat-matrix dilat-div dilat-shift)
(img_save b "out/dilat2.jpg")
|





1
2
3
4
5
6
(load "imsh.scm")
(define b (img_open "ngirl.jpg"))
(img_bw b 60)
(img_conv b dilat-matrix dilat-div dilat-shift)
(img_conv b dilat-matrix dilat-div dilat-shift)
(img_save b "out/dilat2.jpg")

Changes to test8.scm.

1
2
3
4
5
6
7
8
(load "conv.scm")
(define b (img_open "ngirl.jpg"))
(img_pix b 10 1)
(img_save b "out/pix1.jpg")

(define b (img_open "ngirl.jpg"))
(img_pix b 5 0)
(img_save b "out/pix2.jpg")
|







1
2
3
4
5
6
7
8
(load "imsh.scm")
(define b (img_open "ngirl.jpg"))
(img_pix b 10 1)
(img_save b "out/pix1.jpg")

(define b (img_open "ngirl.jpg"))
(img_pix b 5 0)
(img_save b "out/pix2.jpg")

Changes to test9.scm.

1
2
3
4
(load "conv.scm")
(define b (img_open "ngirl.jpg"))
(img_med b 9)
(img_save b "out/med.jpg")
|



1
2
3
4
(load "imsh.scm")
(define b (img_open "ngirl.jpg"))
(img_med b 9)
(img_save b "out/med.jpg")