#!/bin/bash
if [ -z "$offset" -a -z "$fraction" ]; then
	offset=-20
fi
for A; do
	echo >&2 "$A"
#	pos=$(dc -e "$(mlength "$A") 10 - p" | sed 's/\..*//')
	if [ -n "$fraction" ]; then
		pos=$(dc -e "$(mlength "$A") $fraction * p" | sed 's/\..*//')
	else
		if [ "$offset" -lt 0 ]; then
			pos=$(dc -e "$(mlength "$A") 0$offset - p" | sed 's/\..*//')
		else
			pos="$offset"
		fi
	fi
#	mplayer -really-quiet -frames 1 -ss $pos "$A" -nosound -vo jpeg:quality=90
	fix_count=0
	while true; do
		echo >&2 -n "  " ; v mplayer -really-quiet -frames 1 -ss $pos "$A" -nosound -vo jpeg:quality=90
		if [ -e 00000001.jpg ]; then
			break
		fi
		if [ $pos -eq 0 ]; then
			echo >&2 "  failed"
			break
		elif [ $pos -lt 60 ]; then
			pos=0
		elif [ "$fix_count" -lt 5 ]; then
			pos=$(($pos - 10))
		elif [ "$fix_count" -lt 10 ]; then
			pos=$(($pos - 60))
		else
			pos=$(($pos / 2))
		fi
		fix_count=$((fix_count + 1))
	done
	mv 00000001.jpg "${A%.*}.jpg"
done
