#!/bin/bash
# Batch extracts right and left images from 
# folders of Fuji .MPO stereogram files.
# Also generates viewing jpg pairs for 3 common viewer types.

# Copy this to the folder with the .MPO files.

# Uncomment the Pair Generation lines you want, 
# following the instructions on each.
# Leave unwanted sections commented so you dont drown in pictures.
# 
# Call this script (making sure it's executable).
#
# Enjoy and edit your new viewing files.

# Maybe import the viewing pairs to Open Office Draw for
# free, easy and precise scaling and printing:
# ( Format > Position and Size. Check box "Keep Ratio".
# View Magic vertical edge 8" . Spectacular!
# Side-by-side, horizontal edge 2 x 70-75mm = 150mm
#                             abt 2 x 2 3/4" = 5 1/2"
# Cross-eyed, size not critical. Experiment.

# (Thank you David Glover for Image Magick inspiration.
# You will also need vips , free for Mac / Linux.
# Win folk, sorry. This script won't work as is for you,
# but you should be able to base a script on it.

# michael.pitchford@yale.edu perpetrated this script. 
# Use free, at entirely your own risk. 
# I give no guarantees whatever. 04JAN11.)

# Make sure we have the ok directories, or make them.

# left images
if [ ! -d l ]
then
mkdir l 
fi

# right images
if [ ! -d r ]
then
mkdir r 
fi

# top-bottom pairs for View Magic
if [ ! -d tbpairs ]
then
mkdir tbpairs 
fi

# right-left pairs for cross-eye viewing
if [ ! -d rlpairs ]
then
mkdir rlpairs 
fi

# left-right pairs for side-by-side viewers
if [ ! -d lrpairs ]
then
mkdir lrpairs 
fi

# pull out the left images
for k in $(ls *.MPO) ; do exiftool -trailer:all= $k -o l/$k.jpg ; done
# pull out the right images
for k in $(ls *.MPO) ; do exiftool $k -mpimage2 -b > r/$k.jpg ; done
echo "splitting done, now making your viewing pairs"

# 

# Uncomment the next line to enable View Magic pairs
 for k in $(ls *.MPO) ; do vips im_tbjoin r/$k.jpg l/$k.jpg tbpairs/$k.jpg ; done

# Uncomment the next line to enable cross-eye viewing pairs
 for k in $(ls *.MPO) ; do vips im_lrjoin r/$k.jpg l/$k.jpg rlpairs/$k.jpg ; done

# Uncomment the next line to enable side-by-side viewer pairs
 for k in $(ls *.MPO) ; do vips im_lrjoin l/$k.jpg r/$k.jpg lrpairs/$k.jpg ; done

echo "Congratulations - Find your stereo pairs in"
echo "tbpairs for View Magic"
echo "rlpairs for Cross-Eye"
echo "lrpairs for side-by-side viewers"
sleep 5
exit 0

