/**********************************************************************
 * testflat -- test read and write for flat field                     *
 *                                                                    *
 * Version 0.7.6.3 21 January 2007                                    *
 *                                                                    *
 *                          Paul Ellis and                            *
 *         Herbert J. Bernstein (yaya@bernstein-plus-sons.com)        *
 *                                                                    *
 * (C) Copyright 2007 Herbert J. Bernstein                            *
 *                                                                    *
 **********************************************************************/

/**********************************************************************
 *                                                                    *
 * YOU MAY REDISTRIBUTE THE CBFLIB PACKAGE UNDER THE TERMS OF THE GPL *
 * WHILE YOU MAY ALTERNATIVE DISTRIBUTE THE API UNDER THE LGPL        *
 * YOU MAY ***NOT*** DISTRBUTE THIS PROGRAM UNDER THE LGPL            *
 *                                                                    *                                                                    *
 **********************************************************************/

/*************************** GPL NOTICES ******************************
 *                                                                    *
 * This program is free software; you can redistribute it and/or      *
 * modify it under the terms of the GNU General Public License as     *
 * published by the Free Software Foundation; either version 2 of     *
 * (the License, or (at your option) any later version.               *
 *                                                                    *
 * This program is distributed in the hope that it will be useful,    *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of     *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *
 * GNU General Public License for more details.                       *
 *                                                                    *
 * You should have received a copy of the GNU General Public License  *
 * along with this program; if not, write to the Free Software        *
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA           *
 * 02111-1307  USA                                                    *
 *                                                                    *
 **********************************************************************/


/**********************************************************************
 *                                                                    *
 *                    Stanford University Notices                     *
 *  for the CBFlib software package that incorporates SLAC software   *
 *                 on which copyright is disclaimed                   *
 *                                                                    *
 * This software                                                      *
 * -------------                                                      *
 * The term 'this software', as used in these Notices, refers to      *
 * those portions of the software package CBFlib that were created by *
 * employees of the Stanford Linear Accelerator Center, Stanford      *
 * University.                                                        *
 *                                                                    *
 * Stanford disclaimer of copyright                                   *
 * --------------------------------                                   *
 * Stanford University, owner of the copyright, hereby disclaims its  *
 * copyright and all other rights in this software.  Hence, anyone    *
 * may freely use it for any purpose without restriction.             *
 *                                                                    *
 * Acknowledgement of sponsorship                                     *
 * ------------------------------                                     *
 * This software was produced by the Stanford Linear Accelerator      *
 * Center, Stanford University, under Contract DE-AC03-76SFO0515 with *
 * the Department of Energy.                                          *
 *                                                                    *
 * Government disclaimer of liability                                 *
 * ----------------------------------                                 *
 * Neither the United States nor the United States Department of      *
 * Energy, nor any of their employees, makes any warranty, express or *
 * implied, or assumes any legal liability or responsibility for the  *
 * accuracy, completeness, or usefulness of any data, apparatus,      *
 * product, or process disclosed, or represents that its use would    *
 * not infringe privately owned rights.                               *
 *                                                                    *
 * Stanford disclaimer of liability                                   *
 * --------------------------------                                   *
 * Stanford University makes no representations or warranties,        *
 * express or implied, nor assumes any liability for the use of this  *
 * software.                                                          *
 *                                                                    *
 * Maintenance of notices                                             *
 * ----------------------                                             *
 * In the interest of clarity regarding the origin and status of this *
 * software, this and all the preceding Stanford University notices   *
 * are to remain affixed to any copy or derivative of this software   *
 * made or distributed by the recipient and are to be affixed to any  *
 * copy of software made or distributed by the recipient that         *
 * contains a copy or derivative of this software.                    *
 *                                                                    *
 * Based on SLAC Software Notices, Set 4                              *
 * OTT.002a, 2004 FEB 03                                              *
 **********************************************************************/


/**********************************************************************
 *                                 NOTICE                             *
 * Creative endeavors depend on the lively exchange of ideas. There   *
 * are laws and customs which establish rights and responsibilities   *
 * for authors and the users of what authors create.  This notice     *
 * is not intended to prevent you from using the software and         *
 * documents in this package, but to ensure that there are no         *
 * misunderstandings about terms and conditions of such use.          *
 *                                                                    *
 * Please read the following notice carefully.  If you do not         *
 * understand any portion of this notice, please seek appropriate     *
 * professional legal advice before making use of the software and    *
 * documents included in this software package.  In addition to       *
 * whatever other steps you may be obliged to take to respect the     *
 * intellectual property rights of the various parties involved, if   *
 * you do make use of the software and documents in this package,     *
 * please give credit where credit is due by citing this package,     *
 * its authors and the URL or other source from which you obtained    *
 * it, or equivalent primary references in the literature with the    *
 * same authors.                                                      *
 *                                                                    *
 * Some of the software and documents included within this software   *
 * package are the intellectual property of various parties, and      *
 * placement in this package does not in any way imply that any       *
 * such rights have in any way been waived or diminished.             *
 *                                                                    *
 * With respect to any software or documents for which a copyright    *
 * exists, ALL RIGHTS ARE RESERVED TO THE OWNERS OF SUCH COPYRIGHT.   *
 *                                                                    *
 * Even though the authors of the various documents and software      *
 * found here have made a good faith effort to ensure that the        *
 * documents are correct and that the software performs according     *
 * to its documentation, and we would greatly appreciate hearing of   *
 * any problems you may encounter, the programs and documents any     *
 * files created by the programs are provided **AS IS** without any   *
 * warranty as to correctness, merchantability or fitness for any     *
 * particular or general use.                                         *
 *                                                                    *
 * THE RESPONSIBILITY FOR ANY ADVERSE CONSEQUENCES FROM THE USE OF    *
 * PROGRAMS OR DOCUMENTS OR ANY FILE OR FILES CREATED BY USE OF THE   *
 * PROGRAMS OR DOCUMENTS LIES SOLELY WITH THE USERS OF THE PROGRAMS   *
 * OR DOCUMENTS OR FILE OR FILES AND NOT WITH AUTHORS OF THE          *
 * PROGRAMS OR DOCUMENTS.                                             *
 **********************************************************************/

/**********************************************************************
 *                                                                    *
 *                           The IUCr Policy                          *
 *      for the Protection and the Promotion of the STAR File and     *
 *     CIF Standards for Exchanging and Archiving Electronic Data     *
 *                                                                    *
 * Overview                                                           *
 *                                                                    *
 * The Crystallographic Information File (CIF)[1] is a standard for   *
 * information interchange promulgated by the International Union of  *
 * Crystallography (IUCr). CIF (Hall, Allen & Brown, 1991) is the     *
 * recommended method for submitting publications to Acta             *
 * Crystallographica Section C and reports of crystal structure       *
 * determinations to other sections of Acta Crystallographica         *
 * and many other journals. The syntax of a CIF is a subset of the    *
 * more general STAR File[2] format. The CIF and STAR File approaches *
 * are used increasingly in the structural sciences for data exchange *
 * and archiving, and are having a significant influence on these     *
 * activities in other fields.                                        *
 *                                                                    *
 * Statement of intent                                                *
 *                                                                    *
 * The IUCr's interest in the STAR File is as a general data          *
 * interchange standard for science, and its interest in the CIF,     *
 * a conformant derivative of the STAR File, is as a concise data     *
 * exchange and archival standard for crystallography and structural  *
 * science.                                                           *
 *                                                                    *
 * Protection of the standards                                        *
 *                                                                    *
 * To protect the STAR File and the CIF as standards for              *
 * interchanging and archiving electronic data, the IUCr, on behalf   *
 * of the scientific community,                                       *
 *                                                                    *
 * * holds the copyrights on the standards themselves,                *
 *                                                                    *
 * * owns the associated trademarks and service marks, and            *
 *                                                                    *
 * * holds a patent on the STAR File.                                 *
 *                                                                    *
 * These intellectual property rights relate solely to the            *
 * interchange formats, not to the data contained therein, nor to     *
 * the software used in the generation, access or manipulation of     *
 * the data.                                                          *
 *                                                                    *
 * Promotion of the standards                                         *
 *                                                                    *
 * The sole requirement that the IUCr, in its protective role,        *
 * imposes on software purporting to process STAR File or CIF data    *
 * is that the following conditions be met prior to sale or           *
 * distribution.                                                      *
 *                                                                    *
 * * Software claiming to read files written to either the STAR       *
 * File or the CIF standard must be able to extract the pertinent     *
 * data from a file conformant to the STAR File syntax, or the CIF    *
 * syntax, respectively.                                              *
 *                                                                    *
 * * Software claiming to write files in either the STAR File, or     *
 * the CIF, standard must produce files that are conformant to the    *
 * STAR File syntax, or the CIF syntax, respectively.                 *
 *                                                                    *
 * * Software claiming to read definitions from a specific data       *
 * dictionary approved by the IUCr must be able to extract any        *
 * pertinent definition which is conformant to the dictionary         *
 * definition language (DDL)[3] associated with that dictionary.      *
 *                                                                    *
 * The IUCr, through its Committee on CIF Standards, will assist      *
 * any developer to verify that software meets these conformance      *
 * conditions.                                                        *
 *                                                                    *
 * Glossary of terms                                                  *
 *                                                                    *
 * [1] CIF:  is a data file conformant to the file syntax defined     *
 * at http://www.iucr.org/iucr-top/cif/spec/index.html                *
 *                                                                    *
 * [2] STAR File:  is a data file conformant to the file syntax       *
 * defined at http://www.iucr.org/iucr-top/cif/spec/star/index.html   *
 *                                                                    *
 * [3] DDL:  is a language used in a data dictionary to define data   *
 * items in terms of "attributes". Dictionaries currently approved    *
 * by the IUCr, and the DDL versions used to construct these          *
 * dictionaries, are listed at                                        *
 * http://www.iucr.org/iucr-top/cif/spec/ddl/index.html               *
 *                                                                    *
 * Last modified: 30 September 2000                                   *
 *                                                                    *
 * IUCr Policy Copyright (C) 2000 International Union of              *
 * Crystallography                                                    *
 **********************************************************************/

/**********************************************************************
 *                            SYNOPSIS                                *
 *                                                                    *
 *  testflat                                                          *
 *                                                                    *
 **********************************************************************/


#include "cbf.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
#include <unistd.h>


int local_exit (int status);

int outerror(int err)
{

  if ((err&CBF_FORMAT)==CBF_FORMAT)
    fprintf(stderr, " testflat: The file format is invalid.\n");
  if ((err&CBF_ALLOC)==CBF_ALLOC)
    fprintf(stderr, " testflat Memory allocation failed.\n");
  if ((err&CBF_ARGUMENT)==CBF_ARGUMENT)
    fprintf(stderr, " testflat: Invalid function argument.\n");
  if ((err&CBF_ASCII)==CBF_ASCII)
    fprintf(stderr, " testflat: The value is ASCII (not binary).\n");
  if ((err&CBF_BINARY)==CBF_BINARY)
    fprintf(stderr, " testflat: The value is binary (not ASCII).\n");
  if ((err&CBF_BITCOUNT)==CBF_BITCOUNT)
    fprintf(stderr, " testflat: The expected number of bits does"
      " not match the actual number written.\n");
  if ((err&CBF_ENDOFDATA)==CBF_ENDOFDATA)
    fprintf(stderr, " testflat: The end of the data was reached"
     " before the end of the array.\n");
  if ((err&CBF_FILECLOSE)==CBF_FILECLOSE)
    fprintf(stderr, " testflat: File close error.\n");
  if ((err&CBF_FILEOPEN)==CBF_FILEOPEN)
    fprintf(stderr, " testflat: File open error.\n");
  if ((err&CBF_FILEREAD)==CBF_FILEREAD)
    fprintf(stderr, " testflat: File read error.\n");
  if ((err&CBF_FILESEEK)==CBF_FILESEEK)
    fprintf(stderr, " testflat: File seek error.\n");
  if ((err&CBF_FILETELL)==CBF_FILETELL)
    fprintf(stderr, " testflat: File tell error.\n");
  if ((err&CBF_FILEWRITE)==CBF_FILEWRITE)
    fprintf(stderr, " testflat: File write error.\n");
  if ((err&CBF_IDENTICAL)==CBF_IDENTICAL)
    fprintf(stderr, " testflat: A data block with the new name already exists.\n");
  if ((err&CBF_NOTFOUND)==CBF_NOTFOUND)
    fprintf(stderr, " testflat: The data block, category, column or"
      " row does not exist.\n");
  if ((err&CBF_OVERFLOW)==CBF_OVERFLOW)
    fprintf(stderr, " testflat: The number read cannot fit into the "
      "destination argument.\n        The destination has been set to the nearest value.\n");
  if ((err& CBF_UNDEFINED)==CBF_UNDEFINED)
    fprintf(stderr, " testflat: The requested number is not defined (e.g. 0/0).\n");
  if ((err&CBF_NOTIMPLEMENTED)==CBF_NOTIMPLEMENTED)
    fprintf(stderr, " testflat: The requested functionality is not yet implemented.\n");
  return 0;

}


#undef cbf_failnez
#define cbf_failnez(x) \
 {int xerr; \
  xerr = (x); \
  if (xerr) { \
    fprintf(stderr," testflat: CBFlib fatal error %d\n",xerr); \
    outerror(xerr);   \
    outusage();      \
    local_exit (-1); \
  } \
 }



int outusage ( void ) {

 fprintf(stderr," \n Usage:\n");
 fprintf(stderr,"  testflat \\\n");
 fprintf(stderr," Requires testflatin.cbf\n ");
 fprintf(stderr," Creates  testflatout.cbf\n ");
 return -1;

}

int main (int argc, char *argv [])
{
  cbf_handle incbf=NULL, cbf=NULL;

  FILE *in, *out;

  int *image;

  size_t numread, nelem, elsize;

  unsigned int compression;

  int id, elsigned, elunsigned, maxel, minel;

  short *shimage;

  int i, j, k;

  /* Read the input test file */

  if (!(in = fopen ("testflatin.cbf", "rb"))) {
     fprintf (stderr,"testflat: Couldn't open the input imgCIF file %s\n",
     "testflatin.cbf");
  } else {

    const char * byteorder;

    size_t dim1, dim2, dim3, padding;

    cbf_failnez (cbf_make_handle (&incbf))

    cbf_failnez (cbf_read_file (incbf, in, MSG_DIGEST))

    cbf_failnez(cbf_find_datablock(incbf,"testflat"))

    cbf_failnez(cbf_find_category(incbf,"array_data"))

    cbf_failnez(cbf_find_column(incbf,"data"))

    cbf_failnez(cbf_rewind_row(incbf))

    cbf_failnez (	(image = (int *)malloc(sizeof(int)*1000000))==NULL?CBF_ALLOC:0);

    cbf_failnez (cbf_get_integerarrayparameters_wdims (incbf, &compression, &id, &elsize, &elsigned,
                    &elunsigned, &nelem, &maxel, &minel, &byteorder, 	&dim1, &dim2, &dim3, &padding))

    fprintf (stderr,"testflat: element size %ld, element signed %d, element unsigned %d\n",
                    (long)elsize, elsigned, elunsigned );
    fprintf (stderr,"testflat: byte order %s, dimensions %ld, %ld, padding %ld\n",
                    byteorder, (long)dim1, (long)dim2, (long)padding);

    if (compression != CBF_BYTE_OFFSET) fprintf(stderr, "testflat: Compression %x instead of CBF_BYTE_OFFSET\n", compression);

    if (elsize != sizeof(int)) fprintf(stderr,"testflat: element size %ld instead of %d\n", (long)elsize, (int)sizeof(int));

    cbf_failnez (cbf_get_integerarray (incbf, NULL,
                               image, sizeof (int), 0,
                               nelem, &numread))

    if (numread != 1000000) fprintf(stderr,"testflat: Read %ld instead of 1000000 ints\n", (long)numread);
    for (i = 0; i < 1000000; i++) {
  	if (image[i] != 1000) {
  		fprintf(stderr,"testflat: Mismatch for index %d, int value in file %d !=  %d\n",
  		  i, image[i], 1000);
  		/* exit(-1); */
  	}
    }

    free(image);

    cbf_failnez(cbf_next_row(incbf))

    cbf_failnez (	(shimage = (short *)malloc(sizeof(short)*1000000))==NULL?CBF_ALLOC:0);

    cbf_failnez (cbf_get_integerarrayparameters_wdims (incbf, &compression, &id, &elsize, &elsigned,
                    &elunsigned, &nelem, &maxel, &minel, &byteorder, 	&dim1, &dim2, &dim3, &padding))

    fprintf (stderr,"testflat: element size %ld, element signed %d, element unsigned %d\n",
                    (long)elsize, elsigned, elunsigned );
    fprintf (stderr,"testflat: byte order %s, dimensions %ld, %ld, padding %ld\n",
                    byteorder, (long)dim1, (long)dim2, (long)padding);

    if (compression != CBF_BYTE_OFFSET) fprintf(stderr, "testflat: Compression %x instead of CBF_BYTE_OFFSET\n", compression);

    if (elsize != sizeof(short)) fprintf(stderr,"testflat: element size %ld instead of %d\n", (long)elsize, (int)sizeof(short));


    cbf_failnez (cbf_get_integerarray (incbf, NULL,
                               shimage, sizeof (short), 0,
                               1000000,&numread))
    if (numread != 1000000) fprintf(stderr,"testflat: Read %ld instead of 1000000 shorts\n", (long)numread);
    for (i = 0; i < 1000000; i++) {
  	if (shimage[i] != 1000) {
  		fprintf(stderr,"testflat:  Mismatch for index %d, short value in file %d !=  %d\n",
  		  i, shimage[i], 1000);
  		/* exit(-1); */
  	}
    }

    free(shimage);

    cbf_failnez(cbf_next_row(incbf))

    cbf_failnez (	(image = (int *)malloc(sizeof(int)*1000000))==NULL?CBF_ALLOC:0);

    cbf_failnez (cbf_get_integerarrayparameters_wdims (incbf, &compression, &id, &elsize, &elsigned,
                    &elunsigned, &nelem, &maxel, &minel, &byteorder, 	&dim1, &dim2, &dim3, &padding))

    fprintf (stderr,"testflat: element size %ld, element signed %d, element unsigned %d\n",
                    (long)elsize, elsigned, elunsigned );
    fprintf (stderr,"testflat: byte order %s, dimensions %ld, %ld, padding %ld\n",
                    byteorder, (long)dim1, (long)dim2, (long)padding);

    if (compression != CBF_BYTE_OFFSET) fprintf(stderr, "testflat: Compression %x instead of CBF_BYTE_OFFSET\n", compression);

    if (elsize != sizeof(int)) fprintf(stderr,"testflat: element size %ld instead of %d\n", (long)elsize, (int)sizeof(int));

    cbf_failnez (cbf_get_integerarray (incbf, NULL,
                               image, sizeof (int), 1,
                               nelem, &numread))

    if (numread != 1000000) fprintf(stderr,"testflat: Read %ld instead of 1000000 ints\n", (long)numread);


    for (i = 0; i < 1000; i++) {

      for (j = 0; j < 1000; j++) {

        int dtarg;

        dtarg = 1000;

        if (i == j || i == 999-j) dtarg = -3;

  	    if (image[i+j*1000] != dtarg)

  	      fprintf(stderr,"testflat:  Mismatch for index %d, int value in file %d !=  %d\n",
  		        i+j*1000, image[i+j*1000], dtarg);

      }

    }

    free(image);

    cbf_failnez(cbf_next_row(incbf))

    cbf_failnez (	(shimage = (short *)malloc(sizeof(short)*1000000))==NULL?CBF_ALLOC:0);

    cbf_failnez (cbf_get_integerarrayparameters_wdims (incbf, &compression, &id, &elsize, &elsigned,
                    &elunsigned, &nelem, &maxel, &minel, &byteorder, 	&dim1, &dim2, &dim3, &padding))

    fprintf (stderr,"testflat: element size %ld, element signed %d, element unsigned %d\n",
                    (long)elsize, elsigned, elunsigned );
    fprintf (stderr,"testflat: byte order %s, dimensions %ld, %ld, padding %ld\n",
                    byteorder, (long)dim1, (long)dim2, (long)padding);

    if (compression != CBF_BYTE_OFFSET) fprintf(stderr, "testflat: Compression %x instead of CBF_BYTE_OFFSET\n", compression);

    if (elsize != sizeof(short)) fprintf(stderr,"testflat: element size %ld instead of %d\n", (long)elsize, (int)sizeof(short));


    cbf_failnez (cbf_get_integerarray (incbf, NULL,
                               shimage, sizeof (short), 1,
                               1000000,&numread))
    if (numread != 1000000) fprintf(stderr,"testflat: Read %ld instead of 1000000 shorts\n", (long)numread);

    for (i = 0; i < 1000; i++) {

      for (j = 0; j < 1000; j++) {

        short dtarg;

        dtarg = 1000;

        if (i == j || i == 999-j) dtarg = -3;

  	    if (shimage[i+j*1000] != dtarg)

  	          fprintf(stderr,"testflat:  Mismatch for index %d, short value in file %d !=  %d\n",
  		        i+j*1000, shimage[i+j*1000], dtarg);


      }

    }

    free(shimage);

        cbf_failnez(cbf_next_row(incbf))

    cbf_failnez (	(image = (int *)malloc(sizeof(int)*50*60*70))==NULL?CBF_ALLOC:0);

    cbf_failnez (cbf_get_integerarrayparameters_wdims (incbf, &compression, &id, &elsize, &elsigned,
                    &elunsigned, &nelem, &maxel, &minel, &byteorder, 	&dim1, &dim2, &dim3, &padding))

    fprintf (stderr,"testflat: element size %ld, element signed %d, element unsigned %d\n",
                    (long)elsize, elsigned, elunsigned );
    fprintf (stderr,"testflat: byte order %s, dimensions %ld, %ld, %ld, padding %ld\n",
                    byteorder, (long)dim1, (long)dim2, (long)dim3, (long)padding);

    if (compression != CBF_BYTE_OFFSET) fprintf(stderr, "testflat: Compression %x instead of CBF_BYTE_OFFSET\n", compression);

    if (elsize != sizeof(int)) fprintf(stderr,"testflat: element size %ld instead of %d\n", (long)elsize, (int)sizeof(int));

    cbf_failnez (cbf_get_integerarray (incbf, NULL,
                               image, sizeof (int), 1,
                               nelem, &numread))

    if (numread != 50*60*70) fprintf(stderr,"testflat: Read %ld instead of 50*60*70 ints\n", (long)numread);


    for (i = 0; i < 50; i++) {

      for (j = 0; j < 60; j++) {

        for (k = 0; k < 70; k++) {

      	  int dtarg;

      	  dtarg = 1000;

      	  if (i == j || j == k ) dtarg = -3;

  	      if ((i + j*50 + k*50*60)%1000 == 0) dtarg = i+j+k;

  	      if (image[i + j*50 + k*50*60] != dtarg)

  	        fprintf(stderr,"testflat:  Mismatch for index %d, int value in file %d !=  %d\n",
  		      i + j*50 + k*50*60, image[i + j*50 + k*50*60], dtarg );
  		
        }

      }

    }

    free(image);





  }


  cbf_failnez (cbf_make_handle (&cbf))

  cbf_failnez(cbf_new_datablock(cbf,"testflat"))

  cbf_failnez(cbf_new_category(cbf,"array_data"))

  cbf_failnez(cbf_new_column(cbf,"data"))

  cbf_failnez(cbf_new_row(cbf))



/*  Create an  array 1000 x 1000 ints in a flat field of 1000 */

  cbf_failnez (	(image = (int *)malloc(sizeof(int)*1000000))==NULL?CBF_ALLOC:0);

  for (i = 0; i < 1000000; i++) {
  	image[i] = 1000;
  }


  cbf_failnez (cbf_set_integerarray_wdims (cbf, CBF_BYTE_OFFSET, 1,
                               image, sizeof (int), 0,
                               1000000,"little_endian",1000,1000,0,4095))


  free(image);

  cbf_failnez(cbf_new_row(cbf))


  /*  Create an array 1000 x 1000 shorts as a flat field */

  cbf_failnez( (shimage = (short *)malloc(sizeof(short)*1000000))==NULL?CBF_ALLOC:0);

  for (i = 0; i < 1000000; i++) {
  	shimage[i] = 1000;
  }


  cbf_failnez (cbf_set_integerarray_wdims (cbf, CBF_BYTE_OFFSET, 2,
                               shimage, sizeof (short), 0,
                               1000000, "little_endian",1000,1000,0,4095))


  free(shimage);

  cbf_failnez(cbf_new_row(cbf))


 /*  Create an  array 1000 x 1000 signed ints in a flat field of 1000, except for
     -3 along the main diagonal and its transpose */

  cbf_failnez (	(image = (int *)malloc(sizeof(int)*1000000))==NULL?CBF_ALLOC:0);

  for (i = 0; i < 1000; i++) {

    for (j = 0; j < 1000; j++) {

  	  image[i+j*1000] = 1000;

  	  if (i == j || i == 999-j) image[i+j*1000] = -3;

    }

  }


  cbf_failnez (cbf_set_integerarray_wdims (cbf, CBF_BYTE_OFFSET, 3,
                               image, sizeof (int), 1,
                               1000000,"little_endian",1000,1000,0,4095))


  free(image);

  cbf_failnez(cbf_new_row(cbf))


  /*  Create an array 1000 x 1000 shorts in a flat field of 1000, except for
     -3 along the main diagonal and its transpose */

  cbf_failnez( (shimage = (short *)malloc(sizeof(short)*1000000))==NULL?CBF_ALLOC:0);


  for (i = 0; i < 1000; i++) {

    for (j = 0; j < 1000; j++) {

  	  shimage[i+j*1000] = 1000;

  	  if (i == j || i == 999-j) shimage[i+j*1000] = -3;

    }

  }


  cbf_failnez (cbf_set_integerarray_wdims (cbf, CBF_BYTE_OFFSET, 4,
                               shimage, sizeof (short), 1,
                               1000000, "little_endian",1000,1000,0,4095))


  free(shimage);

  cbf_failnez(cbf_new_row(cbf))


 /*  Create an  array 50 x 60 x 70 signed ints in a flat field of 1000, except for
     -3 along the main diagonal and the values i+j+k every 1000th pixel */

  cbf_failnez (	(image = (int *)malloc(sizeof(int)*50*60*70))==NULL?CBF_ALLOC:0);

  for (i = 0; i < 50; i++) {

    for (j = 0; j < 60; j++) {

      for (k = 0; k < 70; k++) {

  	    image[i + j*50 + k*50*60] = 1000;

  	    if (i == j || j == k ) image[i + j*50 + k*50*60] = -3;

  	    if ((i + j*50 + k*50*60)%1000 == 0) image[i + j*50 + k*50*60] = i+j+k;

      }

    }

  }


  cbf_failnez (cbf_set_integerarray_wdims (cbf, CBF_BYTE_OFFSET, 3,
                               image, sizeof (int), 1,
                               50*60*70,"little_endian",50,60,70,4095))


  free(image);


    /* Write the new file */

  out = fopen ("testflatout.cbf", "w+b");

  if (!out)
  {
    fprintf (stderr, " testflat:  Couldn't open the CBF file %s\n", "testflatout.cbf");

    exit (1);
  }

  cbf_failnez (cbf_write_file (cbf, out, 1, CBF,
                               MSG_DIGEST | MIME_HEADERS, 0))


    /* Free the cbf */

  if (cbf) {
        cbf_failnez (cbf_free_handle (cbf));
  }
  if (incbf) {
        cbf_failnez (cbf_free_handle (incbf));
  }


    /* Success */

  return 0;
}

int local_exit (int status)
{
  exit(status);
  return 1; /* avoid warnings */
}

