/*
 *  PsychGSSetMovieTimeIndex()  -- Set current playback time of movie, perform active seek if needed.
 */
double PsychGSSetMovieTimeIndex(int moviehandle, double timeindex, psych_bool indexIsFrames)
{
    GstElement		*theMovie;
    double		oldtime;
    long		targetIndex;
    GstEvent            *event;
    
    if (moviehandle < 0 || moviehandle >= PSYCH_MAX_MOVIES) {
        PsychErrorExitMsg(PsychError_user, "Invalid moviehandle provided!");
    }
    
    // Fetch references to objects we need:
    theMovie = movieRecordBANK[moviehandle].theMovie;    
    if (theMovie == NULL) {
        PsychErrorExitMsg(PsychError_user, "Invalid moviehandle provided. No movie associated with this handle !!!");
    }
    
    // Retrieve current timeindex:
    oldtime = PsychGSGetMovieTimeIndex(moviehandle);

    // TODO NOTE: We could use GST_SEEK_FLAG_SKIP to allow framedropping on fast forward/reverse playback...

    // Index based or target time based seeking?
    if (indexIsFrames) {
	// Index based seeking:		
	// TODO FIXME: This doesn't work (well) at all! Something's wrong here...
	// Seek to given targetIndex:
	targetIndex = (long) (timeindex + 0.5);

	// Simple seek, frame buffer (index) oriented, with pipeline flush and accurate seek,
	// i.e., not locked to keyframes, but frame-accurate: GST_FORMAT_DEFAULT?
	// gst_element_seek_simple(theMovie, GST_FORMAT_BUFFERS, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, targetIndex);
	event = gst_event_new_seek(1.0, GST_FORMAT_BUFFERS, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
				   GST_SEEK_TYPE_SET, targetIndex, GST_SEEK_TYPE_END, 0);
	gst_element_send_event(theMovie, event);
    }
    else {
	// Time based seeking:
	// Set new timeindex as time in seconds:

	// Simple seek, time-oriented, with pipeline flush and accurate seek,
	// i.e., not locked to keyframes, but frame-accurate:
	gst_element_seek_simple(theMovie, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, (gint64) (timeindex * (double) 1e9));
    }

    // Block until seek completed, failed or timeout of 30 seconds reached:
    gst_element_get_state(theMovie, NULL, NULL, (GstClockTime) (30 * 1e9));

    // Return old time value of previous position:
    return(oldtime);
}
/*
 *  PsychGetMovieTimeIndex()  -- Return current playback time of movie.
 */
double PsychGetMovieTimeIndex(int moviehandle)
{

	if (usegs()) {
        #ifdef PTB_USE_GSTREAMER
	return(PsychGSGetMovieTimeIndex(moviehandle));
	#endif
	} else {
	#ifdef PSYCHQTAVAIL
	return(PsychQTGetMovieTimeIndex(moviehandle));
	#endif
	}

	PsychErrorExitMsg(PsychError_unimplemented, "Sorry, Movie playback support not supported on your configuration.");
	return(0.0);
}