int main(int argc, char *argv []) {
	if(populate_env_variable(REF_ERROR_CODES_FILE, "L2_ERROR_CODES_FILE")) {

		printf("\nUnable to populate [REF_ERROR_CODES_FILE] variable with corresponding environment variable. Routine will proceed without error handling\n");

	}

	if (argc != 2) {

		if(populate_env_variable(SPTS_BLURB_FILE, "L2_SPTS_BLURB_FILE")) {

			RETURN_FLAG = 1;

		} else {

			print_file(SPTS_BLURB_FILE);

		}

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -1, "Status flag for L2 sptrace routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 1;

	} else {
		// ***********************************************************************
		// Redefine routine input parameters

		int order	                = strtol(argv[1], NULL, 0);	
                
		// ***********************************************************************
		// Open [SPFIND_OUTPUTF_PEAKS_FILE] input file
	
		FILE *inputfile;
	
		if (!check_file_exists(SPFIND_OUTPUTF_PEAKS_FILE)) { 

			inputfile = fopen(SPFIND_OUTPUTF_PEAKS_FILE , "r");

		} else {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -2, "Status flag for L2 sptrace routine", ERROR_CODES_FILE_WRITE_ACCESS);

			return 1;

		}

		// ***********************************************************************
		// Find some [SPFIND_OUTPUTF_PEAKS_FILE] input file details

		char input_string [150];
		
		int row_count = 0;
		while(!feof(inputfile)) {
			memset(input_string, '\0', sizeof(char)*150);
			fgets(input_string, 150, inputfile);
			if (strtol(&input_string[0], NULL, 0) > 0) {		// check the line begins with a positive number (usable)
				row_count++;
			}
		}
		
		rewind(inputfile);
		
		// ***********************************************************************
		// Store [SPFIND_OUTPUTF_PEAKS_FILE] data		
		
		double x_coords[row_count];
		memset(x_coords, 0, sizeof(double)*(row_count));

		double y_coords[row_count];
		memset(y_coords, 0, sizeof(double)*(row_count));

		double coord_x, coord_y;
		int idx = 0;
		while(!feof(inputfile)) {
			memset(input_string, '\0', sizeof(char)*150);
			fgets(input_string, 150, inputfile);	
			if (strtol(&input_string[0], NULL, 0) > 0) {		// check the line begins with a positive number (usable)
				sscanf(input_string, "%lf\t%lf\n", &coord_x, &coord_y);
				x_coords[idx] = coord_x;
				y_coords[idx] = coord_y;
				idx++;
			}
		}
		
		// ***********************************************************************
		// Perform a few checks to ensure the input tracing parameters 
		// are sensible

		if ((order < SPTRACE_VAR_POLYORDER_LO) || (order > SPTRACE_VAR_POLYORDER_HI)) {	// Check [order] is within config limits
			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -3, "Status flag for L2 sptrace routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fclose(inputfile);
			return 1; 
		}
		
		// ***********************************************************************
		// Create [SPTRACE_OUTPUTF_TRACES_FILE] output file and print a few 
		// parameters

		FILE *outputfile;
		outputfile = fopen(SPTRACE_OUTPUTF_TRACES_FILE, FILE_WRITE_ACCESS);

		if (!outputfile) { 
			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -4, "Status flag for L2 sptrace routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fclose(inputfile);
			return 1;
		}

		char timestr [80];
		memset(timestr, '\0', sizeof(char)*80);

		find_time(timestr);

		fprintf(outputfile, "#### %s ####\n\n", SPTRACE_OUTPUTF_TRACES_FILE);
		fprintf(outputfile, "# Lists the trace coefficients and corresponding chi-squareds found using the sptrace program.\n\n");
		fprintf(outputfile, "# Run datetime:\t\t%s\n", timestr);
		fprintf(outputfile, "# Polynomial Order:\t%d\n\n", order);
		
		// ***********************************************************************
		// Fit and store results to [SPTRACE_OUTPUTF_TRACES_FILE] file

		double coeffs[order];
		double this_chi_squared;
		if (calc_least_sq_fit(order, row_count, x_coords, y_coords, coeffs, &this_chi_squared)) {	// reversed [coord_y] and [coord_x] as want to find x = f(y) not y = f(x)
			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -5, "Status flag for L2 frtrace routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fclose(inputfile);
			fclose(outputfile);
			return 1; 
		}	

		int ii;
		for (ii=0; ii<=order; ii++) {
			fprintf(outputfile, SPTRACE_VAR_ACCURACY_COEFFS, coeffs[ii]);
			fprintf(outputfile, "\t");
		}
		fprintf(outputfile, SPTRACE_VAR_ACCURACY_CHISQ, this_chi_squared);
		fprintf(outputfile, "\n");
		fprintf(outputfile, "%d", EOF);

		printf("\nFitting results");
		printf("\n--------------------\n");
		printf("\nχ2:\t\t\t%.2f\n", this_chi_squared);
		
		// ***********************************************************************
		// Perform a few checks to ensure the chi squareds are sensible 

		if ((this_chi_squared < SPTRACE_VAR_CHISQUARED_MIN) || (this_chi_squared > SPTRACE_VAR_CHISQUARED_MAX)) {	// comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function
			RETURN_FLAG = 2;
		}	

		// ***********************************************************************
		// Close [SPFIND_OUTPUTF_PEAKS_FILE] input file and 
		// [SPTRACE_OUTPUTF_TRACES_FILE] output file

		if (fclose(inputfile)) {
			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -6, "Status flag for L2 sptrace routine", ERROR_CODES_FILE_WRITE_ACCESS);
			return 1; 
		}
		
		if (fclose(outputfile)) {
			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -7, "Status flag for L2 sptrace routine", ERROR_CODES_FILE_WRITE_ACCESS);
			return 1; 
		}		
		
		// Write success to [ERROR_CODES_FILE]

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", RETURN_FLAG, "Status flag for L2 sptrace routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 0;

	}

}
示例#2
0
static Bool get_default_install_path(char *file_path, u32 path_type)
{
	FILE *f;
	char *sep;
	char szPath[GF_MAX_PATH];


#ifdef _WIN32_WCE
	TCHAR w_szPath[GF_MAX_PATH];
	GetModuleFileName(NULL, w_szPath, GF_MAX_PATH);
	CE_WideToChar((u16 *) w_szPath, file_path);
#else
	GetModuleFileNameA(NULL, file_path, GF_MAX_PATH);
#endif

	/*remove exe name*/
	if (strstr(file_path, ".exe")) {
		sep = strrchr(file_path, '\\');
		if (sep) sep[0] = 0;
	}

	strcpy(szPath, file_path);
	strlwr(szPath);

	/*if this is run from a browser, we do not get our app path - fortunately on Windows, we always use 'GPAC' in the
	installation path*/
	if (!strstr(file_path, "gpac") && !strstr(file_path, "GPAC") ) {
		HKEY hKey = NULL;
		DWORD dwSize = GF_MAX_PATH;

		/*locate the key in current user, then in local machine*/
#ifdef _WIN32_WCE
		DWORD dwType = REG_SZ;
		u16 w_path[1024];
		RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\GPAC"), 0, KEY_READ, &hKey);
#ifdef _DEBUG
		if (RegQueryValueEx(hKey, TEXT("DebugDir"), 0, &dwType, (LPBYTE) w_path, &dwSize) != ERROR_SUCCESS)
#endif
			RegQueryValueEx(hKey, TEXT("InstallDir"), 0, &dwType, (LPBYTE) w_path, &dwSize);
		CE_WideToChar(w_path, (char *)file_path);
		RegCloseKey(hKey);
#else
		if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\GPAC", 0, KEY_READ, &hKey) != ERROR_SUCCESS)
			RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\GPAC", 0, KEY_READ, &hKey);

		dwSize = GF_MAX_PATH;

#ifdef _DEBUG
		if (RegQueryValueEx(hKey, "DebugDir", NULL, NULL,(unsigned char*) file_path, &dwSize) != ERROR_SUCCESS)
#endif
			RegQueryValueEx(hKey, "InstallDir", NULL, NULL,(unsigned char*) file_path, &dwSize);

		RegCloseKey(hKey);
#endif
	}


	if (path_type==GF_PATH_APP) return GF_TRUE;

	if (path_type==GF_PATH_GUI) {
		char *sep;
		strcat(file_path, "\\gui");
		if (check_file_exists("gui.bt", file_path, file_path)) return GF_TRUE;
		sep = strstr(file_path, "\\bin\\");
		if (sep) {
			sep[0] = 0;
			strcat(file_path, "\\gui");
			if (check_file_exists("gui.bt", file_path, file_path)) return GF_TRUE;
		}
		return GF_FALSE;
	}
	/*modules are stored in the GPAC directory (should be changed to GPAC/modules)*/
	if (path_type==GF_PATH_MODULES) return GF_TRUE;

	/*we are looking for the config file path - make sure it is writable*/
	assert(path_type == GF_PATH_CFG);

	strcpy(szPath, file_path);
	strcat(szPath, "\\gpaccfgtest.txt");
	//do not use gf_fopen here, we don't want to through any error if failure
	f = fopen(szPath, "wb");
	if (f != NULL) {
		fclose(f);
		gf_delete_file(szPath);
		return GF_TRUE;
	}
#ifdef _WIN32_WCE
	return 0;
#else
	/*no write access, get user home directory*/
	SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, file_path);
	if (file_path[strlen(file_path)-1] != '\\') strcat(file_path, "\\");
	strcat(file_path, "GPAC");
	/*create GPAC dir*/
	_mkdir(file_path);
	strcpy(szPath, file_path);
	strcat(szPath, "\\gpaccfgtest.txt");
	f = fopen(szPath, "wb");
	/*COMPLETE FAILURE*/
	if (!f) return GF_FALSE;

	fclose(f);
	gf_delete_file(szPath);
	return GF_TRUE;
#endif
}
示例#3
0
static Bool get_default_install_path(char *file_path, u32 path_type)
{
	char app_path[GF_MAX_PATH];
	char *sep;
	u32 size = GF_MAX_PATH;

	/*on OSX, Linux & co, user home is where we store the cfg file*/
	if (path_type==GF_PATH_CFG) {
		char *user_home = getenv("HOME");
#ifdef GPAC_IPHONE
		char buf[PATH_MAX];
		char *res;
#endif
		if (!user_home) return 0;
#ifdef GPAC_IPHONE
		res = realpath(user_home, buf);
		if (res) {
            strcpy(file_path, buf);
            strcat(file_path, "/Documents");
		} else
#endif
			strcpy(file_path, user_home);

		if (file_path[strlen(file_path)-1] == '/') file_path[strlen(file_path)-1] = 0;

		//cleanup of old install in .gpacrc
		if (check_file_exists(".gpacrc", file_path, file_path)) {
			strcpy(app_path, file_path);
			strcat(app_path, "/.gpacrc");
			gf_delete_file(app_path);
		}

		strcat(file_path, "/.gpac");
		if (!gf_dir_exists(file_path)) {
			gf_mkdir(file_path);
		}
		return 1;
	}

	if (path_type==GF_PATH_APP) {
#if (defined(__DARWIN__) || defined(__APPLE__) )
		if (_NSGetExecutablePath(app_path, &size) ==0) {
			realpath(app_path, file_path);
			char *sep = strrchr(file_path, '/');
			if (sep) sep[0] = 0;
			return 1;
		}

#elif defined(GPAC_CONFIG_LINUX)
		size = readlink("/proc/self/exe", file_path, GF_MAX_PATH);
		if (size>0) {
			char *sep = strrchr(file_path, '/');
			if (sep) sep[0] = 0;
			return 1;
		}
#endif
		return 0;
	}


	/*locate the app*/
	if (!get_default_install_path(app_path, GF_PATH_APP)) return 0;

	/*installed or symlink on system, user user home directory*/
	if (!strnicmp(app_path, "/usr/", 5) || !strnicmp(app_path, "/opt/", 5)) {
		if (path_type==GF_PATH_GUI) {
			/*look in possible install dirs ...*/
			if (check_file_exists("gui.bt", "/usr/share/gpac/gui", file_path)) return 1;
			if (check_file_exists("gui.bt", "/usr/local/share/gpac/gui", file_path)) return 1;
			if (check_file_exists("gui.bt", "/opt/share/gpac/gui", file_path)) return 1;
			if (check_file_exists("gui.bt", "/opt/local/share/gpac/gui", file_path)) return 1;
		} else if (path_type==GF_PATH_MODULES) {
			/*look in possible install dirs ...*/
			if (check_file_exists(TEST_MODULE, "/usr/lib/gpac", file_path)) return 1;
			if (check_file_exists(TEST_MODULE, "/usr/local/lib/gpac", file_path)) return 1;
			if (check_file_exists(TEST_MODULE, "/opt/lib/gpac", file_path)) return 1;
			if (check_file_exists(TEST_MODULE, "/opt/local/lib/gpac", file_path)) return 1;
			if (check_file_exists(TEST_MODULE, "/usr/lib/x86_64-linux-gnu/gpac", file_path)) return 1;
			if (check_file_exists(TEST_MODULE, "/usr/lib/i386-linux-gnu/gpac", file_path)) return 1;
		}
	}

	if (path_type==GF_PATH_GUI) {
		if (get_default_install_path(app_path, GF_PATH_CFG)) {
			/*GUI not found, look in ~/.gpac/gui/ */
			strcat(app_path, "/.gpac/gui");
			if (check_file_exists("gui.bt", app_path, file_path)) return 1;
		}

		/*GUI not found, look in gpac distribution if any */
		if (get_default_install_path(app_path, GF_PATH_APP)) {
			char *sep = strstr(app_path, "/bin/gcc");
			if (!sep) sep = strstr(app_path, "/bin/osx");
			if (sep) {
				sep[0] = 0;
				strcat(app_path, "/gui");
				if (check_file_exists("gui.bt", app_path, file_path)) return 1;
			}
		}
		/*GUI not found, look in .app for OSX case*/
	}

	if (path_type==GF_PATH_MODULES) {
		/*look in gpac compilation tree (modules are output in the same folder as apps) */
		if (get_default_install_path(app_path, GF_PATH_APP)) {
			if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1;
			/*on OSX check modules subdirectory */
			strcat(app_path, "/modules");
			if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1;
		}
		/*modules not found, look in ~/.gpac/modules/ */
		if (get_default_install_path(app_path, GF_PATH_CFG)) {
			strcpy(app_path, file_path);
			strcat(app_path, "/.gpac/modules");
			if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1;
		}
		/*modules not found, failure*/
		return 0;
	}

	/*OSX way vs iPhone*/
	sep = strstr(app_path, ".app/");
	if (sep) sep[4] = 0;

	/*we are looking for .app install path, or GUI */
	if (path_type==GF_PATH_GUI) {
#ifndef GPAC_IPHONE
		strcat(app_path, "/Contents/MacOS/gui");
		if (check_file_exists("gui.bt", app_path, file_path)) return 1;
#else /*iOS: for now, everything is set flat within the package*/
		/*iOS app is distributed with embedded GUI*/
		get_default_install_path(app_path, GF_PATH_APP);
		strcat(app_path, "/gui");
		if (check_file_exists("gui.bt", app_path, file_path)) return 1;
#endif
	}
	else { // (path_type==GF_PATH_MODULES)
		strcat(app_path, "/Contents/MacOS/modules");
		if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1;
	}
	/*not found ...*/
	return 0;
}
示例#4
0
int rtp_worker_create(int sockfd, struct sockaddr_storage *rtsp_socket) {
    int ret;
    RTSP_TO_RTP message;
    RTP_TO_RTSP response;
    RTP_WORKER *worker;
    struct msg_to_worker msg;
    char *host, *path;
    int st;
    pid_t child;
    int i;
    unsigned int *ssrc;
    /* TODO */
    ret = recv(sockfd, &message, sizeof(RTSP_TO_RTP), MSG_WAITALL);
    if (ret != sizeof(RTSP_TO_RTP))
        return -1;
    switch (message.order) {
    case CHECK_EXISTS_RTP:
        /* Extract path from uri */
        st = extract_uri(message.uri, &host, &path);
        if (st &&  host && path) {
            /* Check if the path exists in the computer */
            /* Ignore last /audio or /video */
            path[strlen(path)-6] = 0;
            st = check_file_exists(path);
            if (st)
                response.order = OK_RTP;
            else
                response.order = ERR_RTP;
        } else {
            response.order = ERR_RTP;
        }
        free(host);
        free(path);
        ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
        break;
    case SETUP_RTP_UNICAST:
        /* Extract the path */
        st = extract_uri(message.uri, &host, &path);
        if (!st || !host || !path) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            return(0);
        }
        /* Check if the file exists */
        /* Ignore last /audio or /video */
        path[strlen(path)-6] = 0;
        st = check_file_exists(path);
        if (!st) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            free(host);
            free(path);
            return(0);
        }
        free(host);
        free(path);

        /* Create worker process */
        child = fork();
        if (child == 0) {
            rtp_worker_fun();
        } else if (child < 0) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            return(0);
        }

        pthread_mutex_lock(&workers_mutex);
        /* Check if we can have more workers */
        if (n_workers == MAX_RTP_WORKERS) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            kill(child, SIGKILL);
            waitpid(child, 0, 0);
            return(0);
        }
        /* Search for a free worker */
        for (i = 0; i < MAX_RTP_WORKERS; ++i)
            if (workers[i]->used == 0)
                break;
        /* Intialize RTP_WORKER structure */
        workers[i]->used = 1;
        workers[i]->pid = child;
        /* Create new ssrc */
        do {
            workers[i]->ssrc = rand();
        } while (gethashtable(&workers_hash, &(workers[i]->ssrc)));

        /* Reserve memory for worker */
        worker = malloc(sizeof(RTP_WORKER));
        if (!worker) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            kill(child, SIGKILL);
            waitpid(child, 0, 0);
            return(0);
        }
        /* Initialize worker */
        worker->pid = child;
        /* Insert worker in workers hash */
        ssrc = malloc(sizeof(unsigned int));
        if (!ssrc) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            kill(child, SIGKILL);
            waitpid(child, 0, 0);
            return(0);
        }
        *ssrc = workers[i]->ssrc;
        st = puthashtable(&workers_hash, ssrc, worker);
        if (st) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            kill(child, SIGKILL);
            waitpid(child, 0, 0);
            return(0);
        }
        /* Insert the ssrc in the message */
        message.ssrc = workers[i]->ssrc;

        pthread_mutex_unlock(&workers_mutex);

    /* Fall to default */
    default:
        pthread_mutex_lock(&workers_mutex);
        /* Get the worker pid from the ssrc we got in the message */
        worker = gethashtable(&workers_hash, &(message.ssrc));
        if (!worker) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            return(0);
        }

        /* Create message for worker */
        msg.mtype = worker->pid;
        msg.sockfd = sockfd;
        memcpy(&(msg.message), &message, sizeof(RTSP_TO_RTP));
        memcpy(&(msg.rtsp_socket), rtsp_socket, sizeof(struct sockaddr_storage));

        /* Send to the message to the worker */
        st = msgsnd(msg_queue, &msg, sizeof(struct msg_to_worker) - sizeof(long), 0);
        if (st == -1) {
            response.order = ERR_RTP;
            ret = send(sockfd, &response, sizeof(RTP_TO_RTSP), 0);
            return(0);
        }

        pthread_mutex_unlock(&workers_mutex);
        /* Now the worker must get the message and communicate with the RTSP server. */
        break;
    }
    return(1);
}
示例#5
0
文件: minizip.c 项目: wangkan/pgn
int main(int argc, char *argv[])
{
    zipFile zf = NULL;
#ifdef USEWIN32IOAPI
    zlib_filefunc64_def ffunc = {0};
#endif
    char *zipfilename = NULL;
    const char* password = NULL;
    void* buf = NULL;
    int size_buf = WRITEBUFFERSIZE;
    int zipfilenamearg = 0;
    int errclose = 0;
    int err = 0;
    int i = 0;
    int opt_overwrite = APPEND_STATUS_CREATE;
    int opt_compress_level = Z_DEFAULT_COMPRESSION;
    int opt_exclude_path = 0;

    do_banner();
    if (argc == 1)
    {
        do_help();
        return 0;
    }

    /* Parse command line options */
    for (i = 1; i < argc; i++)
    {
        if ((*argv[i]) == '-')
        {
            const char *p = argv[i]+1;

            while ((*p) != '\0')
            {
                char c = *(p++);;
                if ((c == 'o') || (c == 'O'))
                    opt_overwrite = APPEND_STATUS_CREATEAFTER;
                if ((c == 'a') || (c == 'A'))
                    opt_overwrite = APPEND_STATUS_ADDINZIP;
                if ((c >= '0') && (c <= '9'))
                    opt_compress_level = (c - '0');
                if ((c == 'j') || (c == 'J'))
                    opt_exclude_path = 1;

                if (((c == 'p') || (c == 'P')) && (i+1 < argc))
                {
                    password=argv[i+1];
                    i++;
                }
            }
        }
        else
        {
            if (zipfilenamearg == 0)
                zipfilenamearg = i;
        }
    }

    if (zipfilenamearg == 0)
    {
        do_help();
        return 0;
    }
    zipfilename = argv[zipfilenamearg];

    buf = (void*)malloc(size_buf);
    if (buf == NULL)
    {
        printf("Error allocating memory\n");
        return ZIP_INTERNALERROR;
    }

    if (opt_overwrite == 2)
    {
        /* If the file don't exist, we not append file */
        if (check_file_exists(zipfilename) == 0)
            opt_overwrite = 1;
    }
    else if (opt_overwrite == 0)
    {
        /* If ask the user what to do because append and overwrite args not set */
        //if (check_file_exists(zipfilename) != 0)
        //{
        //    char rep = 0;
        //    do
        //    {
        //        char answer[128];
        //        printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ", zipfilename);
        //        if (scanf("%1s", answer) != 1)
        //            exit(EXIT_FAILURE);
        //        rep = answer[0];

        //        if ((rep >= 'a') && (rep <= 'z'))
        //            rep -= 0x20;
        //    }
        //    while ((rep != 'Y') && (rep != 'N') && (rep != 'A'));

        //    if (rep == 'A')
        //        opt_overwrite = 2;
        //    else if (rep == 'N')
        //    {
        //        do_help();
        //        free(buf);
        //        return 0;
        //    }
        //}
    }

#ifdef USEWIN32IOAPI
    fill_win32_filefunc64A(&ffunc);
    zf = zipOpen2_64(zipfilename, opt_overwrite, NULL, &ffunc);
#else
    zf = zipOpen64(zipfilename, opt_overwrite);
#endif

    if (zf == NULL)
    {
        printf("error opening %s\n", zipfilename);
        err = ZIP_ERRNO;
    }
    else
        printf("creating %s\n", zipfilename);

    /* Go through command line args looking for files to add to zip */
    for (i = zipfilenamearg + 1; (i < argc) && (err == ZIP_OK); i++)
    {
        FILE *fin = NULL;
        int size_read = 0;
        const char* filenameinzip = argv[i];
        const char *savefilenameinzip;
        zip_fileinfo zi = {0};
        unsigned long crcFile = 0;
        int zip64 = 0;

        /* Skip command line options */
        if ((((*(argv[i])) == '-') || ((*(argv[i])) == '/')) && (strlen(argv[i]) == 2) &&
            ((argv[i][1] == 'o') || (argv[i][1] == 'O') || (argv[i][1] == 'a') || (argv[i][1] == 'A') ||
             (argv[i][1] == 'p') || (argv[i][1] == 'P') || ((argv[i][1] >= '0') && (argv[i][1] <= '9'))))
            continue;

        /* Get information about the file on disk so we can store it in zip */
        filetime(filenameinzip, &zi.tmz_date, &zi.dosDate);

        if ((password != NULL) && (err == ZIP_OK))
            err = get_file_crc(filenameinzip, buf, size_buf, &crcFile);

        zip64 = is_large_file(filenameinzip);

        /* Construct the filename that our file will be stored in the zip as.
           The path name saved, should not include a leading slash.
           If it did, windows/xp and dynazip couldn't read the zip file. */

        savefilenameinzip = filenameinzip;
        while (savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/')
            savefilenameinzip++;

        /* Should the file be stored with any path info at all? */
        if (opt_exclude_path)
        {
            const char *tmpptr = NULL;
            const char *lastslash = 0;

            for (tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
            {
                if (*tmpptr == '\\' || *tmpptr == '/')
                    lastslash = tmpptr;
            }

            if (lastslash != NULL)
                savefilenameinzip = lastslash + 1; /* base filename follows last slash. */
        }

        /* Add to zip file */
        err = zipOpenNewFileInZip3_64(zf, savefilenameinzip, &zi,
                    NULL, 0, NULL, 0, NULL /* comment*/,
                    (opt_compress_level != 0) ? Z_DEFLATED : 0,
                    opt_compress_level,0,
                    -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                    password, crcFile, zip64);

        if (err != ZIP_OK)
            printf("error in opening %s in zipfile (%d)\n", filenameinzip, err);
        else
        {
            fin = FOPEN_FUNC(filenameinzip, "rb");
            if (fin == NULL)
            {
                err = ZIP_ERRNO;
                printf("error in opening %s for reading\n", filenameinzip);
            }
        }

        if (err == ZIP_OK)
        {
            /* Read contents of file and write it to zip */
            do
            {
                size_read = (int)fread(buf, 1, size_buf, fin);
                if ((size_read < size_buf) && (feof(fin) == 0))
                {
                    printf("error in reading %s\n",filenameinzip);
                    err = ZIP_ERRNO;
                }

                if (size_read > 0)
                {
                    err = zipWriteInFileInZip(zf, buf, size_read);
                    if (err < 0)
                        printf("error in writing %s in the zipfile (%d)\n", filenameinzip, err);
                }
            }
            while ((err == ZIP_OK) && (size_read > 0));
        }

        if (fin)
            fclose(fin);

        if (err < 0)
            err = ZIP_ERRNO;
        else
        {
            err = zipCloseFileInZip(zf);
            if (err != ZIP_OK)
                printf("error in closing %s in the zipfile (%d)\n", filenameinzip, err);
        }
    }

    errclose = zipClose(zf, NULL);
    if (errclose != ZIP_OK)
        printf("error in closing %s (%d)\n", zipfilename, errclose);

    free(buf);
    return err;
}
int main (int argc, char *argv []) {

	if(populate_env_variable(REF_ERROR_CODES_FILE, "L2_ERROR_CODES_FILE")) {

		printf("\nUnable to populate [REF_ERROR_CODES_FILE] variable with corresponding environment variable. Routine will proceed without error handling\n");

	}

	if (argc != 8) {

		if(populate_env_variable(LOR_BLURB_FILE, "L2_LOR_BLURB_FILE")) {

			RETURN_FLAG = 1;

		} else {

			print_file(LOR_BLURB_FILE);

		}

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -1, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 1;

	} else {

		// ***********************************************************************
		// Redefine routine input parameters
	
		char *input_f	                = strdup(argv[1]);
		double start_wav		= strtod(argv[2], NULL);
		double end_wav			= strtod(argv[3], NULL);
		char *interpolation_type	= strdup(argv[4]);
		double dispersion		= strtod(argv[5], NULL);
		int conserve_flux		= strtol(argv[6], NULL, 0);
		char *output_f	                = strdup(argv[7]);

		// ***********************************************************************
		// Open input file (ARG 1), get parameters and perform any data format 
                // checks 

		fitsfile *input_f_ptr;

		int input_f_maxdim = 2;
		int input_f_status = 0, input_f_bitpix, input_f_naxis;
		long input_f_naxes [2] = {1,1};

		if(!fits_open_file(&input_f_ptr, input_f, READONLY, &input_f_status)) {

			if(!populate_img_parameters(input_f, input_f_ptr, input_f_maxdim, &input_f_bitpix, &input_f_naxis, input_f_naxes, &input_f_status, "INPUT FRAME")) {

				if (input_f_naxis != 2) {	// any data format checks here

					write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -2, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

					free(input_f);
					free(interpolation_type);
					free(output_f);

					if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

					return 1;
	
				}

			} else { 

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -3, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, input_f_status); 

				free(input_f);
				free(interpolation_type);
				free(output_f);

				if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

				return 1; 

			}

		} else { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -4, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error(stdout, input_f_status); 

			free(input_f);
			free(interpolation_type);
			free(output_f);

			return 1; 

		}

		// ***********************************************************************
		// Set the range limits using input fits file (ARG 1)

		int cut_x [2] = {1, input_f_naxes[0]};
		int cut_y [2] = {1, input_f_naxes[1]};

		// ***********************************************************************
		// Set parameters used when reading data from input fits file (ARG 1)

		long fpixel [2] = {cut_x[0], cut_y[0]};
		long nxelements = (cut_x[1] - cut_x[0]) + 1;
		long nyelements = (cut_y[1] - cut_y[0]) + 1;

		// ***********************************************************************
		// Create arrays to store pixel values from input fits file (ARG 1)

		double input_f_pixels [nxelements];

		// ***********************************************************************
		// Open [LOARCFIT_OUTPUTF_WAVFITS_FILE] dispersion solutions file

		FILE *dispersion_solutions_f;
	
		if (!check_file_exists(LOARCFIT_OUTPUTF_WAVFITS_FILE)) { 

			dispersion_solutions_f = fopen(LOARCFIT_OUTPUTF_WAVFITS_FILE , "r");

		} else {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -5, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(input_f);
			free(interpolation_type);
			free(output_f);

			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1;

		}	

		// ***********************************************************************
		// Find some [LOARCFIT_OUTPUTF_WAVFITS_FILE] file details

		char input_string [500];

		bool find_polynomialorder_comment = FALSE;

		int polynomial_order;	

		char search_string_1 [20] = "# Polynomial Order:\0";	// this is the comment to be found from the [LOARCFIT_OUTPUTF_WAVFITS_FILE] file

		while(!feof(dispersion_solutions_f)) {

			memset(input_string, '\0', sizeof(char)*500);
	
			fgets(input_string, 500, dispersion_solutions_f);	

			if (strncmp(input_string, search_string_1, strlen(search_string_1)) == 0) { 

				sscanf(input_string, "%*[^\t]%d", &polynomial_order);		// read all data up to tab as string ([^\t]), but do not store (*)
				find_polynomialorder_comment = TRUE;
				break;


			} 

		}

		if (find_polynomialorder_comment == FALSE) {	// error check - didn't find the comment in the [LOARCFIT_OUTPUTF_WAVFITS_FILE] file

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -6, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(input_f);
			free(interpolation_type);
			free(output_f);

			fclose(dispersion_solutions_f);

			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1;

		}

		// ***********************************************************************
		// Rewind and extract coefficients from [LOARCFIT_OUTPUTF_WAVFITS_FILE]
		// file 

		rewind(dispersion_solutions_f);

		int token_index;	// this variable will hold which token we're dealing with
		int coeff_index;	// this variable will hold which coefficient we're dealing with
		double this_coeff;
		double this_chisquared;
	
		char *token;

		double coeffs [polynomial_order+1];
		memset(coeffs, 0, sizeof(double)*(polynomial_order+1));

		while(!feof(dispersion_solutions_f)) {

			memset(input_string, '\0', sizeof(char)*500);
	
			fgets(input_string, 500, dispersion_solutions_f);

			token_index = 0;
			coeff_index = 0;

			if (strtol(&input_string[0], NULL, 0) > 0) { 		// check the line begins with a positive number

				// ***********************************************************************
				// String tokenisation loop: 
				//
				// 1. init calls strtok() loading the function with input_string
				// 2. terminate when token is null
				// 3. we keep assigning tokens of input_string to token until termination by calling strtok with a NULL first argument
				// 
				// n.b. searching for tab or newline separators ('\t' and '\n')

				for (token=strtok(input_string, "\t\n"); token !=NULL; token = strtok(NULL, "\t\n")) {
                                  
                                        if (token_index == 0) {    
                                        } else if ((token_index >= 1) && (token_index <= polynomial_order+1)) { 	// coeff token

						this_coeff = strtod(token, NULL);
						// printf("%d\t%e\n", coeff_index, this_coeff);		// DEBUG
						coeffs[coeff_index] = this_coeff;
						coeff_index++;

					} else if (token_index == polynomial_order+2) {					// chisquared token

						this_chisquared = strtod(token, NULL);
                                                //printf("%f\n", this_chisquared);                      // DEBUG

					}

					token_index++;

				}

			}

		}

		// ***********************************************************************
		// Find wavelength extremities from [LOARCFIT_OUTPUTF_WAVFITS_FILE] file
		// and ensure the input constraints [start_wav] (ARG 2) and [end_wav]
		// (ARG 3) don't lie outside these boundaries

		double smallest_wav, largest_wav;

		int ii;

		for (ii=0; ii<=polynomial_order; ii++) {
		    
			smallest_wav += coeffs[ii]*pow(0+INDEXING_CORRECTION, ii);
			largest_wav += coeffs[ii]*pow((cut_x[1]-1)+INDEXING_CORRECTION, ii);

		}

		// ***********************************************************************
	        // Need to find pixel indexes for starting/ending wavelength positions

	        double this_element_wav;
	        int first_element_index, last_element_index;
                int jj;
		for (ii=0; ii<nxelements; ii++) {
                        this_element_wav = 0.0;
                        for (jj=0; jj<=polynomial_order; jj++) {
                                this_element_wav += coeffs[jj]*pow(ii,jj);
                        }
		      	if (this_element_wav >= start_wav) {	// the current index, ii, represents the first pixel with a wavelength >= start_wav. Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function
		       		break;
		     	}
		     	
                        first_element_index = ii;		     	
                }

		// printf("%d\t%f\n", ii, this_element_wav);	// DEBUG

		for (ii=nxelements; ii>=0; ii--) {
                        this_element_wav = 0.0;
                        for (jj=0; jj<=polynomial_order; jj++) {
                                this_element_wav += coeffs[jj]*pow(ii,jj);
                        }
                        if (this_element_wav <= end_wav) {    // the current index, ii, represents the first pixel with a wavelength <= end_wav. Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function
                                break;
                        }

			last_element_index = ii;

	        }
	        
	        // printf("%d\t%f\n", ii, this_element_wav);     // DEBUG
	
		printf("\nWavelength boundaries");
		printf("\n---------------------\n");

		printf("\nInherent minimum wavelength:\t%.2f Å", smallest_wav);
		printf("\nInherent maximum wavelength:\t%.2f Å\n", largest_wav);

		if (start_wav < smallest_wav) {         // Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function
		  
			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -7, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(input_f);
			free(interpolation_type);
			free(output_f);

			fclose(dispersion_solutions_f);

			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1; 

		} else if (end_wav > largest_wav) {     // Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -8, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(input_f);
			free(interpolation_type);
			free(output_f);

			fclose(dispersion_solutions_f);

			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1; 

		}

		// ***********************************************************************
	        // Set the bin wavelengths 

		int num_bins = 0;

		if (!gsl_fcmp((end_wav-start_wav)/dispersion, rint((end_wav-start_wav)/dispersion), 1e-5)) {	// check to see if nearest integer is within tolerance value	

			num_bins = rint((end_wav-start_wav)/dispersion) + 1;					// if TRUE, round

		} else {

			num_bins = floor((end_wav-start_wav)/dispersion) + 1;					// if FALSE, floor

		}

		// printf("%d\n", num_bins);						// DEBUG

		double bin_wavelengths [num_bins];
		memset(bin_wavelengths, 0, sizeof(double)*num_bins);

		for (ii=0; ii<num_bins; ii++) {

			bin_wavelengths[ii] = start_wav + dispersion*ii;		
			// printf("%f\n", bin_wavelengths[ii]);				// DEBUG
		
		}	

		// printf("%f\t%f\n", bin_wavelengths[0], bin_wavelengths[num_bins-1]);	// DEBUG


		// REBIN INPUT FRAME (ARG 1) AND CONSERVE FLUX IF APPLICABLE
		// ***********************************************************************
		// 1.	Open input frame

		int this_row_index;

		double x_wav [nxelements];

		double output_frame_values [nyelements][num_bins];
		memset(output_frame_values, 0, sizeof(double)*nyelements*num_bins);

		double output_f_pixels [num_bins];
		memset(output_f_pixels, 0, sizeof(double)*(num_bins));

		double this_pre_rebin_row_flux, this_post_rebin_row_flux;

		double conservation_factor;	

		for (fpixel[1] = cut_y[0]; fpixel[1] <= cut_y[1]; fpixel[1]++) {

			this_row_index = fpixel[1] - 1;

			memset(input_f_pixels, 0, sizeof(double)*nxelements);

			if(!fits_read_pix(input_f_ptr, IMG_READ_ACCURACY, fpixel, nxelements, NULL, input_f_pixels, NULL, &input_f_status)) {

				// 2.	Calculate pre-rebin total fluxes

				this_pre_rebin_row_flux = 0.0;

				for (ii=first_element_index; ii<=last_element_index; ii++) {

					this_pre_rebin_row_flux += input_f_pixels[ii];

				}

				// 3.	Create pixel-wavelength translation array and perform interpolation

				memset(x_wav, 0, sizeof(double)*nxelements);

				for (ii=0; ii<nxelements; ii++) {

					for (jj=0; jj<=polynomial_order; jj++) {
					    
						x_wav[ii] += coeffs[jj]*pow(ii+INDEXING_CORRECTION,jj);

					}

					// printf("%d\t%f\n", ii, x_wav[ii]); // DEBUG

				}

				// for (ii=0; ii< nxelements; ii++) printf("\n%f\t%f", x_wav[ii], input_f_pixels[ii]);	// DEBUG

				if (interpolate(interpolation_type, x_wav, input_f_pixels, nxelements, bin_wavelengths[0], bin_wavelengths[num_bins-1], dispersion, output_f_pixels)) {
		
					write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -9, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

					free(input_f);
					free(interpolation_type);
					free(output_f);

					fclose(dispersion_solutions_f);

					if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

					return 1; 

				}

				// 4.	Calculate post-rebin total fluxes

				this_post_rebin_row_flux = 0.0;

				for (ii=0; ii<num_bins; ii++) {

					this_post_rebin_row_flux += output_f_pixels[ii];

				}

				// 5.	Conserve flux if applicable

				conservation_factor = this_pre_rebin_row_flux/this_post_rebin_row_flux;

				// printf("%f\t%f\t%f\n", this_pre_rebin_row_flux, this_post_rebin_row_flux, conservation_factor);	// DEBUG

				for (ii=0; ii<num_bins; ii++) {

					if (conserve_flux == TRUE) {

						output_frame_values[this_row_index][ii] = output_f_pixels[ii]*conservation_factor;

					} else {

						output_frame_values[this_row_index][ii] = output_f_pixels[ii];

					}

				}

			} else { 

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -10, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, input_f_status);

				free(input_f);
				free(interpolation_type);
				free(output_f);

				fclose(dispersion_solutions_f);

				if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

				return 1; 

			}

		}

		// 6.	Create [LOREBIN_OUTPUTF_REBIN_WAVFITS_FILE] output file and print
		// 	a few parameters

		FILE *outputfile;
		outputfile = fopen(LOREBIN_OUTPUTF_REBIN_WAVFITS_FILE, FILE_WRITE_ACCESS);

		if (!outputfile) { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -11, "Status flag for L2 frrebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(input_f);
			free(interpolation_type);
			free(output_f);

			fclose(dispersion_solutions_f);

			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1;

		}

		char timestr [80];
		memset(timestr, '\0', sizeof(char)*80);

		find_time(timestr);

		fprintf(outputfile, "#### %s ####\n\n", LOREBIN_OUTPUTF_REBIN_WAVFITS_FILE);
	        fprintf(outputfile, "# Rebinning wavelength fit parameters.\n\n");
                fprintf(outputfile, "# Run Datetime:\t\t%s\n\n", timestr);
	        fprintf(outputfile, "# Target Filename:\t%s\n\n", input_f);
	        fprintf(outputfile, "# Starting Wavelength:\t%.2f\n", bin_wavelengths[0]);
	        fprintf(outputfile, "# Dispersion:\t\t%.2f\n", dispersion);
		fprintf(outputfile, "%d", EOF);

		// 7.	Write these values to the [ADDITIONAL_KEYS_FILE] file

		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CTYPE1", "Wavelength", "Type of co-ordinate on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CUNIT1", "Angstroms", "Units for axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRVAL1", bin_wavelengths[0], "[pixel] Value at ref. pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CDELT1", dispersion, "[pixel] Pixel scale on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRPIX1", 1.0, "[pixel] Reference pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CTYPE2", "a2", "Type of co-ordinate on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CUNIT2", "Pixels", "Units for axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRVAL2", 1, "[pixel] Value at ref. pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CDELT2", 1, "[pixel] Pixel scale on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRPIX2", 1, "[pixel] Reference pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);

		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CTYPE1", "Wavelength", "Type of co-ordinate on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CUNIT1", "Angstroms", "Units for axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRVAL1", bin_wavelengths[0], "[pixel] Value at ref. pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CDELT1", dispersion, "[pixel] Pixel scale on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRPIX1", 1.0, "[pixel] Reference pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CTYPE2", "a2", "Type of co-ordinate on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CUNIT2", "Pixels", "Units for axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRVAL2", 1, "[pixel] Value at ref. pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CDELT2", 1, "[pixel] Pixel scale on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);
		write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRPIX2", 1, "[pixel] Reference pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS);

		// ***********************************************************************
		// Set output frame parameters

		fitsfile *output_f_ptr;
	
		int output_f_status = 0;
		long output_f_naxes [2] = {num_bins,nyelements};
	
		long output_f_fpixel = 1;

		// ***********************************************************************
		// Create [output_frame_values_1D] array to hold the output data in the 
                // correct format

		double output_frame_values_1D [num_bins*nyelements];
		memset(output_frame_values_1D, 0, sizeof(double)*num_bins*nyelements);
                int kk;
		for (ii=0; ii<nyelements; ii++) {
	
			jj = ii * num_bins;
	
			for (kk=0; kk<num_bins; kk++) {
	
				output_frame_values_1D[jj] = output_frame_values[ii][kk];
				jj++;

			}
		
		}

		// ***********************************************************************
		// Create and write [output_frame_values_1D] to output file (ARG 5)	
	
		if (!fits_create_file(&output_f_ptr, output_f, &output_f_status)) {
	
			if (!fits_create_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[0], 2, output_f_naxes, &output_f_status)) {

				if (!fits_write_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[1], output_f_fpixel, num_bins * nyelements, output_frame_values_1D, &output_f_status)) {

				} else { 

					write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -12, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
					fits_report_error(stdout, output_f_status); 

					free(input_f);
					free(interpolation_type);
					free(output_f);

					fclose(dispersion_solutions_f);
					fclose(outputfile);

					if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
					if(fits_close_file(output_f_ptr, &output_f_status)); 

					return 1; 

				}

			} else {

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -13, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, output_f_status); 

				free(input_f);
				free(interpolation_type);
				free(output_f);

				fclose(dispersion_solutions_f);
				fclose(outputfile);

                                if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                                if(fits_close_file(output_f_ptr, &output_f_status)); 

				return 1; 

			}

		} else {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -14, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error(stdout, output_f_status); 

			free(input_f);
			free(interpolation_type);
			free(output_f);

			fclose(dispersion_solutions_f);
			fclose(outputfile);

			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status);  

			return 1; 

		}

		// ***********************************************************************
		// Clean up heap memory

		free(input_f);
		free(interpolation_type);
		free(output_f);

		// ***********************************************************************
		// Close input file (ARG 1), output file (ARG 7) and 
		// [FRARCFIT_OUTPUTF_WAVFITS_FILE] file

		if (fclose(dispersion_solutions_f)) {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -15, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

			fclose(outputfile);

                        if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                        if(fits_close_file(output_f_ptr, &output_f_status)); 

			return 1; 

		}

		if (fclose(outputfile)) {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -16, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

                        if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                        if(fits_close_file(output_f_ptr, &output_f_status)); 

			return 1; 

		}

		if(fits_close_file(input_f_ptr, &input_f_status)) { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -17, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error (stdout, input_f_status); 

                        if(fits_close_file(output_f_ptr, &output_f_status)); 

			return 1; 

	    	}

		if(fits_close_file(output_f_ptr, &output_f_status)) { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -18, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error (stdout, output_f_status); 

			return 1; 

	    	}

		// ***********************************************************************
		// Write success to [ERROR_CODES_FILE]

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", RETURN_FLAG, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 0;

	}

}
示例#7
0
文件: urlcache.c 项目: Sunmonds/wine
static void test_urlcacheA(void)
{
    static char ok_header[] = "HTTP/1.0 200 OK\r\n\r\n";
    BOOL ret;
    HANDLE hFile;
    BYTE zero_byte = 0;
    LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo;
    DWORD cbCacheEntryInfo;
    static const FILETIME filetime_zero;
    FILETIME now;

    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA1, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ok(lstrcmpiA(filenameA, filenameA1), "expected a different file name\n");

    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));

    ret = CommitUrlCacheEntry(TEST_URL1, NULL, filetime_zero, filetime_zero, NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY, NULL, 0, NULL, NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    ret = GetUrlCacheEntryInfo(TEST_URL1, NULL, &cbCacheEntryInfo);
    ok(!ret, "GetUrlCacheEntryInfo should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "GetUrlCacheEntryInfo should have set last error to ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL1, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(!memcmp(&lpCacheEntryInfo->ExpireTime, &filetime_zero, sizeof(FILETIME)),
       "expected zero ExpireTime\n");
    ok(!memcmp(&lpCacheEntryInfo->LastModifiedTime, &filetime_zero, sizeof(FILETIME)),
       "expected zero LastModifiedTime\n");
    ok(lpCacheEntryInfo->CacheEntryType == (NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY) ||
       broken(lpCacheEntryInfo->CacheEntryType == NORMAL_CACHE_ENTRY /* NT4/W2k */),
       "expected type NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY, got %08x\n",
       lpCacheEntryInfo->CacheEntryType);
    ok(!U(*lpCacheEntryInfo).dwExemptDelta, "expected dwExemptDelta 0, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    /* A subsequent commit with a different time/type doesn't change the type */
    GetSystemTimeAsFileTime(&now);
    ret = CommitUrlCacheEntry(TEST_URL1, NULL, now, now, NORMAL_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), NULL, NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    ret = GetUrlCacheEntryInfo(TEST_URL1, NULL, &cbCacheEntryInfo);
    ok(!ret, "GetUrlCacheEntryInfo should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL1, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    /* but it does change the time.. */
    todo_wine
    ok(memcmp(&lpCacheEntryInfo->ExpireTime, &filetime_zero, sizeof(FILETIME)),
       "expected positive ExpireTime\n");
    todo_wine
    ok(memcmp(&lpCacheEntryInfo->LastModifiedTime, &filetime_zero, sizeof(FILETIME)),
       "expected positive LastModifiedTime\n");
    ok(lpCacheEntryInfo->CacheEntryType == (NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY) ||
       broken(lpCacheEntryInfo->CacheEntryType == NORMAL_CACHE_ENTRY /* NT4/W2k */),
       "expected type NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY, got %08x\n",
       lpCacheEntryInfo->CacheEntryType);
    /* and set the headers. */
    todo_wine
    ok(lpCacheEntryInfo->dwHeaderInfoSize == 19,
       "expected headers size 19, got %d\n",
       lpCacheEntryInfo->dwHeaderInfoSize);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero, NORMAL_CACHE_ENTRY, NULL, 0, "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());

    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, NULL, &cbCacheEntryInfo, 0);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "RetrieveUrlCacheEntryFile should have set last error to ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());

    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo, 0);
    ok(ret, "RetrieveUrlCacheEntryFile failed with error %d\n", GetLastError());

    if (ret) check_cache_entry_infoA("RetrieveUrlCacheEntryFile", lpCacheEntryInfo);

    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = RetrieveUrlCacheEntryFile(TEST_URL1, NULL, &cbCacheEntryInfo, 0);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INVALID_DATA,
       "RetrieveUrlCacheEntryFile should have set last error to ERROR_INVALID_DATA instead of %d\n", GetLastError());

    if (pUnlockUrlCacheEntryFileA)
    {
        ret = pUnlockUrlCacheEntryFileA(TEST_URL, 0);
        ok(ret, "UnlockUrlCacheEntryFileA failed with error %d\n", GetLastError());
    }

    /* test Find*UrlCacheEntry functions */
    test_find_url_cache_entriesA();

    test_GetUrlCacheEntryInfoExA();
    test_RetrieveUrlCacheEntryA();
    test_IsUrlCacheEntryExpiredA();

    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        ret = pDeleteUrlCacheEntryA(TEST_URL1);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
    }

    SetLastError(0xdeadbeef);
    ret = DeleteFile(filenameA);
    todo_wine
    ok(!ret && GetLastError() == ERROR_FILE_NOT_FOUND, "local file should no longer exist\n");

    /* Creating two entries with the same URL */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA1, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ok(lstrcmpiA(filenameA, filenameA1), "expected a different file name\n");

    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    create_and_write_file(filenameA1, &zero_byte, sizeof(zero_byte));
    check_file_exists(filenameA);
    check_file_exists(filenameA1);

    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero,
            filetime_zero, NORMAL_CACHE_ENTRY, (LPBYTE)ok_header,
            strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    check_file_exists(filenameA);
    check_file_exists(filenameA1);
    ret = CommitUrlCacheEntry(TEST_URL, filenameA1, filetime_zero,
            filetime_zero, COOKIE_CACHE_ENTRY, NULL, 0, "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    /* By committing the same URL a second time, the prior entry is
     * overwritten...
     */
    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = GetUrlCacheEntryInfo(TEST_URL, NULL, &cbCacheEntryInfo);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    /* with the previous entry type retained.. */
    ok(lpCacheEntryInfo->CacheEntryType & NORMAL_CACHE_ENTRY,
       "expected cache entry type NORMAL_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    /* and the headers overwritten.. */
    todo_wine
    ok(!lpCacheEntryInfo->dwHeaderInfoSize, "expected headers size 0, got %d\n",
       lpCacheEntryInfo->dwHeaderInfoSize);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);
    /* and the previous filename shouldn't exist. */
    todo_wine
    check_file_not_exists(filenameA);
    check_file_exists(filenameA1);

    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        todo_wine
        check_file_not_exists(filenameA);
        todo_wine
        check_file_not_exists(filenameA1);
        /* Just in case, clean up files */
        DeleteFileA(filenameA1);
        DeleteFileA(filenameA);
    }

    /* Check whether a retrieved cache entry can be deleted before it's
     * unlocked:
     */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());
    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY, NULL, 0, "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());

    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, NULL, &cbCacheEntryInfo, 0);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());

    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, lpCacheEntryInfo,
            &cbCacheEntryInfo, 0);
    ok(ret, "RetrieveUrlCacheEntryFile failed with error %d\n", GetLastError());

    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        todo_wine
        ok(!ret, "Expected failure\n");
        todo_wine
        ok(GetLastError() == ERROR_SHARING_VIOLATION,
           "Expected ERROR_SHARING_VIOLATION, got %d\n", GetLastError());
        check_file_exists(filenameA);
    }
    if (pUnlockUrlCacheEntryFileA)
    {
        check_file_exists(filenameA);
        ret = pUnlockUrlCacheEntryFileA(TEST_URL, 0);
        todo_wine
        ok(ret, "UnlockUrlCacheEntryFileA failed: %d\n", GetLastError());
        /* By unlocking the already-deleted cache entry, the file associated
         * with it is deleted..
         */
        todo_wine
        check_file_not_exists(filenameA);
        /* (just in case, delete file) */
        DeleteFileA(filenameA);
    }
    if (pDeleteUrlCacheEntryA)
    {
        /* and a subsequent deletion should fail. */
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(!ret, "Expected failure\n");
        ok(GetLastError() == ERROR_FILE_NOT_FOUND,
           "expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
    }

    /* Test whether preventing a file from being deleted causes
     * DeleteUrlCacheEntryA to fail.
     */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    check_file_exists(filenameA);

    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero,
            filetime_zero, NORMAL_CACHE_ENTRY, (LPBYTE)ok_header,
            strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    check_file_exists(filenameA);
    hFile = CreateFileA(filenameA, GENERIC_READ, 0, NULL, OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL, NULL);
    ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA failed: %d\n",
       GetLastError());
    if (pDeleteUrlCacheEntryA)
    {
        /* DeleteUrlCacheEntryA should succeed.. */
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
    }
    CloseHandle(hFile);
    if (pDeleteUrlCacheEntryA)
    {
        /* and a subsequent deletion should fail.. */
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(!ret, "Expected failure\n");
        ok(GetLastError() == ERROR_FILE_NOT_FOUND,
           "expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
    }
    /* and the file should be untouched. */
    check_file_exists(filenameA);
    DeleteFileA(filenameA);

    /* Try creating a sticky entry.  Unlike non-sticky entries, the filename
     * must have been set already.
     */
    SetLastError(0xdeadbeef);
    ret = CommitUrlCacheEntry(TEST_URL, NULL, filetime_zero, filetime_zero,
            STICKY_CACHE_ENTRY, (LPBYTE)ok_header, strlen(ok_header), "html",
            NULL);
    ok(!ret, "expected failure\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER,
       "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
    SetLastError(0xdeadbeef);
    ret = CommitUrlCacheEntry(TEST_URL, NULL, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), "html", NULL);
    ok(!ret, "expected failure\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER,
       "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());
    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = GetUrlCacheEntryInfo(TEST_URL, NULL, &cbCacheEntryInfo);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(lpCacheEntryInfo->CacheEntryType & (NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY),
       "expected cache entry type NORMAL_CACHE_ENTRY | STICKY_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    ok(U(*lpCacheEntryInfo).dwExemptDelta == 86400,
       "expected dwExemptDelta 864000, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);
    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        /* When explicitly deleting the cache entry, the file is also deleted */
        todo_wine
        check_file_not_exists(filenameA);
    }
    /* Test once again, setting the exempt delta via SetUrlCacheEntryInfo */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());
    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = GetUrlCacheEntryInfo(TEST_URL, NULL, &cbCacheEntryInfo);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(lpCacheEntryInfo->CacheEntryType & (NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY),
       "expected cache entry type NORMAL_CACHE_ENTRY | STICKY_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    ok(U(*lpCacheEntryInfo).dwExemptDelta == 86400,
       "expected dwExemptDelta 864000, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    U(*lpCacheEntryInfo).dwExemptDelta = 0;
    ret = SetUrlCacheEntryInfoA(TEST_URL, lpCacheEntryInfo,
            CACHE_ENTRY_EXEMPT_DELTA_FC);
    ok(ret, "SetUrlCacheEntryInfo failed: %d\n", GetLastError());
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(!U(*lpCacheEntryInfo).dwExemptDelta, "expected dwExemptDelta 0, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    /* See whether a sticky cache entry has the flag cleared once the exempt
     * delta is meaningless.
     */
    ok(lpCacheEntryInfo->CacheEntryType & (NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY),
       "expected cache entry type NORMAL_CACHE_ENTRY | STICKY_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);
    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        todo_wine
        check_file_not_exists(filenameA);
    }
}
示例#8
0
void downloader_init(upstreams *upstr_ptr, mqd_t msgq_id) {

	/* Initialise MySQL connection */
	MYSQL_RES *result;
	MYSQL_ROW row;
	int num_fields;

	if ((conn = init_mysql(conn)) == NULL) {
		mysql_close(conn);
		error_log(ERROR, "MySQL initialisation failed");
		exit(EXIT_FAILURE);
	}

	if (!connect_mysql(conn)) {
		mysql_close(conn);
		error_log(ERROR, "MySQL connection failed");
		exit(EXIT_FAILURE);
	}

	int n;
	const config_setting_t *upstr_setting;
	static int upstream_count;

	upstr_setting = config_lookup(&cfg, "upstreams");
	upstream_count = config_setting_length(upstr_setting);

	error_log(ERROR, "Connected to MySQL.");
	struct mq_attr msgq_attr;
	int fe_id = cfg_get_int("fe_id");
	static char query[QUERY_MAX];
	unsigned int msgprio = 1;

	while (running) {
		/* Schedule upstreams */
		for (n = 0; n < upstream_count; n++) {
			if (!upstr_ptr[n].alive
					&& (time(NULL) - upstr_ptr[n].deadtime)
							> cfg_get_int("upstream_dead_timeout")) {
				error_log(DEBUG,
						"Making %s live again, time of dead: %d, now: %d",
						upstr_ptr[n].upstream, upstr_ptr[n].deadtime,
						time(NULL));
				upstr_ptr[n].alive = 1;
			}
			error_log(DEBUG, "Upstream: %s, active: %d", upstr_ptr[n].upstream,
					upstr_ptr[n].alive);
		}
		/* Get latest data */
		mq_getattr(msgq_id, &msgq_attr);
		if (!msgq_attr.mq_curmsgs) {
			if (cfg_get_int("dmode") == 2) {
				/* Query for robin mode*/
				sprintf(query,
						"SELECT filename, size from scoreboard WHERE id NOT "
								"IN(SELECT id from cached where fe_id=%d) AND count >=%d "
								"order by count DESC, last_modified DESC, size limit %d",
						fe_id, cfg_get_int("cache_req_count"),
						cfg_get_int("workers"));
			} else {
				/* Query for shard mode*/
				sprintf(query,
						"SELECT filename, size from scoreboard WHERE id NOT "
								"IN(SELECT id from cached where fe_id=%d) AND count >=%d "
								"AND fe_id=%d "
								"order by count DESC, last_modified DESC, size limit %d",
						fe_id, cfg_get_int("cache_req_count"), fe_id,
						cfg_get_int("workers"));
			}

			query_mysql(conn, query);
			result = mysql_store_result(conn);
			num_fields = mysql_num_fields(result);

			while ((row = mysql_fetch_row(result))) {
				if (row[0] && row[1]) {
					if (check_file_exists(row[0], atoi(row[1])) != 0) {
						continue;
					}
					mq_send(msgq_id, row[0], strlen(row[0]) + 1, msgprio);
				}
			}
			mysql_free_result(result);
		}
		sleep(5);
	}
	error_log(ERROR, "Exiting");
}
示例#9
0
/* Loop though files in a package and perform full file property checking. */
int check_pkg_full(alpm_pkg_t *pkg)
{
	const char *root, *pkgname;
	size_t errors = 0;
	size_t rootlen;
	char filepath[PATH_MAX];
	struct archive *mtree;
	struct archive_entry *entry = NULL;
	size_t file_count = 0;
	const alpm_list_t *lp;

	root = alpm_option_get_root(config->handle);
	rootlen = strlen(root);
	if(rootlen + 1 > PATH_MAX) {
		/* we are in trouble here */
		pm_printf(ALPM_LOG_ERROR, _("path too long: %s%s\n"), root, "");
		return 1;
	}
	strcpy(filepath, root);

	pkgname = alpm_pkg_get_name(pkg);
	mtree = alpm_pkg_mtree_open(pkg);
	if(mtree == NULL) {
		/* TODO: check error to confirm failure due to no mtree file */
		if(!config->quiet) {
			printf(_("%s: no mtree file\n"), pkgname);
		}
		return 0;
	}

	while(alpm_pkg_mtree_next(pkg, mtree, &entry) == ARCHIVE_OK) {
		struct stat st;
		const char *path = archive_entry_pathname(entry);
		mode_t type;
		size_t file_errors = 0;
		int backup = 0;

		/* strip leading "./" from path entries */
		if(path[0] == '.' && path[1] == '/') {
			path += 2;
		}

		if(strcmp(path, ".INSTALL") == 0) {
			char filename[PATH_MAX];
			snprintf(filename, PATH_MAX, "%slocal/%s-%s/install",
					alpm_option_get_dbpath(config->handle) + 1,
					pkgname, alpm_pkg_get_version(pkg));
			archive_entry_set_pathname(entry, filename);
			path = archive_entry_pathname(entry);
		} else if(strcmp(path, ".CHANGELOG") == 0) {
			char filename[PATH_MAX];
			snprintf(filename, PATH_MAX, "%slocal/%s-%s/changelog",
					alpm_option_get_dbpath(config->handle) + 1,
					pkgname, alpm_pkg_get_version(pkg));
			archive_entry_set_pathname(entry, filename);
			path = archive_entry_pathname(entry);
		} else if(*path == '.') {
			continue;
		}

		file_count++;

		if(rootlen + 1 + strlen(path) > PATH_MAX) {
			pm_printf(ALPM_LOG_WARNING, _("path too long: %s%s\n"), root, path);
			continue;
		}
		strcpy(filepath + rootlen, path);

		if(check_file_exists(pkgname, filepath, &st) == 1) {
			errors++;
			continue;
		}

		type = archive_entry_filetype(entry);

		if(type != AE_IFDIR && type != AE_IFREG && type != AE_IFLNK) {
			pm_printf(ALPM_LOG_WARNING, _("file type not recognized: %s%s\n"), root, path);
			continue;
		}

		if(check_file_type(pkgname, filepath, &st, entry) == 1) {
			errors++;
			continue;
		}

		file_errors += check_file_permissions(pkgname, filepath, &st, entry);

		if(type == AE_IFLNK) {
			file_errors += check_file_link(pkgname, filepath, &st, entry);
		}

		/* the following checks are expected to fail if a backup file has been
		   modified */
		for(lp = alpm_pkg_get_backup(pkg); lp; lp = lp->next) {
			alpm_backup_t *bl = lp->data;

			if(strcmp(path, bl->name) == 0) {
				backup = 1;
				break;
			}
		}

		if(type != AE_IFDIR) {
			/* file or symbolic link */
			file_errors += check_file_time(pkgname, filepath, &st, entry, backup);
		}

		if(type == AE_IFREG) {
			/* TODO: these are expected to be changed with backup files */
			file_errors += check_file_size(pkgname, filepath, &st, entry, backup);
			/* file_errors += check_file_md5sum(pkgname, filepath, &st, entry, backup); */
		}

		if(config->quiet && file_errors) {
			printf("%s %s\n", pkgname, filepath);
		}

		errors += (file_errors != 0 ? 1 : 0);
	}

	alpm_pkg_mtree_close(pkg, mtree);

	if(!config->quiet) {
		printf(_n("%s: %jd total file, ", "%s: %jd total files, ",
					(unsigned long)file_count), pkgname, (intmax_t)file_count);
		printf(_n("%jd altered file\n", "%jd altered files\n",
					(unsigned long)errors), (intmax_t)errors);
	}

	return (errors != 0 ? 1 : 0);
}
int main(int argc, char *argv []) {

	if(populate_env_variable(REF_ERROR_CODES_FILE, "L2_ERROR_CODES_FILE")) {

		printf("\nUnable to populate [REF_ERROR_CODES_FILE] variable with corresponding environment variable. Routine will proceed without error handling\n");

	}

	if (argc != 5) {

		if(populate_env_variable(SPCS_BLURB_FILE, "L2_SPCS_BLURB_FILE")) {

			RETURN_FLAG = 1;

		} else {

			print_file(SPCS_BLURB_FILE);

		}

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -1, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 1;

	} else {
		// ***********************************************************************
		// Redefine routine input parameters
		
		char *input_f			= strdup(argv[1]);
		char *interpolation_type	= strdup(argv[2]);
		int conserve_flux		= strtol(argv[3], NULL, 0);		
		char *output_f			= strdup(argv[4]);		
		
		// ***********************************************************************
		// Open input file (ARG 1), get parameters and perform any data format 
		// checks

		fitsfile *input_f_ptr;

		int input_f_maxdim = 2, input_f_status = 0, input_f_bitpix, input_f_naxis;
		long input_f_naxes [2] = {1,1};

		if(!fits_open_file(&input_f_ptr, input_f, IMG_READ_ACCURACY, &input_f_status)) {

			if(!populate_img_parameters(input_f, input_f_ptr, input_f_maxdim, &input_f_bitpix, &input_f_naxis, input_f_naxes, &input_f_status, "INPUT FRAME")) {

				if (input_f_naxis != 2) {	// any data format checks here

					write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -2, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);

					free(input_f);
					free(output_f);					
					free(interpolation_type);
					if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

					return 1;
	
				}

			} else { 

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -3, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, input_f_status); 

				free(input_f);
					free(output_f);					
				free(interpolation_type);
				if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

				return 1; 

			}

		} else { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -4, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error(stdout, input_f_status); 

			free(input_f);
			free(output_f);				
			free(interpolation_type);			

			return 1; 

		}
		
		// ***********************************************************************
		// Set the range limits

		int cut_x [2] = {1, input_f_naxes[0]};
		int cut_y [2] = {1, input_f_naxes[1]};

		// ***********************************************************************
		// Set parameters used when reading data from input file (ARG 1)

		long fpixel [2] = {cut_x[0], cut_y[0]};
		long nxelements = (cut_x[1] - cut_x[0]) + 1;
		long nyelements = (cut_y[1] - cut_y[0]) + 1;

		// ***********************************************************************
		// Create arrays to store pixel values from input fits file (ARG 1)

		double input_f_pixels [nxelements];
		
		// ***********************************************************************
		// Get input fits file (ARG 1) values and store in 2D array

		int ii;

		double input_frame_values [nyelements][nxelements];
		memset(input_frame_values, 0, sizeof(double)*nxelements*nyelements);
		for (fpixel[1] = cut_y[0]; fpixel[1] <= cut_y[1]; fpixel[1]++) {

			memset(input_f_pixels, 0, sizeof(double)*nxelements);

			if(!fits_read_pix(input_f_ptr, TDOUBLE, fpixel, nxelements, NULL, input_f_pixels, NULL, &input_f_status)) {

				for (ii=0; ii<nxelements; ii++) {

					input_frame_values[fpixel[1]-1][ii] = input_f_pixels[ii];

				}

			} else { 

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -5, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, input_f_status); 

				free(input_f);
				free(output_f);					
				free(interpolation_type);				
				if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

				return 1; 

			}

		}	
		
		// ***********************************************************************
		// Open [SPTRACE_OUTPUTF_TRACES_FILE] input file
	
		FILE *inputfile;
	
		if (!check_file_exists(SPTRACE_OUTPUTF_TRACES_FILE)) { 

			inputfile = fopen(SPTRACE_OUTPUTF_TRACES_FILE , "r");

		} else {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -6, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);

			return 1;

		}	
		
		// ***********************************************************************
		// Find some [SPTRACE_OUTPUTF_TRACES_FILE] file details

		char input_string [500];

		bool find_polynomialorder_comment = FALSE;

		int polynomial_order;	

		char search_string_1 [20] = "# Polynomial Order:\0";	// this is the comment to be found from the [SPTRACE_OUTPUTF_TRACES_FILE] file

		while(!feof(inputfile)) {

			memset(input_string, '\0', sizeof(char)*500);
	
			fgets(input_string, 500, inputfile);	

			if (strncmp(input_string, search_string_1, strlen(search_string_1)) == 0) { 

				sscanf(input_string, "%*[^\t]%d", &polynomial_order);		// read all data up to tab as string ([^\t]), but do not store (*)
				find_polynomialorder_comment = TRUE;
				break;

			} 

		}

		if (find_polynomialorder_comment == FALSE) {	// error check - didn't find the comment in the [SPTRACE_OUTPUTF_TRACES_FILE] file

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -7, "Status flag for L2 frcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(input_f);
			free(output_f);				
			free(interpolation_type);				
			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1;

		}
		
		// ***********************************************************************
		// Rewind and extract coefficients from [SPTRACE_OUTPUTF_TRACES_FILE] file 

		rewind(inputfile);

		int token_index;	// this variable will hold which token we're dealing with
		int coeff_index;	// this variable will hold which coefficient we're dealing with
		double this_coeff;
		double this_chisquared;
	
		char *token;

		double coeffs [polynomial_order+1];
		memset(coeffs, 0, sizeof(double)*(polynomial_order+1));

		while(!feof(inputfile)) {

			memset(input_string, '\0', sizeof(char)*500);
	
			fgets(input_string, 500, inputfile);

			token_index = 0;
			coeff_index = 0;

			if (strtol(&input_string[0], NULL, 0) > 0) { 		// check the line begins with a positive number
				
				// ***********************************************************************
				// String tokenisation loop: 
				//
				// 1. init calls strtok() loading the function with input_string
				// 2. terminate when token is null
				// 3. we keep assigning tokens of input_string to token until termination by calling strtok with a NULL first argument
				// 
				// n.b. searching for tab or newline separators ('\t' and '\n')
				for (token=strtok(input_string, "\t\n"); token !=NULL; token = strtok(NULL, "\t\n")) {	
					if ((token_index >= 0) && (token_index <= polynomial_order)) { 			// coeff token
						this_coeff = strtod(token, NULL);
						//printf("%d\t%e\n", coeff_index, this_coeff);				// DEBUG
						coeffs[coeff_index] = this_coeff;
						coeff_index++;
					} else if (token_index == polynomial_order+1) {					// chisquared token
						this_chisquared = strtod(token, NULL);
					}
					token_index++;
				}
			}
		}	
		
		// ***********************************************************************
		// Determine the min and max offsets from c0 (this is needed to avoid 
		// trying to interpolate past the limits) otherwise throws GSL 
		// INTERPOLATION ERROR.
		
		double c0 = coeffs[0];
		float min_offset = 0;	// this is how much the curvature extends in -ve y
		float max_offset = 0;	// this is how much the curvature extends in +ve y
		for (ii=0; ii<nxelements; ii++) {
			float this_offset = gsl_poly_eval(coeffs, polynomial_order+1, ii) - c0;
			if (this_offset > max_offset) {
				max_offset = this_offset;
			}
			if (this_offset < min_offset) {
				min_offset = this_offset;
			}
		}	

                int min_offset_int = (int)ceil(fabs(min_offset));
		int max_offset_int = (int)ceil(fabs(max_offset));
		int nyelements_reb = nyelements - max_offset_int - min_offset_int;

		// ***********************************************************************
		// Do the rebinning (conserving flux where applicable)

		double reb_values[nyelements_reb][nxelements];
		memset(reb_values, 0, sizeof(double)*nyelements_reb*nxelements);		
		
		double this_pre_rebin_flux, this_post_rebin_flux;
		double this_column_values[nyelements];
		double this_column_values_reb[nyelements_reb];		
		double x_offsetted[nyelements];
		
		int jj;
		for (ii=0; ii<nxelements; ii++) {
			this_pre_rebin_flux = 0.;
			double this_offset = gsl_poly_eval(coeffs, polynomial_order+1, ii) - c0;
			memset(this_column_values, 0, sizeof(double)*nyelements);
			memset(this_column_values_reb, 0, sizeof(double)*nyelements_reb);			
			for (jj=0; jj<nyelements; jj++) {
				this_column_values[jj] = input_frame_values[jj][ii];
				x_offsetted[jj] = jj - this_offset;
				this_pre_rebin_flux += input_frame_values[jj][ii];
			}

			interpolate(interpolation_type, x_offsetted, this_column_values, nyelements, min_offset_int, nyelements_reb-max_offset_int, 1, this_column_values_reb);

			// get post rebin flux
			this_post_rebin_flux = 0.;
			for (jj=0; jj<nyelements_reb; jj++) {
				this_post_rebin_flux += this_column_values_reb[jj];
			}
			
			// apply conservation factor
			double conservation_factor = this_pre_rebin_flux/this_post_rebin_flux;
			//printf("%f\t%f\t%f\n", this_pre_rebin_flux, this_post_rebin_flux, conservation_factor);	// DEBUG
			if (conserve_flux == TRUE) {
				for (jj=0; jj<nyelements_reb; jj++) {
					reb_values[jj][ii] = this_column_values_reb[jj] * conservation_factor;
				} 
			} else {
				for (jj=0; jj<nyelements_reb; jj++) {				
					reb_values[jj][ii] = this_column_values_reb[jj];					
				}
			}	
		}
		
		// ***********************************************************************
		// Set output frame parameters	

		fitsfile *output_f_ptr;
	
		int output_f_status = 0;
		long output_f_naxes [2] = {nxelements,nyelements_reb};
	
		long output_f_fpixel = 1;

		// ***********************************************************************
		// Create [output_frame_values] array to hold the output data in the 
		// correct format
                
		int kk;
		double output_frame_values [nxelements*nyelements_reb];
		memset(output_frame_values, 0, sizeof(double)*nxelements*nyelements_reb);
		for (ii=0; ii<nyelements_reb; ii++) {	
			jj = ii * nxelements;			
			for (kk=0; kk<nxelements; kk++) {
				output_frame_values[jj] = reb_values[ii][kk];
				jj++;
			}
		}	
		
		// ***********************************************************************
		// Create and write [output_frame_values] to output file (ARG 4)
	
		if (!fits_create_file(&output_f_ptr, output_f, &output_f_status)) {
	
			if (!fits_create_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[0], 2, output_f_naxes, &output_f_status)) {

				if (!fits_write_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[1], output_f_fpixel, nxelements*nyelements_reb, output_frame_values, &output_f_status)) {

				} else { 

					write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -8, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
					fits_report_error(stdout, output_f_status); 

					free(input_f);
					free(output_f);				
					free(interpolation_type);
					if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
					if(fits_close_file(output_f_ptr, &output_f_status)) fits_report_error (stdout, output_f_status);

					return 1; 

				}

			} else {

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -9, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, output_f_status); 

				free(input_f);
				free(output_f);				
				free(interpolation_type);
				if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
				if(fits_close_file(output_f_ptr, &output_f_status)) fits_report_error (stdout, output_f_status);

				return 1; 

			}

		} else {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -10, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error(stdout, output_f_status); 

			free(input_f);
			free(output_f);				
			free(interpolation_type);
			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1; 

		}

		// ***********************************************************************
		// Free arrays on heap

		free(input_f);
		free(interpolation_type);
		free(output_f);
		
		// ***********************************************************************
		// Close [SPTRACE_OUTPUTF_TRACES_FILE] output file, input file (ARG 1) and
		// output file (ARG 4)
		
		if (fclose(inputfile)) {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -11, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);

			if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

			return 1; 

		}		

		if(fits_close_file(input_f_ptr, &input_f_status)) { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -12, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error (stdout, input_f_status); 

			return 1; 

	    	}
	    	
		if(fits_close_file(output_f_ptr, &output_f_status)) { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", -13, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error (stdout, output_f_status); 

			return 1; 

	    	}	    	
		
		// ***********************************************************************
		// Write success to [ERROR_CODES_FILE]

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATCO", RETURN_FLAG, "Status flag for L2 spcorrect routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 0;

	}

}
示例#11
0
static http_status_t check_response_status(const int status,const char * path)
{
	if(status == HTTP_STATUS_NOT_IMPLEMENTED) return HTTP_STATUS_LOOKUP[status];
	if(!check_file_exists(path))              return HTTP_STATUS_LOOKUP[HTTP_STATUS_NOT_FOUND];
	return HTTP_STATUS_LOOKUP[HTTP_STATUS_OK];
}
示例#12
0
/* init_stat()
 * 
 * Initialize MySQL and GeoIP API.
 * Needs a 'path' to a passwd file. If it is NULL or does not exist,
 * will use the 'DEFAULT_PATH' constant defined previously.
 * However, 'host' can not be NULL.
 * */
int
init_stat				(char * host, char * path)
{
    char * contents, * entry, * user, * passwd, * add_info;
	
    if (host == NULL)
    {
	log_message(ERROR, EMSG_DBHOST, NULL);
	return (ECOD_DBHOST);
    }
	
    /* Find required login and password.
     * If 'path' is NULL or does not exist, use a default value.
     * */
    if ((path == NULL) || (!check_file_exists(path)))
    {
	contents = (char *)get_file_contents(DEFAULT_PATH);
    }
    else
    {
	contents = (char *)get_file_contents(path);
    }
	
    entry = strstr(contents, DATABASE);
    entry = strchr(entry, '=') + 1;
	
    if ((user = get_first_substr(entry, ',')) == NULL)
    {
	free(contents);
	log_message(ERROR, EMSG_STATDBUSER, NULL);
	return (ECOD_STATDBUSER);
    }
	
    if ((passwd = get_between_delim(entry, ',', ';')) == NULL)
    {
	free(user);
	free(contents);
	log_message(ERROR, EMSG_STATDBPASS, NULL);
	return (ECOD_STATDBPASS);
    }
    free(contents);

    /* Connect to MySQL database. */
    if (((db_conn = mysql_init(NULL)) == NULL) ||
	(mysql_real_connect(db_conn, host, user, passwd, DATABASE, 0, NULL, 0) == NULL))
    {
	free(user);
	free(passwd);
	mysql_close(db_conn);
	log_message(ERROR, EMSG_DBSTATCONN, NULL);
	return (ECOD_DBSTATCONN);
    }
	
    free(user);
    free(passwd);
	
    /* GeoIP, only for request statistics.
     * Initialization is done here to avoid performance and memory usage
     * problems while analyzing request data.
     * */
    if ((gi_db = GeoIP_open("/usr/share/GeoIP/GeoLiteCity.dat", GEOIP_STANDARD)) == NULL)
    {
	log_message(ERROR, EMSG_GISTATINIT, NULL);
	return (ECOD_GISTATINIT);
    }
	
    asprintf(&add_info, "Server: %s\n", host);
    log_message(MESSAGE, IMSG_STATSENABLED, add_info);
    free(add_info);
    stats_enabled = 1;
    return (EXIT_SUCCESS);
}