-- Columns: snarf only columns with variations in them (ignoring spaces)

module Columns where

import Data.List (elemIndex,intersperse)
import Data.Char (isSpace)

-- | remove columns where all agree
filterCols cs = filter (\((i,c),ss) -> i `elem`cs || (unlike $ filter (not . isSpace) ss))
    where unlike (x:xs) = any (/=x) xs
	  unlike [] = False

alignCols = unlines . map (concat . intersperse "\t")

-- | convert set of columns to lines of tab-separated cells, the names for each
--   line passed in separately
showCols :: [String] -> [((Int,Char),[Char])] -> [[String]]
showCols names cols = header : zipWith (:) names (map (map return) $ transpose rest)
    where header = take (maximum $ map length names) (repeat ' ') : map showFst cols
          rest   = map snd cols :: [[Char]]
          concatCols = undefined -- concat . intersperse '\t'
          showFst ((i,c),_) = show i++[c]

-- enumerate columns, given the index row
-- position increments 10 for
enumerate :: [Char] -> [String] -> [((Int,Char),[Char])]
enumerate ix cs = go (init,' ') ix cs 
    where init = negate . length . takeWhile (==' ') $ ix
          go (n,' ') ('-':is) (c:cs) = ((n-1,'a'),c)  : go (n,'a') is cs
          go (n,x)   ('-':is) (c:cs) = ((n-1,succ x),c) : go (n,succ x) is cs
          go (n,_)   (i:is)   (c:cs) = ((n,' '),c) : go (n+1,' ') is cs
          go _ [] [] = []
          go _ _ _   = error "mismatching number of columns!"

-- break after
splitLine l = case elemIndex ')' l of 
                Just i -> splitAt (i+2) l
                Nothing -> error ("can't find closing paren in line:\n '"++take 50 l++"'.")

-- turn lines into columns, lines must have same length!
transpose :: [[Char]] -> [[Char]]
transpose xs = case filter (not . null) xs of 
                 [] -> []
                 _ -> map head xs : transpose (map tail xs)


