%include "inc:util.imp"
%include "iff:iffinc.imp"
%include "level1:graphinc.imp"
!Program recombines three monochrome images into an RGB image using half-tones.

%begin
%record (iffhdr fm) iffin, iffout
%halfarray map(0:255)
%string (255) param, rfile,gfile,bfile,outfile
%integerarray hist(0:255)
%owninteger i,j,k,l,rc,r,g,b,ri,gi,bi,x,m,p,q
%real rd,gd,bd

%routine Mix (%byte Col, %integer Red, Green, Blue)
   Map(Col)=Red+Green<<5+Blue<<10
%end

%routine countfile(%integer image, %integerarrayname hist, %realname density)
   %integer i,c,d
   d=0; density=0 ;!32-bit integer should be OK.
   {%for i=0, 1, 255 %cycle; hist(i)=0; %repeat}
   %for i=0,1,iffin_ht*iffin_wid-1 %cycle
      c = byteinteger(image+i)
      {hist(c) = hist(c)+1}; d=d+c
   %repeat
   density = d/(iffin_ht*iffin_wid)
%end

!***** Set up the colour map *****
Offset (0,0)
enable(16_FF)
clear
%for i=0, 1, 31 %cycle; mix(i,    i, 0, 0); %repeat
%for i=0, 1, 31 %cycle; mix(i+32, 0, i, 0); %repeat
%for i=0, 1, 31 %cycle; mix(i+64, 0, 0, i); %repeat
%for i=96, 1, 255 %cycle; map(i)=0; %repeat
update colour map(map(0))

!***** 1: Split the command line *****

param = cli param
outfile = "" %unless param -> param.("/").outfile
printline("Parameters?") %and %return %unless param -> rfile.(",").gfile %and %c
gfile -> gfile.(",").bfile

!***** 1: read in the images *****
r=0
rc = iff readin(rfile, iffin, r)
iff show header(iffin, 0)
printline("Problem with ".rfile) %and %stop %if rc#0
countfile(r, hist, rd)

g=0
rc = iff readin(gfile, iffin, g)
iff show header(iffin, 0)
printline("Problem with ".gfile) %and %stop %if rc#0
countfile(g, hist, gd)

b=0
rc = iff readin(bfile, iffin, b)
iff show header(iffin, 0)
printline("Problem with ".bfile) %and %stop %if rc#0
countfile(b, hist, bd)

printstring("Images read. weights (R,G,B): ")
print(rd, 3,3); print(gd, 3,3); print(bd, 3,3); newline
rd=96/rd; rd=1 %if rd<1
gd=96/gd; gd=1 %if gd<1
bd=96/bd; bd=1 %if bd<1

!***** 2: Combine the images *****

p=0; q=heapget(iffin_wid*iffin_ht*4); k=q; l=q+iffin_wid*2
%for i=iffin_ht-1, -1, 0 %cycle
   m=k
   %for j=0, 1, iffin_wid-1 %cycle
     ri=int(byteinteger(r+p)*rd)>>3; ri=31 %if ri>31
     gi=int(byteinteger(g+p)*gd)>>3; gi=31 %if gi>31
     gi=gi + 32
     bi=int(byteinteger(b+p)*bd)>>3; bi=31 %if bi>31
     bi=bi + 64
     byteinteger(k)=ri; byteinteger(k+1)=gi
     byteinteger(l)=bi; byteinteger(l+1)=0
     p=p+1; k=k+2; l=l+2
   %repeat
   k=k+iffin_wid+iffin_wid
   l=l+iffin_wid+iffin_wid
   col fill(0, i*2, iffin_wid*2-1, i*2+1, byteinteger(m))
%repeat

!!col fill(0,0,iffin_wid*2-1,iffin_ht*2-1, byteinteger(q))
  
!***** 3: Now write the modified picture back to OUTFILE *****

%if outfile # "" %start
   iffout=iffin
   iffout_mapaddr = addr(map(0)); iffout_maplen=256; iffout_mapwid=16
   iffout_hlen=0
   iffout_wid=iffin_wid*2; iffout_ht=iffin_ht*2

   rc = iff writeout(outfile, iffout, q)
   write(rc, 3); newline
%finish

%endofprogram
