/*	Copyright (C) 1990 Free Software Foundation, Inc.

This file is part of Oleo, the GNU Spreadsheet.

Oleo 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 1, or (at your option)
any later version.

Oleo 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 Oleo; see the file COPYING.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

#undef NULL
#include <stdio.h>
#include "funcdef.h"
#include "sysdef.h"

#include "global.h"

extern char **environ;

extern int dup EXT1(int);
extern int close EXT1(int);
extern void *sbrk EXT1(size_t);
extern void *brk EXT1(void *);

void
panic_write_file FUN2(FILE *,fp, struct rng *,rng)
{
#ifndef AMIGA
	int fd;
	void *datend;
	void *datstart;
	unsigned long cnt;

	if(rng) {
		error_msg("Can't write partial panic-save files");
		return;
	}
	fd=dup(fileno(fp));
	if(fd<0) {
		error_msg("Couldn't dup save file");
		return;
	}
	datstart= (void *)(&environ+sizeof(char **));
	datend=sbrk(0);
	if(datend==(char *)-1) {
		error_msg("Couldn't sbrk(0)!");
		close(fd);
		return;
	}

	cnt=(char *)datend-(char *)datstart;
	if(write(fd,&cnt,sizeof(cnt))!=sizeof(cnt)) {
		error_msg("Couldn't write %lu (%d bytes) to save file",cnt,sizeof(cnt));
		close(fd);
		return;
	}
	if(write(fd,datstart,cnt)!=cnt) {
		error_msg("Couldn't write %lu bytes to save file",cnt);
		close(fd);
		return;
	}
	if(close(fd)<0) {
		error_msg("Couldn't close save file");
		return;
	}
#endif
}

void
panic_read_file FUN2(FILE *,fp, int, ismerge)
{
#ifndef AMIGA
	int fd;
	unsigned long cnt;
	void *datstart;

	if(ismerge) {
		error_msg("Can't merge panic-save files");
		return;
	}
	if((fd=dup(fileno(fp)))<0) {
		error_msg("Couldn't dup save file");
		return;
	}
	if(read(fd,(void *)&cnt,sizeof(cnt))!=sizeof(cnt)) {
		error_msg("Couldn't read data_size (%d bytes) from save file",sizeof(cnt));
		close(fd);
		return;
	}
	datstart= (void *)(&environ+sizeof(char **));
	if(brk((char *)datstart+cnt)==(void *)-1) {
		error_msg("Couldn't allocate %lu bytes of memory",cnt);
		close(fd);
		return;
	}
	if(read(fd,datstart,cnt)!=cnt) {
		error_msg("Couldn't read in %lu bytes of data",cnt);
		close(fd);
		return;
	}
	if(close(fd)<0)
		error_msg("Couldn't close save file");
	recenter_all_win();
#endif
}

int
panic_set_options FUN2(int,set_opt, char *,option)
{
	return -1;
}


void
panic_show_options FUN0()
{
	text_line("File format:  panic save   (quick-n-dirty data-segment dump)");
}
