packages feed

UMM-0.2.2: UMMPlot.hs

{- Copyright 2010 Uwe Hollerbach <uh@alumni.caltech.edu>

This file is part of umm, Uwe's Money Manager.

umm is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.

umm is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License
along with umm; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

$Id: UMMPlot.hs,v 1.3 2010/06/13 23:46:16 uwe Exp $ -}

module UMMPlot (genPlot) where
import Prelude hiding (putStr, putStrLn, print)
import Data.List
import System.IO(openFile, IOMode(..), hClose)
import System.IO.UTF8
import System.Process
import Control.Monad

import UMMData

-- TODO: a lot more work!

-- Adjust as needed: for example, for pgm output, use
--  "set terminal pbm gray medium size 800,600\n" ++

termo :: String -> String -> String
termo output name =
  "set terminal postscript 'Times-Roman' 16\n" ++
  "set output '" ++ output ++ ".ps'\n" ++
  "set title 'Value of " ++ name ++ " over time'\n" ++
  "unset key\n" ++
  "plot '" ++ output ++ ".dat' using 1:2 with lines\n"

genPlot :: String -> Name -> [(Date, [Amount])] -> IO ()
genPlot output name pts =
  do fp <- openFile (output ++ ".plot") WriteMode
     hPutStr fp (termo output (show name))
     -- TODO: analyze input, generate nice xtics
     hClose fp
     fd <- openFile (output ++ ".dat") WriteMode
     mapM_ (dP fd) pts
     hClose fd
     doit ("gnuplot " ++ output ++ ".plot")
  where dP fp (d,vs) =
          hPutStr fp (show (julianDate d)) >>
            mapM_ (dY fp) vs >> hPutStrLn fp ""
        dY fp r = hPutStr fp (' ' : show r)

-- If you use the stupid version, you'll get a warning that nothing from
-- System.Process is used... that's ok.

doit :: String -> IO ()

-- Stupid version that just says what the user needs to do next:
-- use this if you're using ghc 6.8.

-- doit cmd = putStrLn ("now you must run '" ++ cmd ++ "'")

-- Smart version that actually runs the command:
-- use this if you're using 6.10 or later.

doit cmd = putStrLn ("running '" ++ cmd ++ "'") >> system cmd >> return ()