;coluniv  --  universal colour image
; Usage:
;        *coluniv <dest.im> <basename> #red #green #blue
; dest.im.   image to put the result in
; basename   basename of colour image on disk, e.g. baboo
; #red, etc. number of levels per colour (e.g. 6, 7, 6)
;
; Expects: 
;   3 images on disk: <basename>r, <basename>g and <basename>b
;
#define DITHER    1
parms
  file destim         ;1st. param: destination image
  string target       ;2nd. param: basename of colour image (e.g. baboon)
  int nred            ;number of levels for red
  int ngreen          ;idem green
  int nblue           ;idem blue
endparms
char tmp[100]         ;character array to assemble file names
file img              ;image variable
file klad = "a"       ;klad-image
int colmode = PIX8    ;default colour mode
int err

if (nred*ngreen*nblue) > 256
  if ((((improp destim) & PIXMASK) == PIX12) || (((improp destim) & PIXMASK) == PIX16))
    colmode = PIX12
  else
     print "Product of colour levels must be < 256"
     stop 1
  endif
endif

if (nred == 1) || (ngreen == 1) || (nblue == 1)
 colmode = DITHER
endif

if ((improp destim) & DIS_BIT) == DIS_BIT
  switch colmode
    case DITHER
	  err = chk lut 2 6 5 6
    case PIX12
	  err = chk lut 2 1 110 16 16 16
    case PIX8
	  err = chk lut 2 6 10 nred ngreen nblue
  endsw
elseif ((improp destim) & WIN_BIT) == WIN_BIT
  switch colmode
    case DITHER
      lut 3 1 5 6
    case PIX8
      lut 3 1 10 nred ngreen nblue
    default
      call error
  endsw
else
  print "ILLEGAL IMAGE SPECIFIED"
  beep
  stop 1
endif

dest klad                         ;tmp
fprint tmp 0 "%s%s" target, "b"
img = tmp

switch colmode       ;BLUE
  case DITHER
    dot img 
    keep 8           ;keep the most significant bitplane
  case PIX8
    mul img nblue    ;get blue img, scale to 'nblue' levels
  case PIX12
    shr img 4        ;shifting down the 4 upper bitplanes into the lower
endsw
copy klad destim     ;the blue image is the lowest

fprint tmp 0 "%s%s" target, "g"
img = tmp

switch colmode        ;GREEN
  case DITHER
    dot img
    keep 7
  case PIX8
    mul img ngreen       ;get green img, scale to 'ngreen' levels
    mul (nblue*256)      ;green is on to of blue
  case PIX12
    and img 0xf0         ;keep the 4 upper biplanes
endsw
;add klad destim >destim
add klad destim
save destim

fprint tmp 0 "%s%s" target, "r"
img = tmp

switch colmode            ;RED
  case DITHER
    dot img
    keep 6
	dest destim
    add klad destim
  case PIX8
    mul img nred         ;get red img, scale to 'nred' levels
    mul (nblue*ngreen*256) ;red is on top of blue and green
	dest destim
    add klad destim
  case PIX12
    shr img 4
    ovl destim 2
    save destim
    ovl destim 0    
endsw

stop 0

error:
   beep
   print "Illegal parameter combination"
return
