#!/bin/bash
#This script splits a PDF into its constituent pages, cuts the pages into half by a HORIZONTAL line, and stitches the pages back together. It requires Imagemagick.
#The command is ./splitpages-hori.sh [number of pages in original file] [file to be converted]  [new file]. So if the original PDF is called book.pdf and has 6 pages, and the new file is newbook.pdf, the command would be ./splitpages-hori.sh 6 book.pdf newbook.pdf

#Split book.pdf into many images, one for each page
convert -quality 100 -density 200x200 $2 page%05d.png

#Determine width of images
width=$(file page00000.png | cut -d "," -f 2 | cut -d " " -f 2)

#Halve the height. Must convert from float to int
readheight=$(file page00000.png | cut -d "," -f 2 | cut -d " " -f 4)
height=${readheight%,} #remove comma
halfheight=`echo $height / 2 | bc -l` #use bc for floating point calc
inthalfheight=`echo ${halfheight} | cut -d . -f 1` #truncate decimal point and zeroes

#Loop over all pages and slice each into half
for ((i=0; i<$1; i++)); do
    ii=$(printf "%.5d" "$i")
    k=$((2*$i))
    convert page${ii}.png -crop ${width}x${inthalfheight} +repage +adjoin -scene $k half%05d.png
done

#Combine halved pages into PDF
convert -adjoin half* $3

#Remove images
rm *png