+/*
+=item is_channel_copy(coeff, outchan, inchan, chan_copy_info)
+
+Test if the coefficients represent just copying channels around, and
+initialize lists of the channels to copy, zero or set to max.
+
+=cut
+*/
+
+static
+int is_channel_copy(i_img *im, const double *coeff, int outchan, int inchan,
+ struct chan_copy *info) {
+ int srcchan[MAXCHANNELS];
+ int onechan[MAXCHANNELS];
+ int i, j;
+ int ilimit = im->channels > inchan ? inchan : im->channels;
+
+ for (j = 0; j < outchan; ++j) {
+ srcchan[j] = -1;
+ onechan[j] = 0;
+ }
+
+ for (j = 0; j < outchan; ++j) {
+ for (i = 0; i < ilimit; ++i) {
+ if (coeff[i+inchan*j] == 1.0) {
+ if (srcchan[j] != -1) {
+ /* from two or more channels, not a copy */
+ return 0;
+ }
+ srcchan[j] = i;
+ }
+ else if (coeff[i+inchan*j]) {
+ /* some other non-zero value, not a copy */
+ return 0;
+ }
+ }
+ if (i < inchan) {
+ if (coeff[i+inchan*j] == 1.0) {
+ if (srcchan[j] != -1) {
+ /* can't do both */
+ return 0;
+ }
+ onechan[j] = 1;
+ }
+ else if (coeff[i+inchan*j]) {
+ /* some other non-zero value, not a copy */
+ return 0;
+ }
+ }
+ }
+
+ /* build our working data structures */
+ info->copy_count = info->zero_count = info->one_count = 0;
+ for (j = 0; j < outchan; ++j) {
+ if (srcchan[j] != -1) {
+ info->from[info->copy_count] = srcchan[j];
+ info->to[info->copy_count] = j;
+ ++info->copy_count;
+ }
+ else if (onechan[j]) {
+ info->one[info->one_count] = j;
+ ++info->one_count;
+ }
+ else {
+ info->zero[info->zero_count] = j;
+ ++info->zero_count;
+ }
+ }
+
+#if 0
+ {
+ for (i = 0; i < info->copy_count; ++i) {
+ printf("From %d to %d\n", info->from[i], info->to[i]);
+ }
+ for (i = 0; i < info->one_count; ++i) {
+ printf("One %d\n", info->one[i]);
+ }
+ for (i = 0; i < info->zero_count; ++i) {
+ printf("Zero %d\n", info->zero[i]);
+ }
+ fflush(stdout);
+ }
+#endif
+
+ return 1;
+}
+
+/*
+=item convert_via_copy(im, src, chan_copy_info)
+
+Perform a convert that only requires channel copies.
+
+=cut
+*/
+
+static i_img *
+convert_via_copy(i_img *im, i_img *src, struct chan_copy *info) {
+#code src->bits <= i_8_bits
+ IM_COLOR *in_line = mymalloc(sizeof(IM_COLOR) * src->xsize);
+ IM_COLOR *out_line = mymalloc(sizeof(IM_COLOR) * src->xsize);
+ i_img_dim x, y;
+ int i;
+ IM_COLOR *inp, *outp;
+
+ for (y = 0; y < src->ysize; ++y) {
+ IM_GLIN(src, 0, src->xsize, y, in_line);
+
+ inp = in_line;
+ outp = out_line;
+ for (x = 0; x < src->xsize; ++x) {
+ for (i = 0; i < info->copy_count; ++i) {
+ outp->channel[info->to[i]] = inp->channel[info->from[i]];
+ }
+ for (i = 0; i < info->one_count; ++i) {
+ outp->channel[info->one[i]] = IM_SAMPLE_MAX;
+ }
+ for (i = 0; i < info->zero_count; ++i) {
+ outp->channel[info->zero[i]] = 0;
+ }
+ ++inp;
+ ++outp;
+ }
+
+ IM_PLIN(im, 0, src->xsize, y, out_line);
+ }
+
+ myfree(in_line);
+ myfree(out_line);
+#/code
+
+ return im;
+}
+