--------------------------------------------------------------------
-- |
-- Module    : scale an image
-- Copyright : (c) Galois, Inc. 2008
-- License   : BSD3
--
-- Maintainer: Don Stewart <dons@galois.com>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------

import System.Environment
import System.IO
import System.Exit
import Data.Char

import System.FilePath
import Graphics.GD

main = do
    args      <- getArgs
    (x,y,f,g) <- case args of
         [sx,sy,f,g] -> case do x <- maybeRead sx
                                y <- maybeRead sx
                                Just (x,y,f,g) of
                       Nothing -> die
                       Just g  -> return g
         _ -> die

    load <- case map toLower (takeExtension f) of
        ".jpg"  -> return loadJpegFile
        ".jpeg" -> return loadJpegFile
        ".png"  -> return loadPngFile
        ".gif"  -> return loadGifFile
        _       -> die

    save <- case map toLower (takeExtension g) of
        ".jpg"  -> return (saveJpegFile 95)
        ".jpeg" -> return (saveJpegFile 95)
        ".png"  -> return savePngFile
        ".gif"  -> return saveGifFile
        _       -> die

    image  <- load f
    image' <- resizeImage x y image
    save g image'

------------------------------------------------------------------------

die :: IO a
die = do
    hPutStrLn stderr
         "Usage: scaleimage <x> <y> input.[png,gif,jpg] output.[png,gif,jpg]"
    exitWith (ExitFailure 1)

maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
    [(x, "")] -> Just x
    _         -> Nothing
