/* libmondo-archive.c
   $Id: libmondo-archive.c 3192 2013-09-25 07:03:25Z bruno $

subroutines to handle the archiving of files
*/

/**
 * @file
 * Functions to handle backing up data.
 * This is the main file (at least the longest one) in libmondo.
 */

#include "my-stuff.h"
#include "mr_mem.h"
#include "mr_str.h"
#include "mondostructures.h"
#include "libmondo-string-EXT.h"
#include "libmondo-stream-EXT.h"
#include "libmondo-devices-EXT.h"
#include "libmondo-tools-EXT.h"
#include "libmondo-gui-EXT.h"
#include "libmondo-fork-EXT.h"
#include "libmondo-files-EXT.h"
#include "libmondo-filelist-EXT.h"
#include "libmondo-tools-EXT.h"
#include "libmondo-verify-EXT.h"
#include "libmondo-archive.h"
#include "lib-common-externs.h"
#include <sys/sem.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdarg.h>
#define DVDRWFORMAT 1



#ifndef _SEMUN_H
#define _SEMUN_H

	/**
	 * The semaphore union, provided only in case the user's system doesn't.
	 */
union semun {
	int val;
	struct semid_ds *buf;
	unsigned short int *array;
	struct seminfo *__buf;
};
#endif

/*@unused@*/
//static char cvsid[] = "$Id: libmondo-archive.c 3192 2013-09-25 07:03:25Z bruno $";
//
extern char *get_non_rewind_dev(char *);

/* *************************** external global vars ******************/
extern int g_current_media_number;
extern int g_currentY;
extern bool g_text_mode;
extern bool g_exiting;
extern long g_current_progress;
extern FILE *g_tape_stream;
extern long long g_tape_posK;
extern bool g_cd_recovery;
extern char *g_mondo_home;
/*
extern char *g_tmpfs_mountpt;
*/
extern char *g_serial_string;
extern char *g_getfacl;
extern char *g_getfattr;
extern char *MONDO_LOGFILE;

/* Reference to global bkpinfo */
extern struct s_bkpinfo *bkpinfo;


/**
 * @addtogroup globalGroup
 * @{
 */
/**
 * The current backup media type in use.
 */
t_bkptype g_backup_media_type = none;

/**
 * Incremented by each archival thread when it starts up. After that,
 * this is the number of threads running.
 */
int g_current_thread_no = 0;

/* @} - end of globalGroup */

extern int g_noof_rows;

/* Semaphore-related code */

static int set_semvalue(void);
static void del_semvalue(void);
static int semaphore_p(void);
static int semaphore_v(void);

static int g_sem_id;
static int g_sem_key;

/**
 * Initialize the semaphore.
 * @see del_semvalue
 * @see semaphore_p
 * @see semaphore_v
 * @return 1 for success, 0 for failure.
 */
static int set_semvalue(void)	// initializes semaphore
{
	union semun sem_union;
	sem_union.val = 1;
	if (semctl(g_sem_id, 0, SETVAL, sem_union) == -1) {
		return (0);
	}
	return (1);
}

/**
 * Frees (deletes) the semaphore. Failure is indicated by a log
 * message.
 * @see set_semvalue
 */
static void del_semvalue(void)	// deletes semaphore
{
	union semun sem_union;

	if (semctl(g_sem_id, 0, IPC_RMID, sem_union) == -1) {
		log_msg(3, "Failed to delete semaphore");
	}
}

/**
 * Acquire (increment) the semaphore (change status to P).
 * @return 1 for success, 0 for failure.
 * @see semaphore_v
 */
static int semaphore_p(void)	// changes status to 'P' (waiting)
{
	struct sembuf sem_b;

	sem_b.sem_num = 0;
	sem_b.sem_op = -1;			// P()
	sem_b.sem_flg = SEM_UNDO;
	if (semop(g_sem_id, &sem_b, 1) == -1) {
		log_msg(3, "semaphore_p failed");
		return (0);
	}
	return (1);
}

/**
 * Free (decrement) the semaphore (change status to V).
 * @return 1 for success, 0 for failure.
 */
static int semaphore_v(void)	// changes status to 'V' (free)
{
	struct sembuf sem_b;

	sem_b.sem_num = 0;
	sem_b.sem_op = 1;			// V()
	sem_b.sem_flg = SEM_UNDO;
	if (semop(g_sem_id, &sem_b, 1) == -1) {
		log_msg(3, "semaphore_v failed");
		return (0);
	}
	return (1);
}


//------------------------------------------------------


/**
 * Size in megabytes of the buffer afforded to the executable "buffer".
 * This figure is used when we calculate how much data we have probably 'lost'
 * when writing off the end of tape N, so that we can then figure out how much
 * data we must recreate & write to the start of tape N+1.
 */
extern int g_tape_buffer_size_MB;




int
archive_this_fileset_with_star(char *filelist, char *fname, int setno)
{
	int retval = 0;
	unsigned int res = 0;
	int tries = 0;
	char *command = NULL;
	char *tmp = NULL;
	char *p;


	if (!does_file_exist(filelist)) {
		mr_asprintf(tmp, "(archive_this_fileset) - filelist %s does not exist", filelist);
		log_to_screen(tmp);
		paranoid_free(tmp);
		return (1);
	}

	mr_asprintf(tmp, "echo hi > %s 2> /dev/null", fname);
	if (system(tmp)) {
		paranoid_free(tmp);
		fatal_error("Unable to write tarball to scratchdir");
	}
	paranoid_free(tmp);

	mr_asprintf(command, "star H=exustar list=%s -c -sparse " STAR_ACL_SZ " file=%s",
			filelist, fname);
	if (bkpinfo->use_lzo) {
		fatal_error("Can't use lzop");
	}
	if (bkpinfo->compression_level > 0) {
		mr_strcat(command, " -bz");
	}
	mr_strcat(command, " 2>> %s", MONDO_LOGFILE);
	log_msg(4, "command = '%s'", command);

	for (res = 99, tries = 0; tries < 3 && res != 0; tries++) {
		log_msg(5, "command='%s'", command);
		res = system(command);
		mr_asprintf(tmp, "%s", last_line_of_file(MONDO_LOGFILE));
		log_msg(1, "res=%d; tmp='%s'", res, tmp);
		if (bkpinfo->use_star && (res == 254 || res == 65024)
			&& strstr(tmp, "star: Processed all possible files")
			&& tries > 0) {
			log_msg(1, "Star returned nonfatal error");
			res = 0;
		}
		paranoid_free(tmp);

		if (res) {
			log_OS_error(command);
			p = strstr(command, "-acl ");
			if (p) {
				p[0] = p[1] = p[2] = p[3] = ' ';
				log_msg(1, "new command = '%s'", command);
			} else {
				log_msg(3,
						"Attempt #%d failed. Pausing 3 seconds and retrying...",
						tries + 1);
				sleep(3);
			}
		}
	}
	paranoid_free(command);

	retval += res;
	if (retval) {
		log_msg(3, "Failed to write set %d", setno);
	} else if (tries > 1) {
		log_msg(3, "Succeeded in writing set %d, on try #%d", setno,
				tries);
	}
	return (retval);
}


/**
 * Call @c afio to archive the filelist @c filelist to the file @c fname.
 * 
 * @param bkpinfo The backup information structure. Fields used:
 * - @c compression_level
 * - @c scratchdir (only verifies existence)
 * - @c tmpdir (only verifies existence)
 * - @c zip_exe
 * - @c zip_suffix
 * @param filelist The path to a file containing a list of files to be archived
 * in this fileset.
 * @param fname The output file to archive to.
 * @param setno This fileset number.
 * @return The number of errors encountered (0 for success).
 * @ingroup LLarchiveGroup
 */
int
archive_this_fileset(char *filelist, char *fname, int setno)
{

	/*@ int *************************************************************** */
	int retval = 0;
	int res = 0;
	int tries = 0;
	/*
	int i = 0;
	static int free_ramdisk_space = 9999;
	*/

	/*@ buffers ************************************************************ */
	char *command = NULL;
	char *zipparams = NULL;
	char *tmp = NULL;

	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(filelist);
	assert_string_is_neither_NULL_nor_zerolength(fname);

	if (bkpinfo->compression_level > 0 && bkpinfo->use_star) {
		return (archive_this_fileset_with_star(filelist, fname, setno));
	}

	if (!does_file_exist(filelist)) {
		mr_asprintf(tmp, "(archive_this_fileset) - filelist %s does not exist",
				filelist);
		log_to_screen(tmp);
		paranoid_free(tmp);
		return (1);
	}
	mr_asprintf(tmp, "echo hi > %s 2> /dev/null", fname);
	if (system(tmp)) {
		paranoid_free(tmp);
		fatal_error("Unable to write tarball to scratchdir");
	}
	paranoid_free(tmp);


	if (bkpinfo->compression_level > 0) {
		mr_asprintf(tmp, "%s/do-not-compress-these", g_mondo_home);
		//       -b %ld, TAPE_BLOCK_SIZE
		mr_asprintf(zipparams, "-Z -P %s -G %d -T 3k", bkpinfo->zip_exe,
				bkpinfo->compression_level);
		if (does_file_exist(tmp)) {
			mr_strcat(zipparams, " -E %s",tmp);
		} else {
			log_msg(3, "%s not found. Cannot exclude zipfiles, etc.", tmp);
		}
		paranoid_free(tmp);
	} else {
		mr_asprintf(zipparams, "");
	}

//  make_hole_for_file(fname);

	if (!does_file_exist(bkpinfo->tmpdir)) {
		log_OS_error("tmpdir not found");
		fatal_error("tmpdir not found");
	}
	if (!does_file_exist(bkpinfo->scratchdir)) {
		log_OS_error("scratchdir not found");
		fatal_error("scratchdir not found");
	}
	mr_asprintf(command, "rm -f %s %s. %s.gz %s.%s", fname, fname, fname,
			fname, bkpinfo->zip_suffix);
	paranoid_system(command);
	paranoid_free(command);

	mr_asprintf(command, "afio -o -b %ld -M 16m %s %s < %s 2>> %s",
			TAPE_BLOCK_SIZE, zipparams, fname, filelist, MONDO_LOGFILE);
	paranoid_free(zipparams);

	mr_asprintf(tmp, "echo hi > %s 2> /dev/null", fname);
	if (system(tmp)) {
		paranoid_free(tmp);
		fatal_error("Unable to write tarball to scratchdir");
	}
	paranoid_free(tmp);

	for (res = 99, tries = 0; tries < 3 && res != 0; tries++) {
		log_msg(5, "command='%s'", command);
		res = system(command);
		if (res) {
			log_OS_error(command);
			log_msg(3,
					"Attempt #%d failed. Pausing 3 seconds and retrying...",
					tries + 1);
			sleep(3);
		}
	}
	paranoid_free(command);

	retval += res;
	if (retval) {
		log_msg(3, "Failed to write set %d", setno);
	} else if (tries > 1) {
		log_msg(3, "Succeeded in writing set %d, on try #%d", setno,
				tries);
	}

	return (retval);
}






/**
 * Wrapper function for all the backup commands.
 * Calls these other functions: @c prepare_filelist(),
 * @c call_filelist_chopper(), @c copy_mondo_and_mindi_stuff_to_scratchdir(),
 * @c call_mindi_to_supply_boot_disks(), @c do_that_initial_phase(),
 * @c make_those_afios_phase(), @c make_those_slices_phase(), and
 * @c do_that_final_phase(). If anything fails before @c do_that_initial_phase(),
 * @c fatal_error is called with a suitable message.
 * @param bkpinfo The backup information structure. Uses most fields.
 * @return The number of non-fatal errors encountered (0 for success).
 * @ingroup archiveGroup
 */
int backup_data()
{
	int retval = 0, res = 0;
	char *tmp;

	assert(bkpinfo != NULL);
	set_g_cdrom_and_g_dvd_to_bkpinfo_value();
	malloc_string(tmp);
	if (bkpinfo->backup_media_type == dvd) {
#ifdef DVDRWFORMAT
		if (!find_home_of_exe("dvd+rw-format")) {
			fatal_error
				("Cannot find dvd+rw-format. Please install it or fix your PATH.");
		}
#endif
		if (!find_home_of_exe("growisofs")) {
			fatal_error
				("Cannot find growisofs. Please install it or fix your PATH.");
		}
	}

	if ((res = prepare_filelist())) {	/* generate scratchdir/filelist.full */
		fatal_error("Failed to generate filelist catalog");
	}
	if (call_filelist_chopper()) {
		fatal_error("Failed to run filelist chopper");
	}

/*
      sprintf(tmp, "wc -l %s/archives/filelist.full > %s/archives/filelist.count",bkpinfo->scratchdir, bkpinfo->scratchdir);
      if (run_program_and_log_output(tmp, 2))
        { fatal_error("Failed to count filelist.full"); }
*/
	sprintf(tmp, "gzip -9 %s/archives/filelist.full", bkpinfo->scratchdir);
	if (run_program_and_log_output(tmp, 2)) {
		fatal_error("Failed to gzip filelist.full");
	}
	sprintf(tmp, "cp -f %s/archives/*list*.gz %s", bkpinfo->scratchdir,
			bkpinfo->tmpdir);
	if (run_program_and_log_output(tmp, 2)) {
		fatal_error("Failed to copy to tmpdir");
	}

	copy_mondo_and_mindi_stuff_to_scratchdir();	// payload, too, if it exists
#if __FreeBSD__ == 5
	strcpy(bkpinfo->kernel_path, "/boot/kernel/kernel");
#elif __FreeBSD__ == 4
	strcpy(bkpinfo->kernel_path, "/kernel");
#elif linux
	if (figure_out_kernel_path_interactively_if_necessary
		(bkpinfo->kernel_path)) {
		fatal_error
			("Kernel not found. Please specify manually with the '-k' switch.");
	}
#else
#error "I don't know about this system!"
#endif
	if ((res = call_mindi_to_supply_boot_disks())) {
		fatal_error("Failed to generate boot+data disks");
	}
	retval += do_that_initial_phase();	// prepare
	sprintf(tmp, "rm -f %s/images/*.iso", bkpinfo->scratchdir);
	run_program_and_log_output(tmp, 1);
	retval += make_those_afios_phase();	// backup regular files
	retval += make_those_slices_phase();	// backup BIG files
	retval += do_that_final_phase();	// clean up
	log_msg(1, "Creation of archives... complete.");
	if (bkpinfo->verify_data) {
		sleep(2);
	}
	paranoid_free(tmp);
	return (retval);
}




/**
 * Call Mindi to generate boot and data disks.
 * @note This binds correctly to the new Perl version of mindi.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c boot_loader
 * - @c boot_device
 * - @c compression_level
 * - @c differential
 * - @c image_devs
 * - @c kernel_path
 * - @c make_cd_use_lilo
 * - @c media_device
 * - @c media_size
 * - @c nonbootable_backup
 * - @c scratchdir
 * - @c tmpdir
 * - @c use_lzo
 *
 * @return The number of errors encountered (0 for success)
 * @bug The code to automagically determine the boot drive
 * is messy and system-dependent. In particular, it breaks
 * for Linux RAID and LVM users.
 * @ingroup MLarchiveGroup
 */
int call_mindi_to_supply_boot_disks()
{
	/*@ buffer ************************************************************ */
	char *tmp = NULL;
	char *tmp1 = NULL;
	char *tmp2 = NULL;
	char *command = NULL;
	char *use_lzo_sz = NULL;
	char *use_gzip_sz = NULL;
	char *use_comp_sz = NULL;
	char *use_star_sz = NULL;
	char *bootldr_str = NULL;
	char *bootldr_ver = NULL;
	char *tape_device = NULL;
	char *last_filelist_number = NULL;
	char *broken_bios_sz = NULL;
	char *cd_recovery_sz = NULL;
	char *tape_size_sz = NULL;
	char *use_lilo_sz = NULL;	/* BCO: shared between LILO/ELILO */
	char *value = NULL;
	char *bootdev = NULL;
	char *ntapedev = NULL;



	/*@ char ************************************************************** */
	char ch = '\0';

	/*@ long     ********************************************************** */
	long lines_in_filelist = 0;

	/*@ int     ************************************************************* */
	int res = 0;
	long estimated_total_noof_slices = 0;

	assert(bkpinfo != NULL);

	mvaddstr_and_log_it(g_currentY, 0,
						"Calling MINDI to create boot+data disks");
	open_evalcall_form("Calling MINDI to create boot+data disks");
	mr_asprintf(tmp, "%s/filelist.full", bkpinfo->tmpdir);
	if (!does_file_exist(tmp)) {
		mr_free(tmp);
		mr_asprintf(tmp, "%s/tmpfs/filelist.full", bkpinfo->tmpdir);
		if (!does_file_exist(tmp)) {
			fatal_error
				("Cannot find filelist.full, so I cannot count its lines");
		}
	}
	lines_in_filelist = count_lines_in_file(tmp);
	mr_free(tmp);

	mr_asprintf(tmp, "%s/LAST-FILELIST-NUMBER", bkpinfo->tmpdir);
	mr_asprintf(last_filelist_number, "%s", last_line_of_file(tmp));
	mr_free(tmp);

	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		mr_asprintf(tape_size_sz, "%ld", bkpinfo->media_size);
		ntapedev = get_non_rewind_dev(bkpinfo->media_device);
		if ((bkpinfo->use_obdr) && (ntapedev != NULL)) {
			strncpy(bkpinfo->media_device,ntapedev,(size_t)(MAX_STR_LEN / 4));
		} else {
			if (ntapedev == NULL) {
				log_it("Not able to create OBDR - Restore will have to be done manually");
			}
		}
		paranoid_free(ntapedev);
		mr_asprintf(tape_device, "%s", bkpinfo->media_device);
	} else {
		mr_asprintf(tape_size_sz, "%ld", 0L);;
		mr_asprintf(tape_device, "");
	}
	if (bkpinfo->use_lzo) {
		mr_asprintf(use_lzo_sz, "yes");
	} else {
		mr_asprintf(use_lzo_sz, "no");
	}
	if (bkpinfo->use_gzip) {
		mr_asprintf(use_gzip_sz, "yes");
	} else {
		mr_asprintf(use_gzip_sz, "no");
	}
	if (bkpinfo->use_star) {
		mr_asprintf(use_star_sz, "yes");
	} else {
		mr_asprintf(use_star_sz, "no");
	}

	if (bkpinfo->compression_level > 0) {
		mr_asprintf(use_comp_sz, "yes");
	} else {
		mr_asprintf(use_comp_sz, "no");
	}

	mr_asprintf(broken_bios_sz, "yes");	/* assume so */
	if (g_cd_recovery) {
		mr_asprintf(cd_recovery_sz, "yes");
	} else {
		mr_asprintf(cd_recovery_sz, "no");
	}
	if (bkpinfo->make_cd_use_lilo) {
		mr_asprintf(use_lilo_sz, "yes");
	} else {
		mr_asprintf(use_lilo_sz, "no");
	}

	update_evalcall_form(2);
	if (!bkpinfo->nonbootable_backup
		&& (bkpinfo->boot_loader == '\0'
			|| bkpinfo->boot_device[0] == '\0')) {

#ifdef __FreeBSD__
		mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
			   ("mount | grep ' /boot ' | head -1 | cut -d' ' -f1 | sed 's/\\([0-9]\\).*/\\1/'"));
		if (!bootdev[0]) {
			mr_free(bootdev);
			mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
				   ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | sed 's/\\([0-9]\\).*/\\1/'"));
		}
#else
		/* Linux */
#ifdef __IA64__
		mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
			   ("mount | grep ' /boot/efi ' | head -1 | cut -d' ' -f1 | sed 's/[0-9].*//'"));
#else
		mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
			   ("mount | grep ' /boot ' | head -1 | cut -d' ' -f1 | sed 's/[0-9].*//'"));
#endif
		if (strstr(bootdev, "/dev/cciss/")) {
			mr_free(bootdev);
#ifdef __IA64__
			mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
				   ("mount | grep ' /boot/efi ' | head -1 | cut -d' ' -f1 | cut -dp -f1"));
#else
			mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
				   ("mount | grep ' /boot ' | head -1 | cut -d' ' -f1 | cut -dp -f1"));
#endif
		}
		if (!bootdev[0]) {
			mr_free(bootdev);
			mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
				   ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | sed 's/[0-9].*//'"));
			if (strstr(bootdev, "/dev/cciss/")) {
				mr_free(bootdev);
				mr_asprintf(bootdev, "%s", call_program_and_get_last_line_of_output
					   ("mount | grep ' / ' | head -1 | cut -d' ' -f1 | cut -dp -f1"));
			}
		}
		/* Linux */
#endif
		if (bootdev[0])
			ch = which_boot_loader(bootdev);
		else
			ch = 'U';
		if (bkpinfo->boot_loader != '\0') {
			mr_asprintf(tmp, "User specified boot loader. It is '%c'.", bkpinfo->boot_loader);
			log_msg(2, tmp);
			mr_free(tmp);
		} else {
			bkpinfo->boot_loader = ch;
		}
		if (bkpinfo->boot_device[0] != '\0') {
			mr_asprintf(tmp, "User specified boot device. It is '%s'.", bkpinfo->boot_device);
			log_msg(2, tmp);
			mr_free(tmp);
		} else {
			strcpy(bkpinfo->boot_device, bootdev);
		}
	}
	mr_free(bootdev);

	if (
#ifdef __FreeBSD__
		   bkpinfo->boot_loader != 'B' && bkpinfo->boot_loader != 'D' &&
#endif
#ifdef __IA64__
		   bkpinfo->boot_loader != 'E' &&
#endif
		   bkpinfo->boot_loader != 'L' && bkpinfo->boot_loader != 'G'
		   && bkpinfo->boot_loader != 'R'
		   && !bkpinfo->nonbootable_backup) {
		fatal_error
			("Please specify your boot loader and device, e.g. -l GRUB -f /dev/hda. Type 'man mondoarchive' to read the manual.");
	}
	if (bkpinfo->boot_loader == 'L') {
		mr_asprintf(bootldr_str, "LILO");
		if (!does_file_exist("/etc/lilo.conf")) {
			fatal_error
				("The de facto standard location for your boot loader's config file is /etc/lilo.conf but I cannot find it there. What is wrong with your Linux distribution?");
		}
	} else if (bkpinfo->boot_loader == 'G') {
		mr_asprintf(bootldr_str, "GRUB");
		if (!does_file_exist("/boot/grub/menu.lst")
			&& does_file_exist("/boot/grub/grub.conf")) {
			run_program_and_log_output
				("ln -sf /boot/grub/grub.conf /boot/grub/menu.lst", 5);
		}
		if ((!does_file_exist("/boot/grub/menu.lst")) && (!does_file_exist("/boot/grub/grub.cfg")) && (!does_file_exist("/boot/grub2/grub.cfg"))) {
			fatal_error
				("The de facto standard location for your boot loader's config file is /boot/grub/menu.lst, /boot/grub/grub.cfg, or /boot/grub2/grub.cfg but I cannot find it there. What is wrong with your Linux distribution?");
		}
		mr_asprintf(bootldr_ver, "%s", call_program_and_get_last_line_of_output("grub --version"));
	} else if (bkpinfo->boot_loader == 'E') {
		mr_asprintf(bootldr_str, "ELILO");
		/* BCO: fix it for Debian, Mandrake, ... */
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/efi/redhat/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/efi/redhat/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/efi/SuSE/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/efi/SuSE/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/efi/debian/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/efi/debian/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")
			&& does_file_exist("/boot/efi/debian/elilo.conf")) {
			run_program_and_log_output
				("ln -sf /boot/efi/debian/elilo.conf /etc/elilo.conf",
				 5);
		}
		if (!does_file_exist("/etc/elilo.conf")) {
			fatal_error
				("The de facto mondo standard location for your boot loader's config file is /etc/elilo.conf but I cannot find it there. What is wrong with your Linux distribution? Try finding it under /boot/efi and do 'ln -s /boot/efi/..../elilo.conf /etc/elilo.conf'");
		}
	} else if (bkpinfo->boot_loader == 'R') {
		mr_asprintf(bootldr_str, "RAW");
	}
#ifdef __FreeBSD__
	else if (bkpinfo->boot_loader == 'D') {
		mr_asprintf(bootldr_str, "DD");
	}

	else if (bkpinfo->boot_loader == 'B') {
		mr_asprintf(bootldr_str, "BOOT0");
	}
#endif
	else {
		mr_asprintf(bootldr_str, "unknown");
	}
	mr_asprintf(tmp, "Your boot loader is %s and it boots from %s", bootldr_str, bkpinfo->boot_device);
	log_to_screen(tmp);
	mr_free(tmp);
	if (bootldr_ver != NULL) {
		mr_asprintf(tmp, "Boot loader version string: %s", bootldr_ver);
		log_to_screen(tmp);
		mr_free(tmp);
	}

	mr_asprintf(tmp, "%s/BOOTLOADER.DEVICE", bkpinfo->tmpdir);
	if (write_one_liner_data_file(tmp, bkpinfo->boot_device)) {
		log_msg(1, "%ld: Unable to write one-liner boot device", __LINE__);
	}
	mr_free(tmp);

	switch (bkpinfo->backup_media_type) {
	case cdr:
		mr_asprintf(value, "cdr");
		break;
	case cdrw:
		mr_asprintf(value, "cdrw");
		break;
	case cdstream:
		mr_asprintf(value, "cdstream");
		break;
	case tape:
		mr_asprintf(value, "tape");
		break;
	case udev:
		mr_asprintf(value, "udev");
		break;
	case iso:
		mr_asprintf(value, "iso");
		break;
	case netfs:
		mr_asprintf(value, "netfs");
		break;
	case dvd:
		mr_asprintf(value, "dvd");
		break;
	case usb:
		mr_asprintf(value, "usb");
		break;
	default:
		fatal_error("Unknown backup_media_type");
	}
	if (bkpinfo->backup_media_type == usb) {
		mr_asprintf(tmp2, "--usb %s", bkpinfo->media_device);
	} else {
		mr_asprintf(tmp2," ");
	}

	mr_asprintf(tmp, "%s/BACKUP-MEDIA-TYPE", bkpinfo->tmpdir);
	if (write_one_liner_data_file(tmp, value)) {
		res++;
		log_msg(1, "%ld: Unable to write one-liner backup-media-type",
				__LINE__);
	}
	mr_free(value);
	mr_free(tmp);

	mr_asprintf(tmp, "%s/BOOTLOADER.NAME", bkpinfo->tmpdir);
	if (write_one_liner_data_file(tmp, bootldr_str)) {
		res++;
		log_msg(1, "%ld: Unable to write one-liner bootloader.name",
				__LINE__);
	}
	mr_free(bootldr_str);
	mr_free(tmp);

	mr_asprintf(tmp, "%s/BOOTLOADER.VER", bkpinfo->tmpdir);
	if (write_one_liner_data_file(tmp, bootldr_ver)) {
		res++;
		log_msg(1, "%ld: Unable to write one-liner bootloader.ver",
				__LINE__);
	}
	mr_free(bootldr_ver);
	mr_free(tmp);

	mr_asprintf(tmp, "%s/DIFFERENTIAL", bkpinfo->tmpdir);
	if (bkpinfo->differential) {
		res += write_one_liner_data_file(tmp, "1");
	} else {
		res += write_one_liner_data_file(tmp, "0");
	}
	mr_free(tmp);

	if (g_getfattr) {
		mr_asprintf(tmp1, "%s/XATTR", bkpinfo->tmpdir);
		if (write_one_liner_data_file(tmp1, "TRUE")) {
			log_msg(1, "%ld: Unable to write one-liner XATTR",
				__LINE__);
		}
		paranoid_free(tmp1);
	}
	if (g_getfacl) {
		mr_asprintf(tmp1, "%s/ACL", bkpinfo->tmpdir);
		if (write_one_liner_data_file(tmp1, "TRUE")) {
			log_msg(1, "%ld: Unable to write one-liner ACL",
				__LINE__);
		}
		paranoid_free(tmp1);
	}
	if (bkpinfo->use_obdr) {
		mr_asprintf(tmp1, "%s/OBDR", bkpinfo->tmpdir);
		if (write_one_liner_data_file(tmp1, "TRUE")) {
			log_msg(1, "%ld: Unable to write one-liner OBDR",
				__LINE__);
		}
		paranoid_free(tmp1);
	}

	estimated_total_noof_slices =
		size_of_all_biggiefiles_K(bkpinfo) / bkpinfo->optimal_set_size + 1;
	/* add netfs stuff here? */
	mr_asprintf(command, "mkdir -p %s/images", bkpinfo->scratchdir);
	if (system(command)) {
		res++;
		log_OS_error("Unable to make images directory");
	}
	paranoid_free(command);
	log_msg(1, "lines_in_filelist = %ld", lines_in_filelist);
	update_evalcall_form(3);

/*	   "mindi --custom 2=%s 3=%s/images 4=\"%s\" 5=\"%s\" \
6=\"%s\" 7=%ld 8=\"%s\" 9=\"%s\" 10=\"%s\" \
11=\"%s\" 12=%s 13=%ld 14=\"%s\" 15=\"%s\" 16=\"%s\" 17=\"%s\" 18=%ld 19=%d",*/
	mr_asprintf(command, "mindi %s --custom %s %s/images '%s' '%s' \
'%s' %ld '%s' '%s' '%s' \
'%s' %s %ld '%s' '%s' '%s' '%s' %ld %d '%s'", tmp2, bkpinfo->tmpdir,	// parameter #2
			bkpinfo->scratchdir,	// parameter #3
			bkpinfo->kernel_path,	// parameter #4
			tape_device,		// parameter #5
			tape_size_sz,		// parameter #6
			lines_in_filelist,	// parameter #7 (INT)
			use_lzo_sz,			// parameter #8
			cd_recovery_sz,		// parameter #9
			bkpinfo->image_devs,	// parameter #10
			broken_bios_sz,		// parameter #11
			last_filelist_number,	// parameter #12 (STRING)
			estimated_total_noof_slices,	// parameter #13 (INT)
			(bkpinfo->exclude_devs == NULL) ? "\"\"" : bkpinfo->exclude_devs,   // parameter #14
			use_comp_sz,		// parameter #15
			use_lilo_sz,		// parameter #16
			use_star_sz,		// parameter #17
			bkpinfo->internal_tape_block_size,	// parameter #18 (LONG)
			bkpinfo->differential,	// parameter #19 (INT)
			use_gzip_sz);		// parameter #20 (STRING)

	mr_free(last_filelist_number);
	mr_free(tape_device);
	mr_free(use_lzo_sz);
	mr_free(use_gzip_sz);
	mr_free(use_star_sz);
	mr_free(use_comp_sz);
	mr_free(broken_bios_sz);
	mr_free(cd_recovery_sz);
	mr_free(use_lilo_sz);
	mr_free(tape_size_sz);

	if (bkpinfo->nonbootable_backup) {
		mr_strcat(command, " NONBOOTABLE");
	}
	log_msg(2, command);

//  popup_and_OK("Pausing");

	res = run_program_and_log_output(command, FALSE);
	update_evalcall_form(99);
	paranoid_free(command);

	if (bkpinfo->nonbootable_backup) {
		res = 0;
	}							// hack
	if (!res) {
		log_to_screen("Boot+data disks were created OK");
		mr_asprintf(command, "cp -f %s/images/mindi.iso %s/mondorescue.iso",
				bkpinfo->scratchdir, MINDI_CACHE);
		log_msg(2, command);
		run_program_and_log_output(command, FALSE);
		paranoid_free(command);

		if (bkpinfo->nonbootable_backup) {
			mr_asprintf(command, "cp -f %s/all.tar.gz %s/images",
					bkpinfo->tmpdir, bkpinfo->scratchdir);
			if (system(command)) {
				paranoid_free(command);
				fatal_error("Unable to create temporary all tarball");
			}
			paranoid_free(command);
		}
		/* For USB we already have everything on the key */
		if (bkpinfo->backup_media_type == usb) {
			mr_asprintf(command, "rm -rf %s/images", bkpinfo->scratchdir);
			run_program_and_log_output(command, FALSE);
			paranoid_free(command);
		} else {
			mr_asprintf(tmp, "cp -f %s/images/all.tar.gz %s", bkpinfo->scratchdir,
				bkpinfo->tmpdir);
			if (system(tmp)) {
				fatal_error("Cannot find all.tar.gz in tmpdir");
			}
			mr_free(tmp);
		}
		if (res) {
			mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
		} else {
			mvaddstr_and_log_it(g_currentY++, 74, "Done.");
		}
	} else {
		log_to_screen("Mindi failed to create your boot+data disks.");
		mr_asprintf(command, "grep 'Fatal error' /var/log/mindi.log");
		mr_asprintf(tmp, "%s", call_program_and_get_last_line_of_output(command));
		paranoid_free(command);

		if (strlen(tmp) > 1) {
			popup_and_OK(tmp);
		}
		mr_free(tmp);
	}
	close_evalcall_form();
	return (res);
}



/**
 * Maximum number of filesets allowed in this function.
 */
#define MAX_NOOF_SETS_HERE 32767

/**
 * Offset of the bkpinfo pointer (in bytes) from the
 * buffer passed to create_afio_files_in_background.
 */
#define BKPINFO_LOC_OFFSET (16+MAX_NOOF_SETS_HERE/8+16)

/**
 * Main function for each @c afio thread.
 * @param inbuf A transfer block containing:
 * - @c p_last_set_archived: [offset 0] pointer to an @c int
 *   containing the last set archived.
 * - @c p_archival_threads_running: [offset 4] pointer to an @c int
 *   containing the number of archival threads currently running.
 * - @c p_next_set_to_archive: [offset 8] pointer to an @c int containing
 *   the next set that should be archived.
 * - @c p_list_of_fileset_flags: [offset 12] @c char pointer pointing to a
 *   bit array, where each bit corresponds to a filelist (1=needs
 *   to be archived, 0=archived).
 * - @c bkpinfo: [offset BKPINFO_LOC_OFFSET] pointer to backup information
 *   structure. Fields used:
 *   - @c tmpdir
 *   - @c zip_suffix
 *
 * Any of the above may be modified by the caller at any time.
 *
 * @bug Assumes @c int pointers are 4 bytes.
 * @see archive_this_fileset
 * @see make_afioballs_and_images
 * @return NULL, always.
 * @ingroup LLarchiveGroup
 */
void *create_afio_files_in_background(void *inbuf)
{
	long int archiving_set_no;
	char *archiving_filelist_fname;
	char *archiving_afioball_fname;
	char *curr_xattr_list_fname = NULL;
	char *curr_acl_list_fname;

	char *tmp;
	int res = 0, retval = 0;
	int *p_archival_threads_running;
	int *p_last_set_archived;
	int *p_next_set_to_archive;
	char *p_list_of_fileset_flags;
	int this_thread_no = g_current_thread_no++;

	malloc_string(curr_xattr_list_fname);
	malloc_string(curr_acl_list_fname);
	malloc_string(archiving_filelist_fname);
	malloc_string(archiving_afioball_fname);
	malloc_string(tmp);
	p_last_set_archived = (int *) inbuf;
	p_archival_threads_running = (int *) (inbuf + 4);
	p_next_set_to_archive = (int *) (inbuf + 8);
	p_list_of_fileset_flags = (char *) (inbuf + 12);

	sprintf(archiving_filelist_fname, FILELIST_FNAME_RAW_SZ,
			bkpinfo->tmpdir, 0L);
	for (archiving_set_no = 0L; does_file_exist(archiving_filelist_fname);
		 sprintf(archiving_filelist_fname, FILELIST_FNAME_RAW_SZ,
				 bkpinfo->tmpdir, archiving_set_no)) {
		if (g_exiting) {
			fatal_error("Execution run aborted (pthread)");
		}
		if (archiving_set_no >= MAX_NOOF_SETS_HERE) {
			fatal_error
				("Maximum number of filesets exceeded. Adjust MAX_NOOF_SETS_HERE, please.");
		}
		if (!semaphore_p()) {
			log_msg(3, "P sem failed (pid=%d)", (int) getpid());
			fatal_error("Cannot get semaphore P");
		}
		if (archiving_set_no < *p_next_set_to_archive) {
			archiving_set_no = *p_next_set_to_archive;
		}
		*p_next_set_to_archive = *p_next_set_to_archive + 1;
		if (!semaphore_v()) {
			fatal_error("Cannot get semaphore V");
		}

		/* backup this set of files */
		sprintf(archiving_afioball_fname, AFIOBALL_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no, bkpinfo->zip_suffix);
		sprintf(archiving_filelist_fname, FILELIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no);
		if (!does_file_exist(archiving_filelist_fname)) {
			log_msg(3,
					"%s[%d:%d] - well, I would archive %d, except that it doesn't exist. I'll stop now.",
					FORTY_SPACES, getpid(), this_thread_no,
					archiving_set_no);
			break;
		}

		sprintf(tmp, AFIOBALL_FNAME_RAW_SZ, bkpinfo->tmpdir,
				archiving_set_no - ARCH_BUFFER_NUM, bkpinfo->zip_suffix);
		if (does_file_exist(tmp)) {
			log_msg(4, "%s[%d:%d] - waiting for storer", FORTY_SPACES,
					getpid(), this_thread_no);
			while (does_file_exist(tmp)) {
				sleep(1);
			}
			log_msg(4, "[%d] - continuing", getpid());
		}

		log_msg(4, "%s[%d:%d] - EXATing %d...", FORTY_SPACES, getpid(),
				this_thread_no, archiving_set_no);
		if (g_getfattr) {
			sprintf(curr_xattr_list_fname, XATTR_LIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no);
			get_fattr_list(archiving_filelist_fname, curr_xattr_list_fname);
		}
		if (g_getfacl) {
			sprintf(curr_acl_list_fname, ACL_LIST_FNAME_RAW_SZ,
				bkpinfo->tmpdir, archiving_set_no);
			get_acl_list(archiving_filelist_fname, curr_acl_list_fname);
		}

		log_msg(4, "%s[%d:%d] - archiving %d...", FORTY_SPACES, getpid(),
				this_thread_no, archiving_set_no);
		res =
			archive_this_fileset(archiving_filelist_fname,
								 archiving_afioball_fname,
								 archiving_set_no);
		retval += res;

		if (res) {
			sprintf(tmp,
					"Errors occurred while archiving set %ld. Please review logs.",
					archiving_set_no);
			log_to_screen(tmp);
		}
		if (!semaphore_p()) {
			fatal_error("Cannot get semaphore P");
		}

		set_bit_N_of_array(p_list_of_fileset_flags, archiving_set_no, 5);

		if (*p_last_set_archived < archiving_set_no) {
			*p_last_set_archived = archiving_set_no;
		}						// finished archiving this one

		if (!semaphore_v()) {
			fatal_error("Cannot get semaphore V");
		}
		log_msg(4, "%s[%d:%d] - archived %d OK", FORTY_SPACES, getpid(),
				this_thread_no, archiving_set_no);
		archiving_set_no++;
	}
	if (!semaphore_p()) {
		fatal_error("Cannot get semaphore P");
	}
	(*p_archival_threads_running)--;
	if (!semaphore_v()) {
		fatal_error("Cannot get semaphore V");
	}
	log_msg(3, "%s[%d:%d] - exiting", FORTY_SPACES, getpid(),
			this_thread_no);
	paranoid_free(archiving_filelist_fname);
	paranoid_free(archiving_afioball_fname);
	paranoid_free(curr_xattr_list_fname);
	paranoid_free(curr_acl_list_fname);
	paranoid_free(tmp);
	pthread_exit(NULL);
}





/**
 * Finalize the backup.
 * For streaming backups, this writes the closing block
 * to the stream. For CD-based backups, this creates
 * the final ISO image.
 * @param bkpinfo The backup information structure, used only
 * for the @c backup_media_type.
 * @ingroup MLarchiveGroup
 */
int do_that_final_phase()
{

	/*@ int ************************************** */
	int res = 0;
	int retval = 0;

	/*@ buffers ********************************** */

	assert(bkpinfo != NULL);
	mvaddstr_and_log_it(g_currentY, 0,
						"Writing any remaining data to media         ");

	log_msg(1, "Closing tape/CD/USB ... ");
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		/* write tape/cdstream */
		closeout_tape();
	} else {
		/* write final ISO/USB */
		res = write_final_iso_if_necessary();
		retval += res;
		if (res) {
			log_msg(1, "write_final_iso_if_necessary returned an error");
		}
	}
	log_msg(2, "Fork is exiting ... ");

	mvaddstr_and_log_it(g_currentY++, 74, "Done.");

	/* final stuff */
	if (retval) {
		mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
	} else {
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	}

	return (retval);
}


/**
 * Initialize the backup.
 * Does the following:
 * - Sets up the serial number.
 * - For streaming backups, opens the tape stream and writes the data disks
 *   and backup headers.
 * - For CD-based backups, wipes the ISOs in the target directory.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c cdrw_speed
 * - @c prefix
 * - @c isodir
 * - @c media_device
 * - @c scratchdir
 * - @c tmpdir
 * @return The number of errors encountered (0 for success).
 * @ingroup MLarchiveGroup
 */
int do_that_initial_phase()
{
	/*@ int *************************************** */
	int retval = 0;

	/*@ buffers *********************************** */
	char *command, *tmpfile, *data_disks_file;

	assert(bkpinfo != NULL);
	malloc_string(command);
	malloc_string(tmpfile);
	malloc_string(data_disks_file);
	sprintf(data_disks_file, "%s/all.tar.gz", bkpinfo->tmpdir);

	snprintf(g_serial_string, MAX_STR_LEN - 8, "%s",
			 call_program_and_get_last_line_of_output("dd \
if=/dev/urandom bs=16 count=1 2> /dev/null | \
hexdump | tr -s ' ' '0' | head -n1"));
	strip_spaces(g_serial_string);
	strcat(g_serial_string, "...word.");
	log_msg(2, "g_serial_string = '%s'", g_serial_string);
	assert(strlen(g_serial_string) < MAX_STR_LEN);

	sprintf(tmpfile, "%s/archives/SERIAL-STRING", bkpinfo->scratchdir);
	if (write_one_liner_data_file(tmpfile, g_serial_string)) {
		log_msg(1, "%ld: Failed to write serial string", __LINE__);
	}

	mvaddstr_and_log_it(g_currentY, 0, "Preparing to archive your data");
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		if (bkpinfo->backup_media_type == cdstream) {
			openout_cdstream(bkpinfo->media_device, bkpinfo->cdrw_speed);
		} else {
			openout_tape();	/* sets g_tape_stream */
		}
		if (!g_tape_stream) {
			fatal_error("Cannot open backup (streaming) device");
		}
		log_msg(1, "Backup (stream) opened OK");
		write_data_disks_to_stream(data_disks_file);
	} else {
		if (bkpinfo->backup_media_type == usb) {
			log_msg(1, "Backing up to USB's");
		} else {
			log_msg(1, "Backing up to CD's");
		}
	}

	sprintf(command, "rm -f %s/%s/%s-[1-9]*.iso", bkpinfo->isodir,
			bkpinfo->netfs_remote_dir, bkpinfo->prefix);
	paranoid_system(command);
	wipe_archives(bkpinfo->scratchdir);
	mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		write_header_block_to_stream((off_t)0, "start-of-tape",
									 BLK_START_OF_TAPE);
		write_header_block_to_stream((off_t)0, "start-of-backup",
									 BLK_START_OF_BACKUP);
	}
	paranoid_free(command);
	paranoid_free(tmpfile);
	paranoid_free(data_disks_file);
	return (retval);
}


/**
 * Get the <tt>N</tt>th bit of @c array.
 * @param array The bit-array (as a @c char pointer).
 * @param N The number of the bit you want.
 * @return TRUE (bit is set) or FALSE (bit is not set).
 * @see set_bit_N_of_array
 * @ingroup utilityGroup
 */
bool get_bit_N_of_array(char *array, int N)
{
	int element_number;
	int bit_number;
	int mask;

	element_number = N / 8;
	bit_number = N % 8;
	mask = 1 << bit_number;
	if (array[element_number] & mask) {
		return (TRUE);
	} else {
		return (FALSE);
	}
}









/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Start up threads to archive your files.
 *
 * This function starts @c ARCH_THREADS threads,
 * each starting execution in @c create_afio_files_in_background().
 * Each thread will archive individual filesets, based on the
 * pointers passed to it and continually updated, until all files
 * have been backed up. This function coordinates the threads
 * and copies their output to the @c scratchdir.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c scratchdir
 * - @c tmpdir
 * - @c zip_suffix
 *
 * @return The number of errors encountered (0 for success)
 */
int make_afioballs_and_images()
{

	/*@ int ************************************************** */
	int retval = 0;
	long int storing_set_no = 0;
	int res = 0;
	bool done_storing = FALSE;
	char *result_str;
	char *transfer_block;
	void *vp;
	void **pvp;

	/*@ buffers ********************************************** */
	char *storing_filelist_fname;
	char *storing_afioball_fname;
	char *tmp = NULL;
	char *media_usage_comment = NULL;
	pthread_t archival_thread[ARCH_THREADS];
	char *p_list_of_fileset_flags;
	int *p_archival_threads_running;
	int *p_last_set_archived;
	int *p_next_set_to_archive;
	int noof_threads;
	int i;
	char *curr_xattr_list_fname = NULL;
	char *curr_acl_list_fname = NULL;
	int misc_counter_that_is_not_important = 0;

	log_msg(8, "here");
	assert(bkpinfo != NULL);
	malloc_string(result_str);
	malloc_string(curr_xattr_list_fname);
	malloc_string(curr_acl_list_fname);
	malloc_string(storing_filelist_fname);
	malloc_string(storing_afioball_fname);
	transfer_block =
		malloc(sizeof(struct s_bkpinfo) + BKPINFO_LOC_OFFSET + 64);
	memset((void *) transfer_block, 0,
		   sizeof(struct s_bkpinfo) + BKPINFO_LOC_OFFSET + 64);
	p_last_set_archived = (int *) transfer_block;
	p_archival_threads_running = (int *) (transfer_block + 4);
	p_next_set_to_archive = (int *) (transfer_block + 8);
	p_list_of_fileset_flags = (char *) (transfer_block + 12);
	memcpy((void *) (transfer_block + BKPINFO_LOC_OFFSET),
		   (void *) bkpinfo, sizeof(struct s_bkpinfo));
	pvp = &vp;
	vp = (void *) result_str;
	*p_archival_threads_running = 0;
	*p_last_set_archived = -1;
	*p_next_set_to_archive = 0;
	log_to_screen("Archiving regular files");
	log_msg(5, "Go, Shorty. It's your birthday.");
	open_progress_form("Backing up filesystem",
					   "I am backing up your live filesystem now.",
					   "Please wait. This may take a couple of hours.",
					   "Working...",
					   get_last_filelist_number() + 1);

	log_msg(5, "We're gonna party like it's your birthday.");

	srand((unsigned int) getpid());
	g_sem_key = 1234 + random() % 30000;
	if ((g_sem_id =
		 semget((key_t) g_sem_key, 1,
				IPC_CREAT | S_IREAD | S_IWRITE)) == -1) {
		fatal_error("MABAI - unable to semget");
	}
	if (!set_semvalue()) {
		fatal_error("Unable to init semaphore");
	}							// initialize semaphore
	for (noof_threads = 0; noof_threads < ARCH_THREADS; noof_threads++) {
		log_msg(8, "Creating thread #%d", noof_threads);
		(*p_archival_threads_running)++;
		if ((res =
			 pthread_create(&archival_thread[noof_threads], NULL,
							create_afio_files_in_background,
							(void *) transfer_block))) {
			fatal_error("Unable to create an archival thread");
		}
	}

	log_msg(8, "About to enter while() loop");
	while (!done_storing) {
		if (g_exiting) {
			fatal_error("Execution run aborted (main loop)");
		}
		if (*p_archival_threads_running == 0
			&& *p_last_set_archived == storing_set_no - 1) {
			log_msg(2,
					"No archival threads are running. The last stored set was %d and I'm looking for %d. Take off your make-up; the party's over... :-)",
					*p_last_set_archived, storing_set_no);
			done_storing = TRUE;
		} else
			if (!get_bit_N_of_array
				(p_list_of_fileset_flags, storing_set_no)) {
			misc_counter_that_is_not_important =
				(misc_counter_that_is_not_important + 1) % 5;
			/* BCO the media_usage_comment is not really initialized there !
			if (!misc_counter_that_is_not_important) {
				update_progress_form(media_usage_comment);
			}
			*/
			sleep(1);
			} else
				// store set N
			{
				sprintf(storing_filelist_fname, FILELIST_FNAME_RAW_SZ,
						bkpinfo->tmpdir, storing_set_no);
				sprintf(storing_afioball_fname, AFIOBALL_FNAME_RAW_SZ,
						bkpinfo->tmpdir, storing_set_no, bkpinfo->zip_suffix);
				if (g_getfattr) {
					sprintf(curr_xattr_list_fname, XATTR_LIST_FNAME_RAW_SZ,
						bkpinfo->tmpdir, storing_set_no);
				}
				if (g_getfacl) {
					sprintf(curr_acl_list_fname, ACL_LIST_FNAME_RAW_SZ,
						bkpinfo->tmpdir, storing_set_no);
				}

				log_msg(2, "Storing set %d", storing_set_no);
				while (!does_file_exist(storing_filelist_fname)
				   	|| !does_file_exist(storing_afioball_fname)) {
					log_msg(2,
							"Warning - either %s or %s doesn't exist yet. I'll pause 5 secs.",
						storing_filelist_fname, storing_afioball_fname);
					sleep(5);
				}
				mr_asprintf(media_usage_comment, "%s", percent_media_full_comment());
				/* copy to CD (scratchdir) ... and an actual CD-R if necessary */
				if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
					register_in_tape_catalog(fileset, storing_set_no, -1,
										 storing_afioball_fname);
					maintain_collection_of_recent_archives(bkpinfo->tmpdir,
													   storing_afioball_fname);
					log_it("Writing EXAT files");
					res +=
						write_EXAT_files_to_tape(curr_xattr_list_fname,
											 curr_acl_list_fname);
					// archives themselves
					res +=
						move_files_to_stream(storing_afioball_fname,
										 NULL);
				} else {
					if (g_getfacl) {
						if (g_getfattr) {
							res = move_files_to_cd(storing_filelist_fname,
									 curr_xattr_list_fname,
									 curr_acl_list_fname,
									 storing_afioball_fname, NULL);
						} else {
							res = move_files_to_cd(storing_filelist_fname,
									curr_acl_list_fname,
									storing_afioball_fname, NULL);
						}
					} else {
						if (g_getfattr) {
							res = move_files_to_cd(storing_filelist_fname,
									curr_xattr_list_fname,
									storing_afioball_fname, NULL);
						} else {
							res = move_files_to_cd(storing_filelist_fname,
									storing_afioball_fname, NULL);
						}
					}
				}
				retval += res;
				g_current_progress++;
				update_progress_form(media_usage_comment);
				mr_free(media_usage_comment);
				if (res) {
					mr_asprintf(tmp, "Failed to add archive %ld's files to CD dir\n",
						storing_set_no);
					log_to_screen(tmp);
					paranoid_free(tmp);
					fatal_error
						("Is your hard disk full? If not, please send the author the logfile.");
				}
				storing_set_no++;
				//      sleep(2);
		}
	}
	close_progress_form();

	mr_asprintf(tmp, "Your regular files have been archived ");
	log_msg(2, "Joining background threads to foreground thread");
	for (i = 0; i < noof_threads; i++) {
		pthread_join(archival_thread[i], pvp);
		log_msg(3, "Thread %d of %d: closed OK", i + 1, noof_threads);
	}
	del_semvalue();
	log_msg(2, "Done.");
	if (retval) {
		mr_strcat(tmp, "(with errors).");
	} else {
		mr_strcat(tmp, "successfully.");
	}
	log_to_screen(tmp);
	paranoid_free(tmp);

	paranoid_free(transfer_block);
	paranoid_free(result_str);
	paranoid_free(storing_filelist_fname);
	paranoid_free(storing_afioball_fname);
	paranoid_free(curr_xattr_list_fname);
	paranoid_free(curr_acl_list_fname);
	return (retval);
}


void pause_for_N_seconds(int how_long, char *msg)
{
	int i;
	open_evalcall_form(msg);
	for (i = 0; i < how_long; i++) {
		update_evalcall_form((int) ((100.0 / (float) (how_long) * i)));
		sleep(1);
	}
	close_evalcall_form();
}




/**
 * Create a USB image in @c destfile, from files in @c bkpinfo->scratchdir.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c nonbootable_backup
 * - @c scratchdir
 *
 * @param destfile Where to put the generated USB image.
 * @return The number of errors encountered (0 for success)
 */
int make_usb_fs()
{
	/*@ int ********************************************** */
	int retval = 0;
	int res;

	/*@ buffers ****************************************** */
	char *tmp = NULL;
	char *tmp1 = NULL;
	char *result_sz = NULL;
	char *message_to_screen = NULL;
	char *old_pwd;
	char *mds = NULL;

	malloc_string(old_pwd);
	assert(bkpinfo != NULL);

	log_msg(2, "make_usb_fs --- scratchdir=%s", bkpinfo->scratchdir);
	tmp1 = getcwd(old_pwd, MAX_STR_LEN - 1);
	mr_asprintf(tmp, "chmod 700 %s", bkpinfo->scratchdir);
	run_program_and_log_output(tmp, FALSE);
	paranoid_free(tmp);
	if (chdir(bkpinfo->scratchdir)) {
		// FIXME
	}

	mds = media_descriptor_string(bkpinfo->backup_media_type);
	mr_asprintf(message_to_screen, "Copying data to make %s #%d",mds, g_current_media_number);
	mr_free(mds);
	log_msg(1, message_to_screen);

	mr_asprintf(tmp1, "%s1", bkpinfo->media_device);
	if (is_this_device_mounted(tmp1)) {
		log_msg(1, "USB device mounted. Remounting it at the right place");
		mr_asprintf(tmp, "umount %s", tmp1);
		run_program_and_log_output(tmp, FALSE);
		paranoid_free(tmp);
	}
	paranoid_free(tmp1);

	log_msg(1, "Mounting USB device.");
	mr_asprintf(tmp1, "%s/usb", bkpinfo->tmpdir);
	mr_asprintf(tmp, "mkdir -p %s", tmp1);
	run_program_and_log_output(tmp, FALSE);
	paranoid_free(tmp);

	/* Mindi always create one single parition on the USB dev */
	mr_asprintf(tmp, "mount %s1 %s", bkpinfo->media_device, tmp1);
	run_program_and_log_output(tmp, FALSE);
	paranoid_free(tmp);

	if (bkpinfo->nonbootable_backup) {
		log_msg(1, "Making nonbootable USB backup not implemented yet");
	} else {
		log_msg(1, "Making bootable backup");

		/* Command to execute */
		mr_asprintf(tmp,"mv %s/* %s", bkpinfo->scratchdir, tmp1); 
		res = eval_call_to_make_USB(tmp, message_to_screen);
		if (res) {
			mr_asprintf(result_sz, "%s ...failed",tmp);
		} else {
			mr_asprintf(result_sz, "%s ...OK",tmp);
		}
		log_to_screen(result_sz);
		paranoid_free(result_sz);
		paranoid_free(tmp);
		retval += res;

		/* Recreate the required structure under the scratch dir */
		mr_asprintf(tmp,"mkdir %s/archive", bkpinfo->scratchdir); 
		run_program_and_log_output(tmp, FALSE);
		paranoid_free(tmp);
	}
	paranoid_free(message_to_screen);
	paranoid_free(tmp1);

	if (is_this_device_mounted(bkpinfo->media_device)) {
		mr_asprintf(tmp, "umount %s1", bkpinfo->media_device);
		run_program_and_log_output(tmp, FALSE);
		paranoid_free(tmp);
	}

	if (chdir(old_pwd)) {
		// FIXME
	}
	if (retval) {
		log_msg(1, "WARNING - make_usb_fs returned an error");
	}
	paranoid_free(old_pwd);
	return (retval);
}


/**
 * Create an ISO image in @c destfile, from files in @c bkpinfo->scratchdir.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c call_after_iso
 * - @c call_before_iso
 * - @c call_burn_iso
 * - @c call_make_iso
 * - @c make_cd_use_lilo
 * - @c manual_cd_tray
 * - @c nonbootable_backup
 * - @c scratchdir
 *
 * @param destfile Where to put the generated ISO image.
 * @return The number of errors encountered (0 for success)
 */
int make_iso_fs(char *destfile)
{
	/*@ int ********************************************** */
	int retval = 0;
	int res;

	/*@ buffers ****************************************** */
	char *tmp;
	char *old_pwd;
	char *result_sz = NULL;
	char *message_to_screen = NULL;
	char *sz_blank_disk = NULL;
	char *fnam;
	char *tmp2;
	char *tmp3;
	char *isofs_cmd = NULL;
	char *full_isofs_cmd = NULL;
	char *mds = NULL;
	bool cd_is_mountable;

	malloc_string(old_pwd);
	malloc_string(fnam);
	tmp = malloc(1200);
	tmp2 = malloc(1200);
	tmp3 = malloc(1200);
	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(destfile);

	sprintf(tmp, "%s/isolinux.bin", bkpinfo->scratchdir);
	sprintf(tmp2, "%s/isolinux.bin", bkpinfo->tmpdir);
	if (does_file_exist(tmp)) {
		sprintf(tmp3, "cp -f %s %s", tmp, tmp2);
		paranoid_system(tmp3);
	}
	if (!does_file_exist(tmp) && does_file_exist(tmp2)) {
		sprintf(tmp3, "cp -f %s %s", tmp2, tmp);
		paranoid_system(tmp3);
	}
	free(tmp2);
	free(tmp3);
	tmp2 = NULL;
	tmp3 = NULL;
	if (bkpinfo->backup_media_type == iso && bkpinfo->manual_cd_tray) {
		popup_and_OK("Please insert new media and press Enter.");
	}

	log_msg(2, "make_iso_fs --- scratchdir=%s --- destfile=%s",
			bkpinfo->scratchdir, destfile);
	tmp2 = getcwd(old_pwd, MAX_STR_LEN - 1);
	sprintf(tmp, "chmod 700 %s", bkpinfo->scratchdir);
	run_program_and_log_output(tmp, FALSE);
	if (chdir(bkpinfo->scratchdir)) {
		// FIXME
	}

	if (bkpinfo->call_before_iso[0] != '\0') {
		mr_asprintf(message_to_screen, "Running pre-ISO call for CD#%d",
				g_current_media_number);
		res =
			eval_call_to_make_ISO(bkpinfo->call_before_iso,
								  destfile, g_current_media_number,
								  MONDO_LOGFILE, message_to_screen);
		if (res) {
			mr_strcat(message_to_screen, "...failed");
		} else {
			mr_strcat(message_to_screen, "...OK");
		}
		log_to_screen(message_to_screen);
		paranoid_free(message_to_screen);

		retval += res;
	}

	if (bkpinfo->call_make_iso[0] != '\0') {
		log_msg(2, "bkpinfo->call_make_iso = %s", bkpinfo->call_make_iso);
		sprintf(tmp, "%s/archives/NOT-THE-LAST", bkpinfo->scratchdir);
		mds = media_descriptor_string(bkpinfo->backup_media_type);
		mr_asprintf(message_to_screen, "Making an ISO (%s #%d)", mds, g_current_media_number);
		mr_free(mds);

		pause_and_ask_for_cdr(2, &cd_is_mountable);	/* if g_current_media_number >= 2 then pause & ask */
		if (retval) {
			log_to_screen
				("Serious error(s) occurred already. I shan't try to write to media.");
		} else {
			res =
				eval_call_to_make_ISO(bkpinfo->call_make_iso,
									  bkpinfo->scratchdir,
									  g_current_media_number,
									  MONDO_LOGFILE, message_to_screen);
			if (res) {
				log_to_screen("%s...failed to write", message_to_screen);
			} else {
				log_to_screen("%s...OK", message_to_screen);
				sprintf(tmp, "tail -n10 %s | grep -F ':-('", MONDO_LOGFILE);
				if (!run_program_and_log_output(tmp, 1)) {
					log_to_screen
						("Despite nonfatal errors, growisofs confirms the write was successful.");
				}
			}
			retval += res;
#ifdef DVDRWFORMAT
			sprintf(tmp,
					"tail -n8 %s | grep 'blank=full.*dvd-compat.*DAO'",
					MONDO_LOGFILE);
			if (g_backup_media_type == dvd
				&& (res || !run_program_and_log_output(tmp, 1))) {
				log_to_screen
					("Failed to write to disk. I shall blank it and then try again.");
				sleep(5);
				/* reset error counter before trying to blank DVD */
				retval -= res;
				paranoid_system("sync");
				pause_for_N_seconds(5, "Letting DVD drive settle");

// dvd+rw-format --- OPTION 2
				if (!bkpinfo->please_dont_eject) {
					log_to_screen("Ejecting media to clear drive status.");
					eject_device(bkpinfo->media_device);
					inject_device(bkpinfo->media_device);
				}
				pause_for_N_seconds(5, "Letting DVD drive settle");
				mr_asprintf(sz_blank_disk, "dvd+rw-format -force %s", bkpinfo->media_device);
				log_msg(3, "sz_blank_disk = '%s'", sz_blank_disk);
				res =
					run_external_binary_with_percentage_indicator_NEW
					("Blanking DVD disk", sz_blank_disk);
				if (res) {
					log_to_screen
						("Warning - format failed. (Was it a DVD-R?) Sleeping for 5 seconds to take a breath...");
					pause_for_N_seconds(5,
										"Letting DVD drive settle... and trying again.");
					res =
						run_external_binary_with_percentage_indicator_NEW
						("Blanking DVD disk", sz_blank_disk);
					if (res) {
						log_to_screen("Format failed a second time.");
					}
				} else {
					log_to_screen
						("Format succeeded. Sleeping for 5 seconds to take a breath...");
				}
				mr_free(sz_blank_disk);
				pause_for_N_seconds(5, "Letting DVD drive settle");
				if (!bkpinfo->please_dont_eject) {
					log_to_screen("Ejecting media to clear drive status.");
					eject_device(bkpinfo->media_device);
					inject_device(bkpinfo->media_device);
				}
				pause_for_N_seconds(5, "Letting DVD drive settle");
				res =
					eval_call_to_make_ISO(bkpinfo->call_make_iso,
										  bkpinfo->scratchdir,
										  g_current_media_number,
										  MONDO_LOGFILE,
										  message_to_screen);
				retval += res;
				if (!bkpinfo->please_dont_eject) {
					log_to_screen("Ejecting media.");
					eject_device(bkpinfo->media_device);
				}
				if (res) {
					log_to_screen("Dagnabbit. It still failed.");
				} else {
					log_to_screen
						("OK, this time I successfully backed up to DVD.");
				}
			}
#endif
			if (g_backup_media_type == dvd && !bkpinfo->please_dont_eject) {
				eject_device(bkpinfo->media_device);
			}
		}
		paranoid_free(message_to_screen);
	} else {
		mds = media_descriptor_string(bkpinfo->backup_media_type);
		mr_asprintf(message_to_screen, "Running mkisofs to make %s #%d", mds, g_current_media_number);
		log_msg(1, message_to_screen);
		mr_asprintf(result_sz, "Call to mkisofs to make ISO (%s #%d) ", mds,  g_current_media_number);
		mr_free(mds);
		if (find_home_of_exe("genisoimage")) {
			mr_asprintf(isofs_cmd, "%s", MONDO_GENISOIMAGE_CMD);
		} else {
			mr_asprintf(isofs_cmd, "%s", MONDO_MKISOFS_CMD);
		}
		if (bkpinfo->nonbootable_backup) {
			log_msg(1, "Making nonbootable backup");
			mr_asprintf(full_isofs_cmd, "%s%s-o '_ISO_' -V _CD#_ .",isofs_cmd,MONDO_MKISOFS);
			res = eval_call_to_make_ISO(full_isofs_cmd,
									  destfile, g_current_media_number,
									  MONDO_LOGFILE, message_to_screen);
			mr_free(full_isofs_cmd);
		} else {
			log_msg(1, "Making bootable backup");

#ifdef __FreeBSD__
			bkpinfo->make_cd_use_lilo = TRUE;
#endif


			log_msg(1, "make_cd_use_lilo is actually %d",
					bkpinfo->make_cd_use_lilo);
			if (bkpinfo->make_cd_use_lilo) {
				log_msg(1, "make_cd_use_lilo = TRUE");
#ifdef __IA64__
				log_msg(1, "IA64 --> elilo");
				mr_asprintf(full_isofs_cmd, "%s%s-o '_ISO_' -V _CD#_ .",isofs_cmd,MONDO_MKISOFS_REGULAR_ELILO);
				res = eval_call_to_make_ISO(full_isofs_cmd,
											destfile,
											g_current_media_number,
											MONDO_LOGFILE,
											message_to_screen);
				mr_free(full_isofs_cmd);
#else
				log_msg(1, "Non-ia64 --> lilo");
				mr_asprintf(full_isofs_cmd, "%s%s-b images/mindi-bootroot.2880.img -c boot.cat -o '_ISO_' -J -V _CD#_ .",isofs_cmd,MONDO_MKISOFS);
				res =
					// FIXME: fixed boot size probably wrong. lilo to be removed
					eval_call_to_make_ISO(full_isofs_cmd,
										  destfile, g_current_media_number,
										  MONDO_LOGFILE,
										  message_to_screen);
				mr_free(full_isofs_cmd);
#endif
			} else {
				log_msg(1, "make_cd_use_lilo = FALSE");
				log_msg(1, "Isolinux");
				mr_asprintf(full_isofs_cmd, "%s%s-o '_ISO_' -V _CD#_ .",isofs_cmd,MONDO_MKISOFS_REGULAR_SYSLINUX);
				res =
					eval_call_to_make_ISO(full_isofs_cmd,
										  destfile, g_current_media_number,
										  MONDO_LOGFILE,
										  message_to_screen);
				mr_free(full_isofs_cmd);
			}
		}
		mr_free(isofs_cmd);
		paranoid_free(message_to_screen);

		if (res) {
			mr_strcat(result_sz, "...failed");
		} else {
			mr_strcat(result_sz, "...OK");
		}
		log_to_screen(result_sz);
		paranoid_free(result_sz);
		retval += res;
	}

	if (bkpinfo->backup_media_type == cdr
		|| bkpinfo->backup_media_type == cdrw) {
		if (is_this_device_mounted(bkpinfo->media_device)) {
			log_msg(2,
					"Warning - %s mounted. I'm unmounting it before I burn to it.",
					bkpinfo->media_device);
			sprintf(tmp, "umount %s", bkpinfo->media_device);
			run_program_and_log_output(tmp, FALSE);
		}
	}

	if (bkpinfo->call_burn_iso[0] != '\0') {
		log_msg(2, "bkpinfo->call_burn_iso = %s", bkpinfo->call_burn_iso);
		mds = media_descriptor_string(bkpinfo->backup_media_type);
		mr_asprintf(message_to_screen, "Burning %s #%d", mds, g_current_media_number);
		mr_free(mds);
		pause_and_ask_for_cdr(2, &cd_is_mountable);
		res =
			eval_call_to_make_ISO(bkpinfo->call_burn_iso,
								  destfile, g_current_media_number,
								  MONDO_LOGFILE, message_to_screen);
		if (res) {
			mr_strcat(message_to_screen, "...failed");
		} else {
			mr_strcat(message_to_screen, "...OK");
		}
		log_to_screen(message_to_screen);
		paranoid_free(message_to_screen);

		retval += res;
	}

	if (bkpinfo->call_after_iso[0] != '\0') {
		mds = media_descriptor_string(bkpinfo->backup_media_type);
		mr_asprintf(message_to_screen, "Running post-ISO call (%s #%d)", mds, g_current_media_number);
		mr_free(mds);
		res =
			eval_call_to_make_ISO(bkpinfo->call_after_iso,
								  destfile, g_current_media_number,
								  MONDO_LOGFILE, message_to_screen);
		if (res) {
			mr_strcat(message_to_screen, "...failed");
		} else {
			mr_strcat(message_to_screen, "...OK");
		}
		log_to_screen(message_to_screen);
		paranoid_free(message_to_screen);

		retval += res;
	}

	if (chdir(old_pwd)) {
		// FIXME
	}
	if (retval) {
		log_msg(1, "WARNING - make_iso_fs returned an error");
	}
	paranoid_free(old_pwd);
	paranoid_free(fnam);
	paranoid_free(tmp);
	return (retval);
}


bool is_dev_an_NTFS_dev(char *bigfile_fname)
{
	char *tmp = NULL;
	char *command = NULL;
	bool ret = TRUE;

	mr_asprintf(command, "dd if=%s bs=512 count=1 2> /dev/null | strings | head -n1", bigfile_fname);
	log_msg(1, "command = '%s'", command);
	mr_asprintf(tmp, "%s", call_program_and_get_last_line_of_output(command));
	mr_free(command);

	log_msg(1, "--> tmp = '%s'", tmp);
	if (strstr(tmp, "NTFS")) {
		log_it("TRUE");
		ret = TRUE;
	} else {
		log_it("FALSE");
		ret = FALSE;
	}
	mr_free(tmp);
	return(ret);
}


/**
 * Back up big files by chopping them up.
 * This function backs up all "big" files (where "big" depends
 * on your backup media) in "chunks" (whose size again depends
 * on your media).
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c optimal_set_size
 * @param biggielist_fname The path to a file containing a list of
 * all "big" files.
 * @return The number of errors encountered (0 for success)
 * @see slice_up_file_etc
 */
int
make_slices_and_images(char *biggielist_fname)
{

	/*@ pointers ******************************************* */
	FILE *fin;
	char *p;
	char *q;

	/*@ buffers ******************************************** */
	char *tmp = NULL;
	char *bigfile_fname;
	char *sz_devfile = NULL;
	char *ntfsprog_fifo = NULL;
	/*@ long *********************************************** */
	long biggie_file_number = 0;
	long noof_biggie_files = 0;
	long estimated_total_noof_slices = 0;

	/*@ int ************************************************ */
	int retval = 0;
	int res = 0;
	pid_t pid;
	FILE *ftmp = NULL;
	bool delete_when_done;
	bool use_ntfsprog;
	off_t biggie_fsize;

	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(biggielist_fname);

	estimated_total_noof_slices =
		size_of_all_biggiefiles_K() / bkpinfo->optimal_set_size + 1;

	log_msg(1, "size of all biggiefiles = %ld",
			size_of_all_biggiefiles_K());
	log_msg(1, "estimated_total_noof_slices = %ld KB / %ld KB = %ld",
			size_of_all_biggiefiles_K(), bkpinfo->optimal_set_size,
			estimated_total_noof_slices);

	if (length_of_file(biggielist_fname) < 6) {
		log_msg(1, "No biggiefiles; fair enough...");
		return (0);
	}
	mr_asprintf(tmp, "I am now backing up all large files.");
	log_to_screen(tmp);
	noof_biggie_files = count_lines_in_file(biggielist_fname);
	open_progress_form("Backing up big files", tmp,
					   "Please wait. This may take some time.", "",
					   estimated_total_noof_slices);
	paranoid_free(tmp);

	if (!(fin = fopen(biggielist_fname, "r"))) {
		log_OS_error("Unable to openin biggielist");
		return (1);
	}

	malloc_string(bigfile_fname);
	for (q = fgets(bigfile_fname, MAX_STR_LEN, fin); !feof(fin) && (q != NULL);
		 q = fgets(bigfile_fname, MAX_STR_LEN, fin), biggie_file_number++) {
		use_ntfsprog = FALSE;
		if (bigfile_fname[strlen(bigfile_fname) - 1] < 32) {
			bigfile_fname[strlen(bigfile_fname) - 1] = '\0';
		}
		biggie_fsize = length_of_file(bigfile_fname);
		delete_when_done = FALSE;

		if (!does_file_exist(bigfile_fname)) {
			ftmp = fopen(bigfile_fname, "w");
			if (ftmp == NULL) {
				log_msg(3, "Unable to write to %s", bigfile_fname);
				// So skip it as it doesn't exist
				continue;
			} else {
				paranoid_fclose(ftmp);
			}
			delete_when_done = TRUE;
		} else {
			// Call ntfsclone (formerly partimagehack) if it's a /dev entry 
			// (i.e. a partition to be imaged)
			log_msg(2, "bigfile_fname = %s", bigfile_fname);
			use_ntfsprog = FALSE;
			if (!strncmp(bigfile_fname, "/dev/", 5)
				&& is_dev_an_NTFS_dev(bigfile_fname)) {
				use_ntfsprog = TRUE;
				log_msg(2,
						"Calling ntfsclone in background because %s is an NTFS partition",
						bigfile_fname);
				mr_asprintf(sz_devfile, "%s/%d.%d.000", bkpinfo->tmpdir,
						(int) (random() % 32768),
						(int) (random() % 32768));
				mkfifo(sz_devfile, 0x770);
				ntfsprog_fifo = sz_devfile;
				switch (pid = fork()) {
				case -1:
					mr_free(sz_devfile);
					fatal_error("Fork failure");
				case 0:
					log_msg(2,
							"CHILD - fip - calling feed_into_ntfsprog(%s, %s)",
							bigfile_fname, sz_devfile);
					res = feed_into_ntfsprog(bigfile_fname, sz_devfile);
					/* BCO/BERLIOS Does the child need to unalocate memory as well ?
					paranoid_free(bigfile_fname);
					mr_free(sz_devfile);
					*/
					exit(res);
					break;
				default:
					log_msg(2,
							"feed_into_ntfsprog() called in background --- pid=%ld",
							(long int) (pid));
				}
			}
			// Otherwise, use good old 'dd' and 'bzip2'
			else {
				ntfsprog_fifo = NULL;
			}

			// Whether partition or biggiefile, just do your thang :-)
			if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
				write_header_block_to_stream(biggie_fsize, bigfile_fname,
											 use_ntfsprog ?
											 BLK_START_A_PIHBIGGIE :
											 BLK_START_A_NORMBIGGIE);
			}
			res =
				slice_up_file_etc(bigfile_fname,
								  ntfsprog_fifo, biggie_file_number,
								  noof_biggie_files, use_ntfsprog);

			/* Free it here as ntfsprog_fifo is not used anymore */
			mr_free(sz_devfile);

			if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
				write_header_block_to_stream((off_t)0,
											 calc_checksum_of_file
											 (bigfile_fname),
											 BLK_STOP_A_BIGGIE);
			}
			retval += res;
			p = strrchr(bigfile_fname, '/');
			if (p) {
				p++;
			} else {
				p = bigfile_fname;
			}
			mr_asprintf(tmp, "Archiving %s ... ", bigfile_fname);
			if (res) {
				mr_strcat(tmp, "Failed!");
			} else {
				mr_strcat(tmp, "OK");
			}
			if (delete_when_done) {
				unlink(bigfile_fname);
				delete_when_done = FALSE;
			}
		}
#ifndef _XWIN
		if (!g_text_mode) {
			newtDrawRootText(0, g_noof_rows - 2, tmp);
			newtRefresh();
		}
#endif
		paranoid_free(tmp);
	}
	log_msg(1, "Finished backing up bigfiles");
	log_msg(1, "estimated slices = %ld; actual slices = %ld",
			estimated_total_noof_slices, g_current_progress);
	close_progress_form();
	paranoid_fclose(fin);
	paranoid_free(bigfile_fname);
	return (retval);
}




/**
 * Single-threaded version of @c make_afioballs_and_images().
 * @see make_afioballs_and_images
 */
int make_afioballs_and_images_OLD()
{

	/*@ int ************************************************** */
	int retval = 0;
	long int curr_set_no = 0L;
	int res = 0;

	/*@ buffers ********************************************** */
	char *curr_filelist_fname = NULL;
	char *curr_afioball_fname = NULL;
	char *curr_xattr_list_fname = NULL;
	char *curr_acl_list_fname = NULL;
	char *tmp = NULL;
	char *media_usage_comment = NULL;

	log_to_screen("Archiving regular files");

	open_progress_form("Backing up filesystem",
					   "I am backing up your live filesystem now.",
					   "Please wait. This may take a couple of hours.",
					   "Working...",
					   get_last_filelist_number() + 1);

	for (;;) {
		/* backup this set of files */
		mr_asprintf(curr_filelist_fname, FILELIST_FNAME_RAW_SZ, bkpinfo->tmpdir, curr_set_no);
		if (! does_file_exist(curr_filelist_fname)) {
			mr_free(curr_filelist_fname);
			break;
		}

		mr_asprintf(curr_afioball_fname, AFIOBALL_FNAME_RAW_SZ, bkpinfo->tmpdir, curr_set_no, bkpinfo->zip_suffix);

		log_msg(1, "EXAT'g set %ld", curr_set_no);
		if (g_getfattr) {
			mr_asprintf(curr_xattr_list_fname, XATTR_LIST_FNAME_RAW_SZ, bkpinfo->tmpdir, curr_set_no);
			get_fattr_list(curr_filelist_fname, curr_xattr_list_fname);
		}
		if (g_getfacl) {
			mr_asprintf(curr_acl_list_fname, ACL_LIST_FNAME_RAW_SZ, bkpinfo->tmpdir, curr_set_no);
			get_acl_list(curr_filelist_fname, curr_acl_list_fname);
		}

		log_msg(1, "Archiving set %ld", curr_set_no);
		res =
			archive_this_fileset(curr_filelist_fname,
								 curr_afioball_fname, curr_set_no);
		retval += res;
		if (res) {
			mr_asprintf(tmp, "Errors occurred while archiving set %ld. Perhaps your live filesystem changed?", curr_set_no);
			log_to_screen(tmp);
			mr_free(tmp);
		}

		mr_asprintf(media_usage_comment, "%s", percent_media_full_comment());

		/* copy to CD (scratchdir) ... and an actual CD-R if necessary */
		if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
			register_in_tape_catalog(fileset, curr_set_no, -1, curr_afioball_fname);
			maintain_collection_of_recent_archives(bkpinfo->tmpdir, curr_afioball_fname);
			log_it("Writing EXAT files");
			res +=
				write_EXAT_files_to_tape(curr_xattr_list_fname,
										 curr_acl_list_fname);
			// archives themselves
			res = move_files_to_stream(curr_afioball_fname, NULL);
		} else {
				if (g_getfacl) {
					if (g_getfattr) {
						res = move_files_to_cd(curr_filelist_fname,
									 curr_xattr_list_fname,
									 curr_acl_list_fname,
									 curr_afioball_fname, NULL);
					} else {
						res = move_files_to_cd(curr_filelist_fname,
									curr_acl_list_fname,
									curr_afioball_fname, NULL);
					}
				} else {
					if (g_getfattr) {
							res = move_files_to_cd(curr_filelist_fname,
									curr_xattr_list_fname,
									curr_afioball_fname, NULL);
					} else {
							res = move_files_to_cd(curr_filelist_fname,
									curr_afioball_fname, NULL);
					}
				}
		}
		if (g_getfattr) {
			mr_free(curr_xattr_list_fname);
		}
		if (g_getfacl) {
			mr_free(curr_acl_list_fname);
		}
		retval += res;
		g_current_progress++;
		update_progress_form(media_usage_comment);
		mr_free(media_usage_comment);

		if (res) {
			mr_asprintf(tmp, "Failed to add archive %ld's files to CD dir\n", curr_set_no);
			log_to_screen(tmp);
			mr_free(tmp);
			fatal_error
				("Is your hard disk is full? If not, please send the author the logfile.");
		}
		mr_free(curr_filelist_fname);
		mr_free(curr_afioball_fname);
		curr_set_no++;
	}
	close_progress_form();
	mr_asprintf(tmp, "Your regular files have been archived ");
	if (retval) {
		mr_strcat(tmp, "(with errors).");
	} else {
		mr_strcat(tmp, "successfully.");
	}
	log_to_screen(tmp);
	mr_free(tmp);
	return (retval);
}

/* @} - end of LLarchiveGroup */


/**
 * Wrapper around @c make_afioballs_and_images().
 * @param bkpinfo the backup information structure. Only the
 * @c backup_media_type field is used within this function.
 * @return return code of make_afioballs_and_images
 * @see make_afioballs_and_images
 * @ingroup MLarchiveGroup
 */
int make_those_afios_phase()
{
	/*@ int ******************************************* */
	int res = 0;
	int retval = 0;

	assert(bkpinfo != NULL);

	mvaddstr_and_log_it(g_currentY, 0,
						"Archiving regular files to media          ");

	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		write_header_block_to_stream((off_t)0, "start-of-afioballs",
									 BLK_START_AFIOBALLS);
#if __FreeBSD__ == 5
		log_msg(1,
				"Using single-threaded make_afioballs_and_images() to suit b0rken FreeBSD 5.0");
		res = make_afioballs_and_images_OLD();
#else
		res = make_afioballs_and_images_OLD();
#endif
		write_header_block_to_stream((off_t)0, "stop-afioballs",
									 BLK_STOP_AFIOBALLS);
	} else {
		res = make_afioballs_and_images();
	}

	retval += res;
	if (res) {
		mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
		log_msg(1, "make_afioballs_and_images returned an error");
	} else {
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	}
	return (retval);
}

/**
 * Wrapper around @c make_slices_and_images().
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c scratchdir
 * - @c tmpdir
 * @return The number of errors encountered (0 for success)
 * @ingroup MLarchiveGroup
 */
int make_those_slices_phase()
{

	/*@ int ***************************************************** */
	int res = 0;
	int retval = 0;

	/*@ buffers ************************************************** */
	char *biggielist = NULL;
	char *command = NULL;
	char *blah = NULL;
	char *xattr_fname = NULL;
	char *acl_fname = NULL;

	assert(bkpinfo != NULL);
	/* slice big files */
	mvaddstr_and_log_it(g_currentY, 0,
						"Archiving large files to media           ");
	mr_asprintf(biggielist, "%s/archives/biggielist.txt", bkpinfo->scratchdir);
	if (g_getfattr) {
		mr_asprintf(xattr_fname, XATTR_BIGGLST_FNAME_RAW_SZ, bkpinfo->tmpdir);
	}
	if (g_getfacl) {
		mr_asprintf(acl_fname, ACL_BIGGLST_FNAME_RAW_SZ, bkpinfo->tmpdir);
	}

	mr_asprintf(command, "cp %s/biggielist.txt %s", bkpinfo->tmpdir,
			biggielist);
	paranoid_system(command);
	mr_free(command);

	mr_asprintf(blah, "biggielist = %s", biggielist);
	log_msg(2, blah);
	mr_free(blah);

	if (!does_file_exist(biggielist)) {
		log_msg(1, "BTW, the biggielist does not exist");
	}

	if (g_getfattr) {
		get_fattr_list(biggielist, xattr_fname);
		mr_asprintf(command, "cp %s %s/archives/", xattr_fname,
			bkpinfo->scratchdir);
		paranoid_system(command);
		mr_free(command);
	}
	if (g_getfacl) {
		get_acl_list(biggielist, acl_fname);
		mr_asprintf(command, "cp %s %s/archives/", acl_fname, bkpinfo->scratchdir);
		paranoid_system(command);
		mr_free(command);
	}

	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		res += write_EXAT_files_to_tape(xattr_fname, acl_fname);
		mr_asprintf(blah, "%ld", count_lines_in_file(biggielist));
		write_header_block_to_stream((off_t)0, blah, BLK_START_BIGGIEFILES);
		mr_free(blah);
	}
	res = make_slices_and_images(biggielist);
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		write_header_block_to_stream((off_t)0, "end-of-biggiefiles",
									 BLK_STOP_BIGGIEFILES);
	}
	retval += res;
	if (res) {
		log_msg(1, "make_slices_and_images returned an error");
		mvaddstr_and_log_it(g_currentY++, 74, "Errors.");
	} else {
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	}
	mr_free(biggielist);
	mr_free(xattr_fname);
	mr_free(acl_fname);
	return (retval);
}


/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Function pointer to an appropriate @c move_files_to_cd routine.
 * You can set this to your own function (for example, one to
 * transfer files over the network) or leave it as is.
 */
int (*move_files_to_cd) (char *, ...) =
	_move_files_to_cd;

/**
 * Move some files to the ISO scratch directory.
 * This function moves files specified as parameters, into the directory
 * @c bkpinfo->scratchdir, where the files that will be stored on the next
 * CD are waiting.
 *
 * @param bkpinfo The backup information structure. Fields used:
 * - @c media_size
 * - @c scratchdir
 * @param files_to_add The files to add to the scratchdir.
 * @warning The list of @c files_to_add must be terminated with @c NULL.
 * @note If and when the space occupied by the scratchdir would exceed
 * the capacity of the current CD,
 * <tt>write_iso_and_go_on(bkpinfo, FALSE)</tt> is called and the
 * scratchdir is emptied.
 *
 * @return The number of errors encountered (0 for success)
 */
int _move_files_to_cd(char *files_to_add, ...)
{

	/*@ int ************************************************************ */
	int retval = 0;
	int res = 0;

	/*@ buffers ******************************************************** */
	char *tmp = NULL;
	char *curr_file = NULL;
	char *cf;

	/*@ long ************************************************************ */
	va_list ap;
	long long would_occupy;

	assert(bkpinfo != NULL);
	would_occupy = space_occupied_by_cd(bkpinfo->scratchdir);
	va_start(ap, files_to_add);	// initialize the variable arguments
	for (cf = files_to_add; cf != NULL; cf = va_arg(ap, char *)) {
		if (!cf) {
			continue;
		}
		mr_asprintf(curr_file, "%s", cf);
		if (!does_file_exist(curr_file)) {
			log_msg(1,
					"Warning - you're trying to add a non-existent file - '%s' to the CD",
					curr_file);
		} else {
			log_msg(8, "Trying to add file %s to CD", curr_file);
			would_occupy += length_of_file(curr_file) / 1024;
		}
		mr_free(curr_file);
	}
	va_end(ap);

	if (bkpinfo->media_size <= 0) {
		fatal_error("move_files_to_cd() - unknown media size");
	}
	if (would_occupy / 1024 > bkpinfo->media_size) {
		res = write_iso_and_go_on(FALSE);	/* FALSE because this is not the last CD we'll write */
		retval += res;
		if (res) {
			log_msg(1, "WARNING - write_iso_and_go_on returned an error");
		}
	}

	va_start(ap, files_to_add);	// initialize the variable arguments
	for (cf = files_to_add; cf != NULL; cf = va_arg(ap, char *)) {
		if (!cf) {
			continue;
		}
		mr_asprintf(curr_file, "%s", cf);

		mr_asprintf(tmp, "mv -f %s %s/archives/", curr_file, bkpinfo->scratchdir);
		mr_free(curr_file);
		res = run_program_and_log_output(tmp, 5);
		retval += res;
		if (res) {
			log_msg(1, "(move_files_to_cd) '%s' failed", tmp);
		} else {
			log_msg(8, "Moved %s to CD OK", tmp);
		}
		mr_free(tmp);
	}
	va_end(ap);

	if (retval) {
		log_msg(1,
				"Warning - errors occurred while I was adding files to CD dir");
	}
	return (retval);
}

/* @} - end of LLarchiveGroup */


/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Function pointer to an appropriate @c move_files_to_stream routine.
 * You can set this to your own function (for example, one to
 * transfer files over the network) or leave it as is.
 */
int (*move_files_to_stream) (char *, ...) =
	_move_files_to_stream;

/**
 * Copy some files to tape.
 * This function copies the files specified as parameters into the tape stream.
 *
 * @param bkpinfo The backup information structure. Used only in the call to
 * @c write_file_to_stream_from_file().
 *
 * @param files_to_add The files to copy to the tape stream.
 * @warning The list of @c files_to_add must be terminated with @c NULL.
 * @note Files may be split across multiple tapes if necessary.
 *
 * @return The number of errors encountered (0 for success)
 */
int
_move_files_to_stream(char *files_to_add, ...)
{

	/*@ int ************************************************************ */
	int retval = 0;
	int res = 0;
	/*@ buffers ******************************************************** */

	/*@ char *********************************************************** */
	char start_chr;
	char stop_chr;
	char *curr_file = NULL;
	char *cf;
	/*@ long long ****************************************************** */
	off_t length_of_incoming_file = (off_t)0;
	va_list ap;

	assert(bkpinfo != NULL);
	va_start(ap, files_to_add);
	for (cf = files_to_add; cf != NULL; cf = va_arg(ap, char *)) {
		if (!cf) {
			continue;
		}
		mr_asprintf(curr_file, "%s", cf);
		if (!does_file_exist(curr_file)) {
			log_msg(1,
					"Warning - you're trying to add a non-existent file - '%s' to the tape",
					curr_file);
		}
		/* create header chars */
		start_chr = BLK_START_AN_AFIO_OR_SLICE;
		stop_chr = BLK_STOP_AN_AFIO_OR_SLICE;
		/* ask for new tape if necessary */
		length_of_incoming_file = length_of_file(curr_file);
		write_header_block_to_stream(length_of_incoming_file, curr_file,
									 start_chr);
		res = write_file_to_stream_from_file(curr_file);
		retval += res;
		unlink(curr_file);
		mr_free(curr_file);
		/* write closing header */
		write_header_block_to_stream((off_t)0, "finished-writing-file", stop_chr);
	}
	va_end(ap);

	if (retval) {
		log_msg(1,
				"Warning - errors occurred while I was adding file to tape");
	}
	return (retval);
}

/* @} - end of LLarchiveGroup */



/**
 * @addtogroup utilityGroup
 * @{
 */
/**
 * Make sure the user has a valid CD-R(W) in the CD drive.
 * @param cdrw_dev Set to the CD-R(W) device checked.
 * @param keep_looping If TRUE, keep pestering user until they insist
 * or insert a correct CD; if FALSE, only check once.
 * @return 0 (there was an OK CD in the drive) or 1 (there wasn't).
 */
int interrogate_disk_currently_in_cdrw_drive(char *cdrw_dev,
											 bool keep_looping)
{
	int res = 0;
	char *bkp = NULL;
	char *cdrecord = NULL;

	mr_asprintf(bkp, "%s", cdrw_dev);
	if (find_cdrw_device(cdrw_dev)) {
		strcpy(cdrw_dev, bkp);
	} else {
		if (!system("which cdrecord > /dev/null 2> /dev/null")) {
			mr_asprintf(cdrecord, "cdrecord dev=%s -atip", cdrw_dev);
		} else if (!system("which dvdrecord > /dev/null 2> /dev/null")) {
			mr_asprintf(cdrecord, "cdrecord dev=%s -atip", cdrw_dev);
		} else {
			log_msg(2, "Oh well. I guess I'll just pray then.");
		}
		if (cdrecord != NULL) {
			if (!keep_looping) {
				retract_CD_tray_and_defeat_autorun();
				res = run_program_and_log_output(cdrecord, 5);
			} else {
				while ((res = run_program_and_log_output(cdrecord, 5))) {
					retract_CD_tray_and_defeat_autorun();
					if (ask_me_yes_or_no
						("Unable to examine CD. Are you sure this is a valid CD-R(W) CD?"))
					{
						log_msg(1, "Well, he insisted...");
						break;
					}
				}
			}
		}
	}
	mr_free(bkp);

	mr_free(cdrecord);
	return (res);
}


/**
 * Asks the user to put a CD-R(W) in the drive.
 * @param ask_for_one_if_more_than_this (unused)
 * @param pmountable If non-NULL, pointed-to value is set to TRUE if the CD is mountable, FALSE otherwise.
 */
void
pause_and_ask_for_cdr(int ask_for_one_if_more_than_this, bool * pmountable)
{

	/*@ buffers ********************************************* */
	char *tmp = NULL;
	char *cdrom_dev;
	char *cdrw_dev;
	char *our_serial_str = NULL;
	bool ok_go_ahead_burn_it;
	int cd_number = -1;
	int attempt_to_mount_returned_this = 999;
	char *mtpt = NULL;
	char *szcdno;
	char *szserfname;
	char *szunmount;
	char *mds = NULL;

	malloc_string(cdrom_dev);
	malloc_string(cdrw_dev);
	malloc_string(szcdno);
	malloc_string(szserfname);
	malloc_string(szunmount);
	malloc_string(mtpt);

	mds = media_descriptor_string(g_backup_media_type);
	mr_asprintf(tmp, "I am about to burn %s #%d", mds, g_current_media_number);
	mr_free(mds);
	log_to_screen(tmp);
	mr_free(tmp);
	if (g_current_media_number < ask_for_one_if_more_than_this) {
		return;
	}
	log_to_screen("Scanning CD-ROM drive...");
	sprintf(mtpt, "%s/cd.mtpt", bkpinfo->tmpdir);
	make_hole_for_dir(mtpt);

  gotos_make_me_puke:
	ok_go_ahead_burn_it = TRUE;
	if (!find_cdrom_device(cdrom_dev, FALSE)) {
/* When enabled, it made CD eject-and-retract when wrong CD inserted.. Weird
      log_msg(2, "paafcd: Retracting CD-ROM drive if possible" );
      retract_CD_tray_and_defeat_autorun();
*/
		mr_asprintf(tmp, "umount %s", cdrom_dev);
		run_program_and_log_output(tmp, 1);
		sprintf(szcdno, "%s/archives/THIS-CD-NUMBER", mtpt);
		sprintf(szserfname, "%s/archives/SERIAL-STRING", mtpt);
		sprintf(szunmount, "umount %s", mtpt);
		cd_number = -1;
		mr_asprintf(tmp, "mount %s %s", cdrom_dev, mtpt);
		mr_asprintf(our_serial_str, "%s", "");
		attempt_to_mount_returned_this = run_program_and_log_output(tmp, 1);
		mr_free(tmp);
		if (attempt_to_mount_returned_this) {
			log_msg(4, "Failed to mount %s at %s", cdrom_dev, mtpt);
			log_to_screen("If there's a CD/DVD in the drive, it's blank.");
			/*
			   if (interrogate_disk_currently_in_cdrw_drive(cdrw_dev, FALSE))
			   {
			   ok_go_ahead_burn_it = FALSE;
			   log_to_screen("There isn't a writable CD/DVD in the drive.");
			   }
			   else
			   {
			   log_to_screen("Confirmed. There is a blank CD/DVD in the drive.");
			   }
			 */
		} else if (!does_file_exist(szcdno)
				   || !does_file_exist(szserfname)) {
			mds = media_descriptor_string(g_backup_media_type);
			log_to_screen
				("%s has data on it but it's probably not a Mondo CD.", mds);
			mr_free(mds);
		} else {
			mds = media_descriptor_string(g_backup_media_type);
			log_to_screen("%s found in drive. It's a Mondo disk.", mds);
			mr_free(mds);

			cd_number = atoi(last_line_of_file(szcdno));
			mr_asprintf(tmp, "cat %s 2> /dev/null", szserfname);
			mr_free(our_serial_str);
			mr_asprintf(our_serial_str, "%s",
				   call_program_and_get_last_line_of_output(tmp));
			mr_free(tmp);
			// FIXME - should be able to use last_line_of_file(), surely?
		}
		run_program_and_log_output(szunmount, 1);
		log_msg(2, "paafcd: cd_number = %d", cd_number);
		log_msg(2, "our serial str = %s; g_serial_string = %s",
				our_serial_str, g_serial_string);
		if (cd_number > 0 && !strcmp(our_serial_str, g_serial_string)) {
			mds = media_descriptor_string(g_backup_media_type);
			log_msg(2, "This %s is part of this backup set!", mds);
			ok_go_ahead_burn_it = FALSE;
			if (cd_number == g_current_media_number - 1) {
				log_to_screen("I think you've left the previous %s in the drive.", mds);
			} else {
				log_to_screen("Please remove this %s. It is part of the backup set you're making now.", mds);
			}
			mr_free(mds);

		} else {
			log_to_screen("...but not part of _our_ backup set.");
		}
		mr_free(our_serial_str);
	} else {
		mds = media_descriptor_string(g_backup_media_type);
		log_msg(2,
				"paafcd: Can't find CD-ROM drive. Perhaps it has a blank %s in it?", mds);
		if (interrogate_disk_currently_in_cdrw_drive(cdrw_dev, FALSE)) {
			ok_go_ahead_burn_it = FALSE;
			log_to_screen("There isn't a writable %s in the drive.", mds);
		}
		mr_free(mds);
	}

	if (!ok_go_ahead_burn_it) {
		if (!bkpinfo->please_dont_eject) {
			eject_device(cdrom_dev);
		}
		mds = media_descriptor_string(g_backup_media_type);
		mr_asprintf(tmp, "I am about to burn %s #%d of the backup set. Please insert %s and press Enter.", 
				mds, g_current_media_number, mds);
		mr_free(mds);

		popup_and_OK(tmp);
		mr_free(tmp);
		goto gotos_make_me_puke;
	} else {
		log_msg(2, "paafcd: OK, going ahead and burning it.");
	}

	mds = media_descriptor_string(g_backup_media_type);
	log_msg(2,
			"paafcd: OK, I assume I have a blank/reusable %s in the drive...", mds);

	log_to_screen("Proceeding w/ %s in drive.", mds);
	mr_free(mds);

	paranoid_free(cdrom_dev);
	paranoid_free(cdrw_dev);
	paranoid_free(mtpt);
	paranoid_free(szcdno);
	paranoid_free(szserfname);
	paranoid_free(szunmount);
	if (pmountable) {
		if (attempt_to_mount_returned_this) {
			*pmountable = FALSE;
		} else {
			*pmountable = TRUE;
		}
	}

}








/**
 * Set the <tt>N</tt>th bit of @c array to @c true_or_false.
 * @param array The bit array (as a @c char pointer).
 * @param N The bit number to set or reset.
 * @param true_or_false If TRUE then set bit @c N, if FALSE then reset bit @c N.
 * @see get_bit_N_of_array
 */
void set_bit_N_of_array(char *array, int N, bool true_or_false)
{
	int bit_number;
	int mask, orig_val, to_add;
	int element_number;

	assert(array != NULL);

	element_number = N / 8;
	bit_number = N % 8;
	to_add = (1 << bit_number);
	mask = 255 - to_add;
	orig_val = array[element_number] & mask;
	//  log_it("array[%d]=%02x; %02x&%02x = %02x", element_number, array[element_number], mask, orig_val);
	if (true_or_false) {
		array[element_number] = orig_val | to_add;
	}
}

/* @} - end of utilityGroup */








/**
 * Chop up @c filename.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c compression_level
 * - @c optimal_set_size
 * - @c tmpdir
 * - @c use_lzo
 * - @c zip_exe
 * - @c zip_suffix
 *
 * @param biggie_filename The file to chop up.
 * @param ntfsprog_fifo The FIFO to ntfsclone if this is an imagedev, NULL otherwise.
 * @param biggie_file_number The sequence number of this biggie file (starting from 0).
 * @param noof_biggie_files The number of biggie files there are total.
 * @return The number of errors encountered (0 for success)
 * @see make_slices_and_images
 * @ingroup LLarchiveGroup
 */
int
slice_up_file_etc(char *biggie_filename,
				  char *ntfsprog_fifo, long biggie_file_number,
				  long noof_biggie_files, bool use_ntfsprog)
{

	/*@ buffers ************************************************** */
	char *tmp = NULL;
	char *checksum_line, *command;
	char *tempblock;
	char *curr_slice_fname_uncompressed = NULL;
	char *curr_slice_fname_compressed = NULL;
	char *file_to_archive = NULL;
	char *file_to_openin;
	/*@ pointers ************************************************** */
	char *pB;
	FILE *fin = NULL, *fout = NULL;

	/*@ bool ****************************************************** */
	bool finished = FALSE;

	/*@ long ****************************************************** */
	size_t blksize = 0;
	long slice_num = 0;
	long i;
	long optimal_set_size;
	bool should_I_compress_slices;
	char *suffix = NULL;				// for compressed slices

	/*@ long long ************************************************** */
	off_t totalread = (off_t)0;
	off_t totallength = (off_t)0;

	/*@ int ******************************************************** */
	int retval = 0;
	int res = 0;

	/*@ structures ************************************************** */
	struct s_filename_and_lstat_info biggiestruct;
//  struct stat statbuf;

	assert(bkpinfo != NULL);
	assert_string_is_neither_NULL_nor_zerolength(biggie_filename);
	malloc_string(checksum_line);

	biggiestruct.for_backward_compatibility = '\n';
	biggiestruct.use_ntfsprog = use_ntfsprog;
	optimal_set_size = bkpinfo->optimal_set_size;
	if (is_this_file_compressed(biggie_filename)
		|| bkpinfo->compression_level == 0) {
		mr_asprintf(suffix, "%s", "");
		//      log_it("%s is indeed compressed :-)", filename);
		should_I_compress_slices = FALSE;
	} else {
		mr_asprintf(suffix, "%s", bkpinfo->zip_suffix);
		should_I_compress_slices = TRUE;
	}

	if (optimal_set_size < 999) {
		fatal_error("bkpinfo->optimal_set_size is insanely small");
	}
	if (ntfsprog_fifo) {
		file_to_openin = ntfsprog_fifo;
		strcpy(checksum_line, "IGNORE");
		log_msg(2,
				"Not calculating checksum for %s: it would take too long",
				biggie_filename);
		if ( !find_home_of_exe("ntfsresize")) {
			fatal_error("ntfsresize not found");
		}
		mr_asprintf(command, "ntfsresize --force --info %s|grep '^You might resize at '|cut -d' ' -f5", biggie_filename);
		log_it("command = %s", command);
		mr_asprintf(tmp, "%s", call_program_and_get_last_line_of_output(command));
		mr_free(command);
		log_it("res of it = %s", tmp); 
		totallength = (off_t)atoll(tmp);
		paranoid_free(tmp);
	} else {
		file_to_openin = biggie_filename;
		if (strchr(biggie_filename,'\'') != NULL) {
			mr_asprintf(command, "md5sum \"%s\"", biggie_filename);
		} else {
			mr_asprintf(command, "md5sum '%s'", biggie_filename);
		}
		if (!(fin = popen(command, "r"))) {
			log_OS_error("Unable to popen-in command");
			mr_free(suffix);
			return (1);
		}
		mr_free(command);
		tmp = fgets(checksum_line, MAX_STR_LEN, fin);
		pclose(fin);
		totallength = length_of_file (biggie_filename);
	}
	lstat(biggie_filename, &biggiestruct.properties);
	strcpy(biggiestruct.filename, biggie_filename);
	pB = strchr(checksum_line, ' ');
	if (!pB) {
		pB = strchr(checksum_line, '\t');
	}
	if (pB) {
		*pB = '\0';
	}
	strcpy(biggiestruct.checksum, checksum_line);

	mr_asprintf(tmp, "%s", slice_fname(biggie_file_number, 0, bkpinfo->tmpdir, ""));
	fout = fopen(tmp, "w");
	if (fout == NULL) {
		log_msg(1, "Unable to open and write to %s\n", tmp);
		paranoid_free(tmp);
		mr_free(suffix);
		return (1);
	}
	paranoid_free(tmp);

	res = fwrite((void *) &biggiestruct, 1, sizeof(biggiestruct), fout);
	if (fout != NULL) {
		paranoid_fclose(fout);
	}
	log_msg(1, "Opening in %s; slicing it and writing to CD/tape",
			file_to_openin);
	if (!(fin = fopen(file_to_openin, "r"))) {
		log_OS_error("Unable to openin biggie_filename");
		mr_asprintf(tmp, "Cannot archive bigfile '%s': not found", biggie_filename);
		log_to_screen(tmp);
		paranoid_free(tmp);

		paranoid_free(checksum_line);
		mr_free(suffix);
		return (1);
	}
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		res =
			move_files_to_stream(slice_fname(biggie_file_number, 0,
											 bkpinfo->tmpdir, ""), NULL);
	} else {
		res =
			move_files_to_cd(slice_fname(biggie_file_number, 0,
										 bkpinfo->tmpdir, ""), NULL);
	}
	i = bkpinfo->optimal_set_size / 256;
	if (!(tempblock = (char *) malloc(256 * 1024))) {
		fatal_error("malloc error 256*1024");
	}
	for (slice_num = 1; !finished; slice_num++) {
		mr_asprintf(curr_slice_fname_uncompressed, "%s", slice_fname(biggie_file_number, slice_num, bkpinfo->tmpdir, ""));
		mr_asprintf(curr_slice_fname_compressed, "%s", slice_fname(biggie_file_number, slice_num, bkpinfo->tmpdir, suffix));

		mr_asprintf(tmp, "%s", percent_media_full_comment());
		update_progress_form(tmp);
		paranoid_free(tmp);

		if (!(fout = fopen(curr_slice_fname_uncompressed, "w"))) {
			log_OS_error(curr_slice_fname_uncompressed);
			mr_free(suffix);
			return (1);
		}
		if ((i == bkpinfo->optimal_set_size / 256)
			&& (totalread < 1.1 * totallength)) {
			for (i = 0; i < bkpinfo->optimal_set_size / 256; i++) {
				blksize = fread(tempblock, 1, 256 * 1024, fin);
				if (blksize > 0) {
					totalread = totalread + blksize;
					res = fwrite(tempblock, 1, blksize, fout);
				} else {
					break;
				}
			}
		} else {
			i = 0;
		}
		paranoid_fclose(fout);
		if (i > 0)				// length_of_file (curr_slice_fname_uncompressed)
		{
			if (!does_file_exist(curr_slice_fname_uncompressed)) {
				log_msg(2,
						"Warning - '%s' doesn't exist. How can I compress slice?",
						curr_slice_fname_uncompressed);
			}
			if (should_I_compress_slices && bkpinfo->compression_level > 0) {
				mr_asprintf(command, "%s -%d %s", bkpinfo->zip_exe, bkpinfo->compression_level, curr_slice_fname_uncompressed);
				log_msg(2, command);
				if ((res = system(command))) {
					log_OS_error(command);
				}
				//          did_I_compress_slice = TRUE;
			} else {
				mr_asprintf(command, "mv %s %s 2>> %s", curr_slice_fname_uncompressed, curr_slice_fname_compressed, MONDO_LOGFILE);
				res = 0;		// don't do it :)
				//          did_I_compress_slice = FALSE;
			}
			mr_free(command);

			retval += res;
			if (res) {
				log_msg(2, "Failed to compress the slice");
			}
			if (bkpinfo->use_lzo
				&& strcmp(curr_slice_fname_compressed,
						  curr_slice_fname_uncompressed)) {
				unlink(curr_slice_fname_uncompressed);
			}
			if (res) {
				mr_asprintf(tmp, "Problem with slice # %ld", slice_num);
			} else {
				mr_asprintf(tmp, "%s - Bigfile #%ld, slice #%ld compressed OK          ", biggie_filename, biggie_file_number + 1,
						slice_num);
			}
#ifndef _XWIN
			if (!g_text_mode) {
				newtDrawRootText(0, g_noof_rows - 2, tmp);
				newtRefresh();
			} else {
				log_msg(2, tmp);
			}
#else
			log_msg(2, tmp);
#endif
			paranoid_free(tmp);

			mr_asprintf(file_to_archive, "%s", curr_slice_fname_compressed);
			g_current_progress++;
		} else {				/* if i==0 then ... */

			finished = TRUE;
			mr_asprintf(file_to_archive, "%s", curr_slice_fname_uncompressed);
			if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
				break;
			}
		}
		mr_free(curr_slice_fname_uncompressed);
		mr_free(curr_slice_fname_compressed);

		if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
			register_in_tape_catalog(biggieslice, biggie_file_number,
									 slice_num, file_to_archive);
			maintain_collection_of_recent_archives(bkpinfo->tmpdir,
												   file_to_archive);
			res = move_files_to_stream(file_to_archive, NULL);
		} else {
			res = move_files_to_cd(file_to_archive, NULL);
		}
		mr_free(file_to_archive);

		retval += res;
		if (res) {
			mr_asprintf(tmp, "Failed to add slice %ld of bigfile %ld to scratchdir", slice_num, biggie_file_number + 1);
			log_to_screen(tmp);
			paranoid_free(tmp);
			fatal_error
				("Hard disk full. You should have bought a bigger one.");
		}
	}
	mr_free(tempblock);
	mr_free(suffix);
	paranoid_fclose(fin);
	mr_asprintf(tmp, "Sliced bigfile #%ld", biggie_file_number + 1);
	if (retval) {
		mr_strcat(tmp, "...FAILED");
	} else {
		mr_strcat(tmp, "...OK!");
	}
	log_msg(1, tmp);
	paranoid_free(tmp);

	paranoid_free(checksum_line);
	return (retval);
}


/**
 * Remove the archives in @c d.
 * This could possibly include any of:
 * - all afioballs (compressed and not)
 * - all filelists
 * - all slices
 * - all checksums
 * - a zero filler file
 *
 * @param d The directory to wipe the archives from.
 * @ingroup utilityGroup
 */
void wipe_archives(char *d)
{
	/*@ buffers ********************************************* */
	char *tmp = NULL;
	char *dir = NULL;

	assert_string_is_neither_NULL_nor_zerolength(d);

	mr_asprintf(dir, "%s/archives", d);
	mr_asprintf(tmp, "find %s -name '*.afio*' -exec rm -f '{}' \\;", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);
	mr_asprintf(tmp, "find %s -name '*list.[0-9]*' -exec rm -f '{}' \\;", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);
	mr_asprintf(tmp, "find %s -name 'slice*' -exec rm -f '{}' \\;", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);
	mr_asprintf(tmp, "rm -f %s/cklist*", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);
	mr_asprintf(tmp, "rm -f %s/zero", dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);
	log_msg(1, "Wiped %s's archives", dir);
	mr_asprintf(tmp, "ls -l %s", dir);
	mr_free(dir);
	run_program_and_log_output(tmp, FALSE);
	mr_free(tmp);
}


/**
 * @addtogroup LLarchiveGroup
 * @{
 */
/**
 * Write the final ISO image.
 * @param bkpinfo The backup information structure. Used only
 * in the call to @c write_iso_and_go_on().
 * @return The number of errors encountered (0 for success)
 * @see write_iso_and_go_on
 * @see make_iso_fs
 * @bug The final ISO is written even if there are no files on it. In practice,
 * however, this occurs rarely.
 */
int write_final_iso_if_necessary()
{
	/*@ int ***************************************************** */
	int res;

	/*@ buffers ************************************************** */
	char *tmp;

	malloc_string(tmp);
	assert(bkpinfo != NULL);

// I should really check if there are any slices or tarballs to be copied to CD-R(W)'s; the odds are approx. 1 in a million that there are no files here, so I'll just go ahead & make one more CD anyway

	sprintf(tmp, "Writing the final ISO");
	log_msg(2, tmp);
	center_string(tmp, 80);
#ifndef _XWIN
	if (!g_text_mode) {
		newtPushHelpLine(tmp);
	}
#endif
	res = write_iso_and_go_on(TRUE);
#ifndef _XWIN
	if (!g_text_mode) {
		newtPopHelpLine();
	}
#endif
	log_msg(2, "Returning from writing final ISO (res=%d)", res);
	paranoid_free(tmp);
	return (res);
}


/**
 * Write an ISO image to <tt>[bkpinfo->isodir]/bkpinfo->prefix-[g_current_media_number].iso</tt>.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_media_type
 * - @c prefix
 * - @c isodir
 * - @c manual_cd_tray
 * - @c media_size
 * - @c netfs_remote_dir
 * - @c scratchdir
 * - @c verify_data
 *
 * @param last_cd If TRUE, this is the last CD to write; if FALSE, it's not.
 * @return The number of errors encountered (0 for success)
 * @see make_iso_fs
 */
int write_iso_and_go_on(bool last_cd)
{
	/*@ pointers **************************************************** */
	FILE *fout;

	/*@ buffers ***************************************************** */
	char *tmp;
	char *cdno_fname;
	char *lastcd_fname;
	char *isofile;
	char *mds = NULL;

	/*@ bool ******************************************************** */
	bool that_one_was_ok;
	bool orig_vfy_flag_val;

	/*@ int *********************************************************** */
	int res = 0;

	malloc_string(tmp);
	malloc_string(cdno_fname);
	malloc_string(lastcd_fname);
	malloc_string(isofile);

	assert(bkpinfo != NULL);
	orig_vfy_flag_val = bkpinfo->verify_data;
	if (bkpinfo->media_size <= 0) {
		fatal_error("write_iso_and_go_on() - unknown media size");
	}

	mds = media_descriptor_string(bkpinfo->backup_media_type);
	log_msg(1, "OK, time to make %s #%d", mds, g_current_media_number);
	mr_free(mds);

	/* label the ISO with its number */

	sprintf(cdno_fname, "%s/archives/THIS-CD-NUMBER", bkpinfo->scratchdir);
	fout = fopen(cdno_fname, "w");
	fprintf(fout, "%d", g_current_media_number);
	paranoid_fclose(fout);

	sprintf(tmp, "cp -f %s/autorun %s/", g_mondo_home,
			bkpinfo->scratchdir);
	if (run_program_and_log_output(tmp, FALSE)) {
		log_msg(2, "Warning - unable to copy autorun to scratchdir");
	}

	/* last CD or not? Label accordingly */
	sprintf(lastcd_fname, "%s/archives/NOT-THE-LAST", bkpinfo->scratchdir);
	if (last_cd) {
		unlink(lastcd_fname);
		log_msg(2,
				"OK, you're telling me this is the last CD. Fair enough.");
	} else {
		fout = fopen(lastcd_fname, "w");
		fprintf(fout,
				"You're listening to 90.3 WPLN, Nashville Public Radio.\n");
		paranoid_fclose(fout);
	}
	if (space_occupied_by_cd(bkpinfo->scratchdir) / 1024 > bkpinfo->media_size) {
		sprintf(tmp,
				"Warning! CD is too big. It occupies %ld KB, which is more than the %ld KB allowed.",
				(long) space_occupied_by_cd(bkpinfo->scratchdir),
				(long) bkpinfo->media_size);
		log_to_screen(tmp);
	}
	sprintf(isofile, "%s/%s/%s-%d.iso", bkpinfo->isodir,
			bkpinfo->netfs_remote_dir, bkpinfo->prefix,
			g_current_media_number);
	for (that_one_was_ok = FALSE; !that_one_was_ok;) {
		if (bkpinfo->backup_media_type != usb) {
			res = make_iso_fs(isofile);
		} else {
			res = make_usb_fs();
		}
		if (g_current_media_number == 1 && !res
			&& (bkpinfo->backup_media_type == cdr
				|| bkpinfo->backup_media_type == cdrw)) {
			if (find_cdrom_device(tmp, FALSE))	// make sure find_cdrom_device() finds, records CD-R's loc
			{
				log_msg(3, "*Sigh* Mike, I hate your computer.");
				bkpinfo->manual_cd_tray = TRUE;
			}					// if it can't be found then force pausing
			else {
				log_msg(3, "Great. Found Mike's CD-ROM drive.");
			}
		}
		if (bkpinfo->verify_data && !res) {
			mds = media_descriptor_string(g_backup_media_type);
			log_to_screen
				("Please reboot from the 1st %s in Compare Mode, as a precaution.", mds);
			mr_free(mds);
			if (chdir("/")) {
				// FIXME
			}
			log_it("Before calling verification of image()");
			if (bkpinfo->backup_media_type == usb) {
				res += verify_usb_image();
			} else {
				res += verify_cd_image();
			}
			log_it("After calling verification of image()");
		}
		if (!res) {
			that_one_was_ok = TRUE;
		} else {
			mds = media_descriptor_string(bkpinfo->backup_media_type);
			sprintf(tmp, "Failed to create %s #%d. Retry?", mds, g_current_media_number);
			mr_free(mds);
			res = ask_me_yes_or_no(tmp);
			if (!res) {
				if (ask_me_yes_or_no("Abort the backup?")) {
					fatal_error("FAILED TO BACKUP");
				} else {
					break;
				}
			} else {
				log_msg(2, "Retrying, at user's request...");
				res = 0;
			}
		}
	}
	g_current_media_number++;
	wipe_archives(bkpinfo->scratchdir);
	sprintf(tmp, "rm -Rf %s/images/*gz %s/images/*data*img",
			bkpinfo->scratchdir, bkpinfo->scratchdir);
	if (system(tmp)) {
		log_msg
			(2,
			 "Error occurred when I tried to delete the redundant IMGs and GZs");
	}

	if (last_cd) {
		log_msg(2, "This was your last media.");
	} else {
		log_msg(2, "Continuing to backup your data...");
	}

	bkpinfo->verify_data = orig_vfy_flag_val;
	paranoid_free(tmp);
	paranoid_free(cdno_fname);
	paranoid_free(lastcd_fname);
	paranoid_free(isofile);
	return (0);
}

/* @} - end of LLarchiveGroup */




/**
 * Verify the user's data.
 * @param bkpinfo The backup information structure. Fields used:
 * - @c backup_data
 * - @c backup_media_type
 * - @c media_device
 * - @c verify_data
 *
 * @return The number of errors encountered (0 for success)
 * @ingroup verifyGroup
 */
int verify_data()
{
	int res = 0, retval = 0, cdno = 0;
	char *tmp = NULL;
	char *mds = NULL;
	long diffs = 0;

	assert(bkpinfo != NULL);
	if (IS_THIS_A_STREAMING_BACKUP(bkpinfo->backup_media_type)) {
		if (chdir("/")) {
			// FIXME
		}
		mvaddstr_and_log_it(g_currentY, 0,
							"Verifying archives against live filesystem");
		if (bkpinfo->backup_media_type == cdstream) {
			strcpy(bkpinfo->media_device, "/dev/cdrom");
		}
		verify_tape_backups();
		mvaddstr_and_log_it(g_currentY++, 74, "Done.");
	} else if (bkpinfo->backup_data)
		//bkpinfo->backup_media_type == cdrw || bkpinfo->backup_media_type == cdr))
	{
		log_msg(2,
				"Not verifying again. Per-CD/ISO verification already carried out.");
		mr_asprintf(tmp, "cat %s/changed.files > %s/changed.files 2> /dev/null",bkpinfo->tmpdir, MONDO_CACHE);
		paranoid_system(tmp);
		mr_free(tmp);
	} else {
		g_current_media_number = cdno;
		if (bkpinfo->backup_media_type != iso) {
			find_cdrom_device(bkpinfo->media_device, FALSE);	// replace 0,0,0 with /dev/cdrom
		}
		if (chdir("/")) {
			// FIXME
		}
		for (cdno = 1; cdno < 99 && bkpinfo->verify_data; cdno++) {
			if (cdno != g_current_media_number) {
				log_msg(2,
						"Warning - had to change g_current_media_number from %d to %d",
						g_current_media_number, cdno);
				g_current_media_number = cdno;
			}
			if (bkpinfo->backup_media_type != iso) {
				insist_on_this_cd_number(cdno);
			}
			res = verify_cd_image();	// sets verify_data to FALSE if it's time to stop verifying
			retval += res;
			if (res) {
				mds = media_descriptor_string(bkpinfo->backup_media_type);
				mr_asprintf(tmp, "Warnings/errors were reported while checking %s #%d", mds, g_current_media_number);
				mr_free(mds);
				log_to_screen(tmp);
				mr_free(tmp);

			}
		}
		mr_asprintf(tmp, "grep 'afio: ' %s | sed 's/afio: //' | grep -vE '^/dev/.*$' >> %s/changed.files", MONDO_LOGFILE, MONDO_CACHE);
		res = system(tmp);
		mr_free(tmp);

		mr_asprintf(tmp, "grep 'star: ' %s | sed 's/star: //' | grep -vE '^/dev/.*$' >> %s/changed.files", MONDO_LOGFILE, MONDO_CACHE);
		res = system(tmp);
		mr_free(tmp);
		run_program_and_log_output("umount " MNT_CDROM, FALSE);
//    if (bkpinfo->backup_media_type != iso && !bkpinfo->please_dont_eject_when_restoring)
		if (!bkpinfo->please_dont_eject) {
			eject_device(bkpinfo->media_device);
		}
	}
	mr_asprintf(tmp, "%s/changed.files", MONDO_CACHE);
	diffs = count_lines_in_file(tmp);
	mr_free(tmp);

	if (diffs > 0) {
		if (retval == 0) {
			retval = (int) (-diffs);
		}
	}
	return (retval);
}


void setenv_mondo_share(void) {

setenv("MONDO_SHARE", MONDO_SHARE, 1);
}
