/*****************************************************************************

				ESPS_WRITE.C
				When the ESPS Waves audio display and processing
				software is loaded, this writes ESPS (*.sd) format data files.
				The ESPS software is currently (2002) owned by Microsoft,
				after they bought Entropics.

Copyright (C) 2002 Greg Kochanski, gpk@pribble.com .

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., 675 Mass Ave, Cambridge, MA 02139, USA.

*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "gpk_std.h"
#include "gpklib.h"
#include "gpklib/ieee754.h"
#include "gpklib/image.h"
#include "rw_misc.h"
#include "gpklib/assert.h"
#include "rbfile.h"
#include "internals.h"




BOOL ESPS_writefile(C struct image *p, FILE *out, C proplist& control)
{
 assert(p);
 assert(out);
 assert(p->prop);
 proplist q(*p->prop);
 normalize_proplist(&q, p);
 q += control;
 int bitpix = q.geti("BITPIX", 0);
 if(bitpix >= 0)
	bitpix = 16;
 else	bitpix = -32;

 double bscale, bzero;
 scale_image_for_bitpix(p, bitpix, &bscale, &bzero, 0, 0, &q, FALSE);

 char execstring[1024];
 sprintf(execstring, "btosps -f %g -T %g -n %d -c no_comment -t %s - %s",
		1.0/p->yscale,
		p->ycenter - p->yscale*(p->nlines-1)*0.5,
		p->npts, bitpix==16 ? "SHORT" : "FLOAT",
		q.gets("_NAME", "no_name.sd"));
 FILE *oo = popen(execstring, "w");
 if(!oo) {
	perror("ERR: popen fails");
	fprintf(stderr, "ERR: can't open pipe to {%s}\n", execstring);
	return FALSE;
	}

 write_out_data(oo, p, bitpix, LOCAL_ORDER, bscale, bzero);
 /* We write in local byte ordering into the pipe,
 but then the ESPS program translates into whatever order it wants. */

 if(pclose(oo) != 0) {	/* Exit status of btosps. */
	perror("ERR: btosps fails or doesn't exist.");
	fprintf(stderr, "ERR: pipe fails to {%s}\n", execstring);
	return FALSE;
 }
 return TRUE;
}
