#!/bin/bash
headOut()
{
letterIn=$(echo "$QUERY_STRING" | sed -n 's/^.*letter=\([^&]*\).*$/\1/p')
touch ../tmp/alphaListing
wget http://www.crunchyroll.com/videos/anime/alpha?group=$letterIn -O ../tmp/alphaListing
IFS=$'\n'
bgs=($(ls -L ../backgrounds/))
numdirs=${#bgs[@]}
index=$(( (( RANDOM % $numdirs ) - 2) + 1 ))
if [ -f ./000.jpg ]; then
bg="
";
else
bg="";
fi
	echo '
	MiniRoll App
	
	
	
'${bg}'
' > ../tmp/alist.html
main
}
main()
{
if [[ -f ../tmp/preaTitles.txt && -f ../tmp/preaImgList.txt && -f ../tmp/aTitles.txt && -f ../tmp/aImgList.txt && -f ../tmp/aMediaIds.txt ]]
then
    touch ../tmp/preaTitles.txt ;
    touch ../tmp/preaImgList.txt ;
    touch ../tmp/aTitles.txt ;
    touch ../tmp/aImgList.txt ;
    touch ../tmp/aMediaIds.txt ;
    sed -n 's/.*title="\([^"]*\).*/\1/p' ../tmp/alphaListing > ../tmp/preaTitles.txt
    sed -n 's/.*src="\([^"]*\).*/\1/p' ../tmp/alphaListing > ../tmp/preaImgList.txt
    sed -n 's/.*group_id="\([^"]*\).*/\1/p' ../tmp/alphaListing > ../tmp/aMediaIds.txt
else
    sed -n 's/.*title="\([^"]*\).*/\1/p' ../tmp/alphaListing > ../tmp/preaTitles.txt
    sed -n 's/.*src="\([^"]*\).*/\1/p' ../tmp/alphaListing > ../tmp/preaImgList.txt
    sed -n 's/.*group_id="\([^"]*\).*/\1/p' ../tmp/alphaListing > ../tmp/aGrpIds.txt
fi
d=$(cat ../tmp/aGrpIds.txt | wc -l) >> /dev/null ;
i="1"
    while [ $i -le $d ]; do
	    title=$(sed -n "${i}p" ../tmp/preaTitles.txt);
      imgLnk=$(sed -n "${i}p" ../tmp/preaImgList.txt);
if [[ "$imgLnk" == *".jpg"* ]]
then
    echo "$imgLnk" >> ../tmp/aImgList.txt
else
    echo "Not an img..."
fi
if [[ "$title" == *"Spring"* || "$title" == *"Summer"* \
   || "$title" == *"Fall"*   || "$title" == *"Winter"* ]]
then
    echo "Not a title..."
else
    echo "$title" >> ../tmp/aTitles.txt ;
fi
	    i=$[$i++1];
done
i="1";
    while [ $i -le $d ]; do
	    title=$(sed -n "${i}p" ../tmp/aTitles.txt);
      imgLnk=$(sed -n "${i}p" ../tmp/aImgList.txt);
	    groupID=$(sed -n "${i}p" ../tmp/aGrpIds.txt);
      vdoLnk="http://www.crunchyroll.com/swf/StandardVideoPlayer.swf?config_url=http%3A%2F%2Fwww.crunchyroll.com%2Fxml%2F%3Freq%3DRpcApiVideoPlayer_GetStandardConfig%26media_id%3D"$groupID""
	    echo '
' >> ../tmp/alist.html ;
	    i=$[$i++1];
done
endOut
}
endOut()
{
    echo '
' >> ../tmp/alist.html
redirect
}
redirect()
{
echo "Content-type: text/html"
echo ""
echo ""
echo  ""
echo    "Loading..."
echo    ""
echo  ""
echo  ""
echo   "
        You will be redirected in a few seconds...
        
"
echo    ""
echo  ""
echo ""
}
headOut