fillPreviewBox :: G.VBox -> PreviewParms  -> IORef [(String,DrawRef)] -> IO ()
fillPreviewBox pBox pprms drawRefList  = do
    --wrt get the top part: a horizontal box with two combo boxes and
    -- two buttons, as well as a radio button group to choose whether
    -- to view available schemes or sections
    optionsBox <-  G.hBoxNew False 0
    sep <- G.hSeparatorNew
    --[lframe ,rframe] <- sequence . replicate 2 $ G.hBoxNew False 2
    --[schmRButt, sectRButt] <- mapM G.radioButtonNewWithLabel ["Schemes","Sections"]
    --------- **** need handles for schmRButt and  sectRButt
    -- output these buttons in a vertical table
    --rButtstable <- tableWithWidgetList False [schmRButt, sectRButt] True 3
    --
    chainEntry <-  G.entryNew
    mapM_ (\ent -> do
                G.entrySetWidthChars ent 4
                G.entrySetMaxLength ent 4) [chainEntry]
    -- let buttLables = ["Add selection","Show subsections","Show all","Analyse selected subsections"]
    let buttLables = ["Add selection","Show subsections","Add all","Analyse selected subsections"]
    [lAnalButt, addButt, remButt,stackButt] <-  mapM G.buttonNewWithLabel buttLables
    --                         flip (horizontalWidgetList True) False
    G.widgetSetSensitive optionsBox False
    --G.containerAdd rframe rbox
    sectsRef <- newIORef [] -- an IOref for defects to be used by the clearAdd function
    drawRef <- newIORef emptyDrawRwf -- emptyDrawRwf
    indexRef <- newIORef [] -- ^ the indexes in the notebook
    --  HANDLE FOR STAKING -----------
    G.on stackButt G.buttonActivated $ do
        drf <- readIORef drawRef
        let ln = length ( chnLabel drf)
        addedChains <- G.entryGetText chainEntry >>= return . entVal
        if all (> 0) [ln , addedChains] then  do
            let name = caption drf
            let fromTo from to = myTake to . drop from
            let currData = fromTo (currChain drf) (addChain drf) (chnLabel drf)
            let range = " chains" ++ (head currData) ++ " to " ++ last currData
            wrtFun pprms (name ++ range)
        else
            return () -- a message here?
    --avlLabel <- G.labelNew (Just "Available conditions/schemes: ")
    [avlCombo,sectionsCombo] <- sequence $ replicate 2 G.comboBoxNewText
    ----- add options to the avlCombo
    ----- get the list for avlCombo by checking to see what ahs been extracted
    ----- The conditions alaready extracted, but not necessarily, analysed, are added to the list
    ----- The same is done for available schemes
    --let extract = (checkIfExtracted (\_ -> return ())) `seq` getAlreadyExtracted
    getAlreadyExtracted True >>= mapM_ (G.comboBoxAppendText avlCombo)
    G.on avlCombo G.changed $ handleForCondComboSelection sectsRef avlCombo sectionsCombo
    avlBox <- labelLeftofWidget "Extracted: " avlCombo False

    G.widgetSetSizeRequest sectionsCombo 130 (-1)
    sectBox <- labelLeftofWidget "Sections: " sectionsCombo False
    -- now pack the boxes at the top
    comboBoxes <- tableWithWidgetList False [avlBox,sectBox] False 4
    G.set comboBoxes [G.tableChildXPadding avlBox G.:= 2]
    -- now pack the bottom bit, omitting the external option for the time being
    mapM_ (\w -> G.boxPackEnd optionsBox w G.PackNatural 3) [lAnalButt,stackButt]
    G.boxPackStart optionsBox chainEntry G.PackNatural 2
    --G.boxPackStart topBox sectBox G.PackGrow 3
    mapM_ (\t -> G.boxPackStart optionsBox t G.PackNatural 2) [addButt, remButt]
    ---
    --------------------------------------------------------
    ------ now get the bottom notebook
    (_,ntbk) <- notebookWithScrollWin False ([] :: [(G.VBox,String)]) False
    -- now handle selection of sections using, placing the chains in the notebook
    let sensAndHandles = (optionsBox,chainEntry,addButt, remButt,lAnalButt )
    G.on sectionsCombo G.changed $ do
        sectComboHandle ntbk indexRef drawRef avlCombo sectionsCombo sensAndHandles
    -- handle for local analysis
    --G.on lAnalButt G.buttonActivated $ lAnalButtHandle drawRef pprms True
    G.on stackButt G.buttonActivated $ lAnalButtHandle drawRef pprms False
    --------------------------------------------------------------------------------------
    --      packing into the box for display
    G.boxPackStart pBox  comboBoxes G.PackNatural 3
    G.boxPackStart pBox  optionsBox G.PackNatural 3
    G.boxPackStart pBox sep G.PackNatural 0
    G.boxPackStart pBox ntbk G.PackGrow 0
    G.widgetShowAll pBox
    where
        handleForCondComboSelection cRef condCombo sectsCombo = do
            -- will need to put options for sections or scehmes here
            mtext <- G.comboBoxGetActiveText condCombo
            case mtext of
                Just text -> do
                    -- add options to the sections combo
                    let defectCR = takeWhile (/= ' ') text
                    let outfile = "./Defects/"++"out"++ defectCR ++".txt"
                    fileExists <- doesFileExist outfile
                    if fileExists then do
                        -- let extractSects    =  map (snd . break isDigit . fst)
                        --let extractSections =  do
                        getSectionsAndSorrogateS outfile >>= clearAdd cRef sectsCombo
                    else do
                        let string = "Data for "++ defectCR ++ " have not been \
                              \extracted. Would you like to extact them now?"
                        --let fileName = (show defect) ++".txt"
                        runDecisionMessageWindow Nothing string (return ())
                Nothing -> return ()
        -- handle for sections combos (need to update the notebook here)
        sectComboHandle ntbk indRef dref avlCombo sectionsCombo opts = do
            --let title = maybe "" id $G.comboBoxGetActiveText avlCombo
            defectCR <- G.comboBoxGetActiveText avlCombo >>= return . maybe "" (takeWhile isAlphaNum)
            let (optsBox,chnEnt,addButt, remButt,lAnalButt ) = opts
            let outFile = "./Defects/"++"out"++ defectCR ++".txt"
            validOption <- doesFileExist outFile
            if validOption then do
                --print "enter valid file"
                mtext <- G.comboBoxGetActiveText sectionsCombo
                case mtext of
                    Just text -> do
                        canvas <- getDrawingCanvas (Just dref)
                        ---------- sensetise and respond to ---------------------
                        G.widgetSetSensitive optsBox True
                        -- handle for add chain
                        G.on addButt G.buttonActivated $ do
                                G.entryGetText chnEnt >>= \s ->
                                    modifyIORef dref (updateAddChain True $ entVal s)
                                G.widgetQueueDraw canvas
                        -- handle for remove chain
                        G.on remButt G.buttonActivated $ do
                                G.entryGetText chnEnt >>= \s ->
                                    modifyIORef dref (updateAddChain False $ entVal s)
                                G.widgetQueueDraw canvas
                        ----------------------------------------------------------

                        let (snm, srg) = span isAlphaNum text
                        let sectSrg' = words srg -- dropWhile (not . isDigit) srg
                        let srg = if length sectSrg' <= 1 then "" else (last sectSrg')
                        --chD <- getSectionData sname srg outFile -- >>= \ -> do -- liftM unzip .
                        (bCD,dds) <- getSectionData snm srg outFile >>= liftM unzip . mapMPair G.buttonNewWithLabel
                        modifyIORef dref (updateDrawData dds)
                        mapM G.buttonGetLabel bCD >>= modifyIORef dref . curryRev updatePtsLabel
                        let title  = defectCR ++ ": "++text
                        modifyIORef dref (updateCaption title)
                        mapM_ (updatePlot canvas dref) (zip bCD [0 .. ])
                        --
                        let ff = onSwith dref
                        G.hBoxNew False 0 >>= add2nbk indRef title ntbk canvas ff dref bCD -- butts
                        --print "not boos houls have been added"
                    Nothing -> print "No selection recorded for sectionCombo"
            else  return ()
            where
                ---
                curryRev :: (a -> b -> c) -> (a -> (b -> c))
                curryRev f  a = f a
                -- actions to do  on a swith page or a delete
                onSwith  ref i  =  do -- switch
                                   dlist <- readIORef drawRefList
                                   modifyIORef ref (\_ -> snd (dlist !! i))
                                   readIORef drawRefList >>= print . show . length
                                   --print ("page: " ++ show i)
                --
                mapMPair :: Monad m => (a -> m b) -> [(a,c)] -> m [(b,c)]
                mapMPair  f xs = sequence [liftM2 (,) (f a) (return c)  | (a,c) <- xs ]
                -- update the values to plot
                updatePlot canvas dref (button, index) =
                    G.on button G.buttonActivated $ do
                        modifyIORef dref (updateCurrChain index)
                        updateDrawingArea canvas dref >> return ()
                --
                setDispFrame widget frame =
                    G.set frame [G.containerBorderWidth G.:= 0, G.frameLabelYAlign G.:= 0.5,
                                G.frameLabelXAlign G.:= 0.5,G.containerChild G.:= widget]
                --
                add2nbk indexRef tabTitle  noteb  canvas ff dref buttons rHBox = do
                    lHBox <-  G.hBoxNew False 0
                    --lVBox <-  G.vBoxNew False 1
                    [chainsFrame,groupsFrame] <- sequence $ replicate 2 G.frameNew
                    vsep   <- G.vSeparatorNew
                    if null buttons then
                        -- message here that there is nothing to add
                        return ()
                    else do
                        buttSclArea <- vScrolledWinWithWgtList buttons VScroll
                        ---
                        G.boxPackStart lHBox buttSclArea G.PackNatural 0
                        G.boxPackStart lHBox vsep G.PackNatural 0
                        G.boxPackEnd lHBox canvas G.PackGrow 1
                        ---
                        let fs = filter ((/= tabTitle) . fst)
                        readIORef dref >>= \dr -> modifyIORef drawRefList ((++ [(tabTitle,dr)]) . fs)
                        ---
                        setDispFrame lHBox chainsFrame
                        --- note the results go in rbox
                        --print "notebook should be added"
                        setDispFrame rHBox groupsFrame
                        hPanedArea  groupsFrame chainsFrame 0 >>=
                            noteBookAddWidget noteb tabTitle indexRef (Just drawRefList) ff
                        G.widgetQueueDraw canvas
        --- handle for local analysis
        lAnalButtHandle :: IORef DrawRef -> PreviewParms -> Bool -> IO ()
        lAnalButtHandle drwRef pprms allSect = do
            [str1,str2] <- mapM G.entryGetText [yrsEnt pprms, distEnt pprms]
            let prt  = wrtFun pprms
            let fromTo from to = myTake to . drop from
            let datYrs a b = if allSect then unzip . map unzip else unzip . map unzip . fromTo a b
            negSlope <- G.toggleButtonGetActive (nSpopes pprms)
            case (validateEntries [str1,str2] ["years","distance"]) of
                Left [e1,e2] -> do
                    -- do the analysis on the selected block
                    dr <- readIORef drwRef
                    --let     n       = lengt (chnLabel dr)
                    let (yr,dst,ns) = (fromIntegral e1, fromIntegral e2,negSlope)
                    let (yrs, dat)  = datYrs (currChain dr) (addChain dr) (drawData dr)
                    let chns        = if allSect then (chnLabel dr) else fromTo (currChain dr) (addChain dr) (chnLabel dr)
                    let title       = caption dr
                    let title'      = filter isAlphaNum title
                    let jt          = Just  ("Analysing "++ title)
                    jtt    <- G.labelNew jt
                    let writr = G.labelSetText jtt
                    let anal        = analyseData drwRef yr  dst ns prt dat yrs chns title'
                    let anal'       = forkProcessWithScroll (Just jtt) writr anal Nothing
                    proceedAfterConsent negSlope title (anal' >> return ())
                Right string ->
                    runMsgDialog Nothing string Error
            where
                ---- need to remove the analysis (should only
                analyseData drwRef yr dist nslp pf daTa yrs chains title = do
                    inputParms <- getInputPrms
                    case inputParms of
                        Right  iprs -> do
                            g <- newStdGen
                            let dpt =  searchDepth iprs     -- search depth
                            let aMx = alignMax iprs     -- maximum number of chains to align
                            let aMn = alignMin iprs     -- minimum number of chains to align
                            let mTd = minTrend  iprs      -- minimum number of points to trend
                            --- use a depth of 5 instead of in excess of 100 for more powerful machines
                            let anl _ = return [] -- mml2DsGD g 100 yr dist (not nslp) aMx aMn mTd pf
                            let resultDir = "./LocalAnalyais"
                            let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
                            let resultFile = resultDir++('/' : title)++".txt"
                            let resultRecFile = resultDir++"/schemeResults.txt"
                            let chainsHeader = L.pack "chains:"-- L.pack "-------CHAINS---------\n"
                            let yearsHeader = L.pack "years:"-- L.pack "-------YEARS---------\n"
                            let rHdr        = L.pack "-------RESULTS--------\n"
                            let chans     = chainsHeader <> (L.pack (printElm chains)) <> (L.pack "\n")
                            --let yrsSS    = L.intercalate (L.pack "\n") $ map (L.pack . printElm) yrs
                            let yrsSS  = (L.pack . printElm) (take 1 yrs)
                            let yrss     = yearsHeader <> yrsSS <> (L.pack "\n")
                            --- debug "./LocalAnalyais/schemeResults.txt"
                            let dataVals = L.pack (printElm $ concat daTa)
                            let dataa = (L.pack "data:") <> dataVals <> (L.pack "\n")
                            print (show $ concat daTa)
                            --print $ show [show dpt, show yr, show dist, show nslp, show aMx, show aMn, show mTd ]
                            -- calculat the results and logg it ----(rHdr <>) .
                            yn <- doesDirectoryExist resultDir
                            if yn then return () else createDirectory resultDir
                            let !prtResults =  ((chans <> yrss) <>) . (dataa <> ) . results2BS'
                            --let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
                            -- print (show anl)
                            anl daTa >>= \rlt -> do
                                (L.writeFile resultFile .  prtResults) rlt
                                (modifyIORef drwRef . omod2derf) rlt
                                let record = L.snoc (L.pack (title )) '\n' --- ++":"++chnn
                                L.appendFile resultRecFile record
                                --addSchemeResults (L.pack title) resultRecFile
                            -- print . show --  mapM_ (L.writeFile resultFile .  prtResults)
                        Left string    -> print ("error reading parameter file: "++string)
                        --- infp for dialog
                proceedAfterConsent ng capt anal = do
                    let mainStr = "You have chosen to analyse "++capt
                    let endStr  = if ng then
                                     ", and have opted to include negative slopes. Are\
                                     \ you sure you want to include negative slopes?"
                                  else
                                     ". Do you wish to proceed?"
                    runDecisionMessageWindow Nothing (mainStr++endStr) anal
                ---
                omod2derf :: [([(OModel, ([Double], [Int]))], [Int])] -> DrawRef  -> DrawRef
                omod2derf   xs  = updateResults rr
                    where ks = concatMap (concatMap (fst . snd) . fst)  xs
                          rr = Results 0 0 0 [] 0 ks []
                --
                addSchemeResults :: L.ByteString -> FilePath -> IO ()
                addSchemeResults result fileName = do
                    -- have to change the result filename so it reflects the chains in the schemeas well
                    schmResults <- L.readFile fileName >>= return . L.lines
                    print "got here"
                    if any (== result) schmResults then
                        return ()
                    else
                        L.appendFile  fileName result
----------------------------------------------------------------------------------------------
--      End of Network Level Dialog Construction and related windows
----------------------------------------------------------------------------------------------}
fillPreviewBox :: G.VBox -> PreviewParms  -> IORef [(String,DrawRef)] -> IO ()
fillPreviewBox pBox pprms drawRefList  = do
    --wrt get the top part: a horizontal box with two combo boxes and
    -- two buttons, as well as a radio button group to choose whether
    -- to view available schemes or sections
    optionsBox <-  G.hBoxNew False 0
    sep <- G.hSeparatorNew
    --[lframe ,rframe] <- sequence . replicate 2 $ G.hBoxNew False 2
    --[schmRButt, sectRButt] <- mapM G.radioButtonNewWithLabel ["Schemes","Sections"]
    --------- **** need handles for schmRButt and  sectRButt
    -- output these buttons in a vertical table
    --rButtstable <- tableWithWidgetList False [schmRButt, sectRButt] True 3
    --
    chainEntry <-  G.entryNew
    mapM_ (\ent -> do
                G.entrySetWidthChars ent 4
                G.entrySetMaxLength ent 4) [chainEntry]
    -- let buttLables = ["Add selection","Show subsections","Show all","Analyse selected subsections"]
    let buttLables = ["Add selection","Show subsections","Add all","Analyse selected subsections"]
    [lAnalButt, addButt, remButt,stackButt] <-  mapM G.buttonNewWithLabel buttLables
    --                         flip (horizontalWidgetList True) False
    G.widgetSetSensitive optionsBox False
    --G.containerAdd rframe rbox
    sectsRef <- newIORef [] -- an IOref for defects to be used by the clearAdd function
    drawRef <- newIORef emptyDrawRwf -- emptyDrawRwf
    indexRef <- newIORef [] -- ^ the indexes in the notebook
    --  HANDLE FOR STAKING -----------
    G.on stackButt G.buttonActivated $ do
        drf <- readIORef drawRef
        let ln = length ( chnLabel drf)
        addedChains <- G.entryGetText chainEntry >>= return . entVal
        if all (> 0) [ln , addedChains] then  do
            let name = caption drf
            let fromTo from to = myTake to . drop from
            let currData = fromTo (currChain drf) (addChain drf) (chnLabel drf)
            let range = " chains" ++ (head currData) ++ " to " ++ last currData
            wrtFun pprms (name ++ range)
        else
            return () -- a message here?
    --avlLabel <- G.labelNew (Just "Available conditions/schemes: ")
    [avlCombo,sectionsCombo] <- sequence $ replicate 2 G.comboBoxNewText
    ----- add options to the avlCombo
    ----- get the list for avlCombo by checking to see what ahs been extracted
    ----- The conditions alaready extracted, but not necessarily, analysed, are added to the list
    ----- The same is done for available schemes
    --let extract = (checkIfExtracted (\_ -> return ())) `seq` getAlreadyExtracted
    getAlreadyExtracted True >>= mapM_ (G.comboBoxAppendText avlCombo)
    G.on avlCombo G.changed $ handleForCondComboSelection sectsRef avlCombo sectionsCombo
    avlBox <- labelLeftofWidget "Extracted: " avlCombo False

    G.widgetSetSizeRequest sectionsCombo 130 (-1)
    sectBox <- labelLeftofWidget "Sections: " sectionsCombo False
    -- now pack the boxes at the top
    comboBoxes <- tableWithWidgetList False [avlBox,sectBox] False 4
    G.set comboBoxes [G.tableChildXPadding avlBox G.:= 2]
    -- now pack the bottom bit, omitting the external option for the time being
    mapM_ (\w -> G.boxPackEnd optionsBox w G.PackNatural 3) [lAnalButt,stackButt]
    G.boxPackStart optionsBox chainEntry G.PackNatural 2
    --G.boxPackStart topBox sectBox G.PackGrow 3
    mapM_ (\t -> G.boxPackStart optionsBox t G.PackNatural 2) [addButt, remButt]
    ---
    --------------------------------------------------------
    ------ now get the bottom notebook
    (_,ntbk) <- notebookWithScrollWin False ([] :: [(G.VBox,String)]) False
    -- now handle selection of sections using, placing the chains in the notebook
    let sensAndHandles = (optionsBox,chainEntry,addButt, remButt,lAnalButt )
    G.on sectionsCombo G.changed $ do
        sectComboHandle ntbk indexRef drawRef avlCombo sectionsCombo sensAndHandles
    -- handle for local analysis
    --G.on lAnalButt G.buttonActivated $ lAnalButtHandle drawRef pprms True
    G.on stackButt G.buttonActivated $ lAnalButtHandle drawRef pprms False
    --------------------------------------------------------------------------------------
    --      packing into the box for display
    G.boxPackStart pBox  comboBoxes G.PackNatural 3
    G.boxPackStart pBox  optionsBox G.PackNatural 3
    G.boxPackStart pBox sep G.PackNatural 0
    G.boxPackStart pBox ntbk G.PackGrow 0
    G.widgetShowAll pBox
    where
        handleForCondComboSelection cRef condCombo sectsCombo = do
            -- will need to put options for sections or scehmes here
            mtext <- G.comboBoxGetActiveText condCombo
            case mtext of
                Just text -> do
                    -- add options to the sections combo
                    let defectCR = takeWhile (/= ' ') text
                    let outfile = "./Defects/"++"out"++ defectCR ++".txt"
                    fileExists <- doesFileExist outfile
                    if fileExists then do
                        -- let extractSects    =  map (snd . break isDigit . fst)
                        --let extractSections =  do
                        getSectionsAndSorrogateS outfile >>= clearAdd cRef sectsCombo
                    else do
                        let string = "Data for "++ defectCR ++ " have not been \
                              \extracted. Would you like to extact them now?"
                        --let fileName = (show defect) ++".txt"
                        runDecisionMessageWindow Nothing string (return ())
                Nothing -> return ()
        -- handle for sections combos (need to update the notebook here)
        sectComboHandle ntbk indRef dref avlCombo sectionsCombo opts = do
            --let title = maybe "" id $G.comboBoxGetActiveText avlCombo
            defectCR <- G.comboBoxGetActiveText avlCombo >>= return . maybe "" (takeWhile isAlphaNum)
            let (optsBox,chnEnt,addButt, remButt,lAnalButt ) = opts
            let outFile = "./Defects/"++"out"++ defectCR ++".txt"
            validOption <- doesFileExist outFile
            if validOption then do
                --print "enter valid file"
                mtext <- G.comboBoxGetActiveText sectionsCombo
                case mtext of
                    Just text -> do
                        canvas <- getDrawingCanvas (Just dref)
                        ---------- sensetise and respond to ---------------------
                        G.widgetSetSensitive optsBox True
                        -- handle for add chain
                        G.on addButt G.buttonActivated $ do
                                G.entryGetText chnEnt >>= \s ->
                                    modifyIORef dref (updateAddChain True $ entVal s)
                                G.widgetQueueDraw canvas
                        -- handle for remove chain
                        G.on remButt G.buttonActivated $ do
                                G.entryGetText chnEnt >>= \s ->
                                    modifyIORef dref (updateAddChain False $ entVal s)
                                G.widgetQueueDraw canvas
                        ----------------------------------------------------------

                        let (snm, srg) = span isAlphaNum text
                        let sectSrg' = words srg -- dropWhile (not . isDigit) srg
                        let srg = if length sectSrg' <= 1 then "" else (last sectSrg')
                        --chD <- getSectionData sname srg outFile -- >>= \ -> do -- liftM unzip .
                        (bCD,dds) <- getSectionData snm srg outFile >>= liftM unzip . mapMPair G.buttonNewWithLabel
                        modifyIORef dref (updateDrawData dds)
                        mapM G.buttonGetLabel bCD >>= modifyIORef dref . curryRev updatePtsLabel
                        let title  = defectCR ++ ": "++text
                        modifyIORef dref (updateCaption title)
                        mapM_ (updatePlot canvas dref) (zip bCD [0 .. ])
                        --
                        let ff = onSwith dref
                        G.hBoxNew False 0 >>= add2nbk indRef title ntbk canvas ff dref bCD -- butts
                        --print "not boos houls have been added"
                    Nothing -> print "No selection recorded for sectionCombo"
            else  return ()
            where
                ---
                curryRev :: (a -> b -> c) -> (a -> (b -> c))
                curryRev f  a = f a
                -- actions to do  on a swith page or a delete
                onSwith  ref i  =  do -- switch
                                   dlist <- readIORef drawRefList
                                   modifyIORef ref (\_ -> snd (dlist !! i))
                                   readIORef drawRefList >>= print . show . length
                                   --print ("page: " ++ show i)
                --
                mapMPair :: Monad m => (a -> m b) -> [(a,c)] -> m [(b,c)]
                mapMPair  f xs = sequence [liftM2 (,) (f a) (return c)  | (a,c) <- xs ]
                -- update the values to plot
                updatePlot canvas dref (button, index) =
                    G.on button G.buttonActivated $ do
                        modifyIORef dref (updateCurrChain index)
                        updateDrawingArea canvas dref >> return ()
                --
                setDispFrame widget frame =
                    G.set frame [G.containerBorderWidth G.:= 0, G.frameLabelYAlign G.:= 0.5,
                                G.frameLabelXAlign G.:= 0.5,G.containerChild G.:= widget]
                --
                add2nbk indexRef tabTitle  noteb  canvas ff dref buttons rHBox = do
                    lHBox <-  G.hBoxNew False 0
                    --lVBox <-  G.vBoxNew False 1
                    [chainsFrame,groupsFrame] <- sequence $ replicate 2 G.frameNew
                    vsep   <- G.vSeparatorNew
                    if null buttons then
                        -- message here that there is nothing to add
                        return ()
                    else do
                        buttSclArea <- vScrolledWinWithWgtList buttons VScroll
                        ---
                        G.boxPackStart lHBox buttSclArea G.PackNatural 0
                        G.boxPackStart lHBox vsep G.PackNatural 0
                        G.boxPackEnd lHBox canvas G.PackGrow 1
                        ---
                        let fs = filter ((/= tabTitle) . fst)
                        readIORef dref >>= \dr -> modifyIORef drawRefList ((++ [(tabTitle,dr)]) . fs)
                        ---
                        setDispFrame lHBox chainsFrame
                        --- note the results go in rbox
                        --print "notebook should be added"
                        setDispFrame rHBox groupsFrame
                        hPanedArea  groupsFrame chainsFrame 0 >>=
                            noteBookAddWidget noteb tabTitle indexRef (Just drawRefList) ff
                        G.widgetQueueDraw canvas
        --- handle for local analysis
        lAnalButtHandle :: IORef DrawRef -> PreviewParms -> Bool -> IO ()
        lAnalButtHandle drwRef pprms allSect = do
            [str1,str2] <- mapM G.entryGetText [yrsEnt pprms, distEnt pprms]
            let prt  = wrtFun pprms
            let fromTo from to = myTake to . drop from
            let datYrs a b = if allSect then unzip . map unzip else unzip . map unzip . fromTo a b
            negSlope <- G.toggleButtonGetActive (nSpopes pprms)
            case (validateEntries [str1,str2] ["years","distance"]) of
                Left [e1,e2] -> do
                    -- do the analysis on the selected block
                    dr <- readIORef drwRef
                    --let     n       = lengt (chnLabel dr)
                    let (yr,dst,ns) = (fromIntegral e1, fromIntegral e2,negSlope)
                    let (yrs, dat)  = datYrs (currChain dr) (addChain dr) (drawData dr)
                    let chns        = if allSect then (chnLabel dr) else fromTo (currChain dr) (addChain dr) (chnLabel dr)
                    let title       = caption dr
                    let title'      = filter isAlphaNum title
                    let jt          = Just  ("Analysing "++ title)
                    jtt    <- G.labelNew jt
                    let writr = G.labelSetText jtt
                    let anal        = analyseData drwRef yr  dst ns prt dat yrs chns title'
                    let anal'       = forkProcessWithScroll (Just jtt) writr anal Nothing
                    proceedAfterConsent negSlope title (anal' >> return ())
                Right string ->
                    runMsgDialog Nothing string Error
            where
                ---- need to remove the analysis (should only
                analyseData drwRef yr dist nslp pf daTa yrs chains title = do
                    inputParms <- getInputPrms
                    case inputParms of
                        Right  iprs -> do
                            g <- newStdGen
                            let dpt =  searchDepth iprs     -- search depth
                            let aMx = alignMax iprs     -- maximum number of chains to align
                            let aMn = alignMin iprs     -- minimum number of chains to align
                            let mTd = minTrend  iprs      -- minimum number of points to trend
                            --- use a depth of 5 instead of in excess of 100 for more powerful machines
                            let anl _ = return [] -- mml2DsGD g 100 yr dist (not nslp) aMx aMn mTd pf
                            let resultDir = "./LocalAnalyais"
                            let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
                            let resultFile = resultDir++('/' : title)++".txt"
                            let resultRecFile = resultDir++"/schemeResults.txt"
                            let chainsHeader = L.pack "chains:"-- L.pack "-------CHAINS---------\n"
                            let yearsHeader = L.pack "years:"-- L.pack "-------YEARS---------\n"
                            let rHdr        = L.pack "-------RESULTS--------\n"
                            let chans     = chainsHeader <> (L.pack (printElm chains)) <> (L.pack "\n")
                            --let yrsSS    = L.intercalate (L.pack "\n") $ map (L.pack . printElm) yrs
                            let yrsSS  = (L.pack . printElm) (take 1 yrs)
                            let yrss     = yearsHeader <> yrsSS <> (L.pack "\n")
                            --- debug "./LocalAnalyais/schemeResults.txt"
                            let dataVals = L.pack (printElm $ concat daTa)
                            let dataa = (L.pack "data:") <> dataVals <> (L.pack "\n")
                            print (show $ concat daTa)
                            --print $ show [show dpt, show yr, show dist, show nslp, show aMx, show aMn, show mTd ]
                            -- calculat the results and logg it ----(rHdr <>) .
                            yn <- doesDirectoryExist resultDir
                            if yn then return () else createDirectory resultDir
                            let !prtResults =  ((chans <> yrss) <>) . (dataa <> ) . results2BS'
                            --let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
                            -- print (show anl)
                            anl daTa >>= \rlt -> do
                                (L.writeFile resultFile .  prtResults) rlt
                                (modifyIORef drwRef . omod2derf) rlt
                                let record = L.snoc (L.pack (title )) '\n' --- ++":"++chnn
                                L.appendFile resultRecFile record
                                --addSchemeResults (L.pack title) resultRecFile
                            -- print . show --  mapM_ (L.writeFile resultFile .  prtResults)
                        Left string    -> print ("error reading parameter file: "++string)
                        --- infp for dialog
                proceedAfterConsent ng capt anal = do
                    let mainStr = "You have chosen to analyse "++capt
                    let endStr  = if ng then
                                     ", and have opted to include negative slopes. Are\
                                     \ you sure you want to include negative slopes?"
                                  else
                                     ". Do you wish to proceed?"
                    runDecisionMessageWindow Nothing (mainStr++endStr) anal
                ---
                omod2derf :: [([(OModel, ([Double], [Int]))], [Int])] -> DrawRef  -> DrawRef
                omod2derf   xs  = updateResults rr
                    where ks = concatMap (concatMap (fst . snd) . fst)  xs
                          rr = Results 0 0 0 [] 0 ks []
                --
                addSchemeResults :: L.ByteString -> FilePath -> IO ()
                addSchemeResults result fileName = do
                    -- have to change the result filename so it reflects the chains in the schemeas well
                    schmResults <- L.readFile fileName >>= return . L.lines
                    print "got here"
                    if any (== result) schmResults then
                        return ()
                    else
                        L.appendFile  fileName result
----------------------------------------------------------------------------------------------
--      End of Network Level Dialog Construction and related windows
----------------------------------------------------------------------------------------------}
fillPreviewBox pBox pprms drawRefList  = do
    --wrt get the top part: a horizontal box with two combo boxes and
    -- two buttons, as well as a radio button group to choose whether
    -- to view available schemes or sections
    optionsBox <-  G.hBoxNew False 0
    sep <- G.hSeparatorNew
    --[lframe ,rframe] <- sequence . replicate 2 $ G.hBoxNew False 2
    --[schmRButt, sectRButt] <- mapM G.radioButtonNewWithLabel ["Schemes","Sections"]
    --------- **** need handles for schmRButt and  sectRButt
    -- output these buttons in a vertical table
    --rButtstable <- tableWithWidgetList False [schmRButt, sectRButt] True 3
    --
    chainEntry <-  G.entryNew
    mapM_ (\ent -> do
                G.entrySetWidthChars ent 4
                G.entrySetMaxLength ent 4) [chainEntry]
    -- let buttLables = ["Add selection","Show subsections","Show all","Analyse selected subsections"]
    let buttLables = ["Add selection","Show subsections","Add all","Analyse selected subsections"]
    [lAnalButt, addButt, remButt,stackButt] <-  mapM G.buttonNewWithLabel buttLables
    --                         flip (horizontalWidgetList True) False
    G.widgetSetSensitive optionsBox False
    --G.containerAdd rframe rbox
    sectsRef <- newIORef [] -- an IOref for defects to be used by the clearAdd function
    drawRef <- newIORef emptyDrawRwf -- emptyDrawRwf
    indexRef <- newIORef [] -- ^ the indexes in the notebook
    --  HANDLE FOR STAKING -----------
    G.on stackButt G.buttonActivated $ do
        drf <- readIORef drawRef
        let ln = length ( chnLabel drf)
        addedChains <- G.entryGetText chainEntry >>= return . entVal
        if all (> 0) [ln , addedChains] then  do
            let name = caption drf
            let fromTo from to = myTake to . drop from
            let currData = fromTo (currChain drf) (addChain drf) (chnLabel drf)
            let range = " chains" ++ (head currData) ++ " to " ++ last currData
            wrtFun pprms (name ++ range)
        else
            return () -- a message here?
    --avlLabel <- G.labelNew (Just "Available conditions/schemes: ")
    [avlCombo,sectionsCombo] <- sequence $ replicate 2 G.comboBoxNewText
    ----- add options to the avlCombo
    ----- get the list for avlCombo by checking to see what ahs been extracted
    ----- The conditions alaready extracted, but not necessarily, analysed, are added to the list
    ----- The same is done for available schemes
    --let extract = (checkIfExtracted (\_ -> return ())) `seq` getAlreadyExtracted
    getAlreadyExtracted True >>= mapM_ (G.comboBoxAppendText avlCombo)
    G.on avlCombo G.changed $ handleForCondComboSelection sectsRef avlCombo sectionsCombo
    avlBox <- labelLeftofWidget "Extracted: " avlCombo False

    G.widgetSetSizeRequest sectionsCombo 130 (-1)
    sectBox <- labelLeftofWidget "Sections: " sectionsCombo False
    -- now pack the boxes at the top
    comboBoxes <- tableWithWidgetList False [avlBox,sectBox] False 4
    G.set comboBoxes [G.tableChildXPadding avlBox G.:= 2]
    -- now pack the bottom bit, omitting the external option for the time being
    mapM_ (\w -> G.boxPackEnd optionsBox w G.PackNatural 3) [lAnalButt,stackButt]
    G.boxPackStart optionsBox chainEntry G.PackNatural 2
    --G.boxPackStart topBox sectBox G.PackGrow 3
    mapM_ (\t -> G.boxPackStart optionsBox t G.PackNatural 2) [addButt, remButt]
    ---
    --------------------------------------------------------
    ------ now get the bottom notebook
    (_,ntbk) <- notebookWithScrollWin False ([] :: [(G.VBox,String)]) False
    -- now handle selection of sections using, placing the chains in the notebook
    let sensAndHandles = (optionsBox,chainEntry,addButt, remButt,lAnalButt )
    G.on sectionsCombo G.changed $ do
        sectComboHandle ntbk indexRef drawRef avlCombo sectionsCombo sensAndHandles
    -- handle for local analysis
    --G.on lAnalButt G.buttonActivated $ lAnalButtHandle drawRef pprms True
    G.on stackButt G.buttonActivated $ lAnalButtHandle drawRef pprms False
    --------------------------------------------------------------------------------------
    --      packing into the box for display
    G.boxPackStart pBox  comboBoxes G.PackNatural 3
    G.boxPackStart pBox  optionsBox G.PackNatural 3
    G.boxPackStart pBox sep G.PackNatural 0
    G.boxPackStart pBox ntbk G.PackGrow 0
    G.widgetShowAll pBox
    where
        handleForCondComboSelection cRef condCombo sectsCombo = do
            -- will need to put options for sections or scehmes here
            mtext <- G.comboBoxGetActiveText condCombo
            case mtext of
                Just text -> do
                    -- add options to the sections combo
                    let defectCR = takeWhile (/= ' ') text
                    let outfile = "./Defects/"++"out"++ defectCR ++".txt"
                    fileExists <- doesFileExist outfile
                    if fileExists then do
                        -- let extractSects    =  map (snd . break isDigit . fst)
                        --let extractSections =  do
                        getSectionsAndSorrogateS outfile >>= clearAdd cRef sectsCombo
                    else do
                        let string = "Data for "++ defectCR ++ " have not been \
                              \extracted. Would you like to extact them now?"
                        --let fileName = (show defect) ++".txt"
                        runDecisionMessageWindow Nothing string (return ())
                Nothing -> return ()
        -- handle for sections combos (need to update the notebook here)
        sectComboHandle ntbk indRef dref avlCombo sectionsCombo opts = do
            --let title = maybe "" id $G.comboBoxGetActiveText avlCombo
            defectCR <- G.comboBoxGetActiveText avlCombo >>= return . maybe "" (takeWhile isAlphaNum)
            let (optsBox,chnEnt,addButt, remButt,lAnalButt ) = opts
            let outFile = "./Defects/"++"out"++ defectCR ++".txt"
            validOption <- doesFileExist outFile
            if validOption then do
                --print "enter valid file"
                mtext <- G.comboBoxGetActiveText sectionsCombo
                case mtext of
                    Just text -> do
                        canvas <- getDrawingCanvas (Just dref)
                        ---------- sensetise and respond to ---------------------
                        G.widgetSetSensitive optsBox True
                        -- handle for add chain
                        G.on addButt G.buttonActivated $ do
                                G.entryGetText chnEnt >>= \s ->
                                    modifyIORef dref (updateAddChain True $ entVal s)
                                G.widgetQueueDraw canvas
                        -- handle for remove chain
                        G.on remButt G.buttonActivated $ do
                                G.entryGetText chnEnt >>= \s ->
                                    modifyIORef dref (updateAddChain False $ entVal s)
                                G.widgetQueueDraw canvas
                        ----------------------------------------------------------

                        let (snm, srg) = span isAlphaNum text
                        let sectSrg' = words srg -- dropWhile (not . isDigit) srg
                        let srg = if length sectSrg' <= 1 then "" else (last sectSrg')
                        --chD <- getSectionData sname srg outFile -- >>= \ -> do -- liftM unzip .
                        (bCD,dds) <- getSectionData snm srg outFile >>= liftM unzip . mapMPair G.buttonNewWithLabel
                        modifyIORef dref (updateDrawData dds)
                        mapM G.buttonGetLabel bCD >>= modifyIORef dref . curryRev updatePtsLabel
                        let title  = defectCR ++ ": "++text
                        modifyIORef dref (updateCaption title)
                        mapM_ (updatePlot canvas dref) (zip bCD [0 .. ])
                        --
                        let ff = onSwith dref
                        G.hBoxNew False 0 >>= add2nbk indRef title ntbk canvas ff dref bCD -- butts
                        --print "not boos houls have been added"
                    Nothing -> print "No selection recorded for sectionCombo"
            else  return ()
            where
                ---
                curryRev :: (a -> b -> c) -> (a -> (b -> c))
                curryRev f  a = f a
                -- actions to do  on a swith page or a delete
                onSwith  ref i  =  do -- switch
                                   dlist <- readIORef drawRefList
                                   modifyIORef ref (\_ -> snd (dlist !! i))
                                   readIORef drawRefList >>= print . show . length
                                   --print ("page: " ++ show i)
                --
                mapMPair :: Monad m => (a -> m b) -> [(a,c)] -> m [(b,c)]
                mapMPair  f xs = sequence [liftM2 (,) (f a) (return c)  | (a,c) <- xs ]
                -- update the values to plot
                updatePlot canvas dref (button, index) =
                    G.on button G.buttonActivated $ do
                        modifyIORef dref (updateCurrChain index)
                        updateDrawingArea canvas dref >> return ()
                --
                setDispFrame widget frame =
                    G.set frame [G.containerBorderWidth G.:= 0, G.frameLabelYAlign G.:= 0.5,
                                G.frameLabelXAlign G.:= 0.5,G.containerChild G.:= widget]
                --
                add2nbk indexRef tabTitle  noteb  canvas ff dref buttons rHBox = do
                    lHBox <-  G.hBoxNew False 0
                    --lVBox <-  G.vBoxNew False 1
                    [chainsFrame,groupsFrame] <- sequence $ replicate 2 G.frameNew
                    vsep   <- G.vSeparatorNew
                    if null buttons then
                        -- message here that there is nothing to add
                        return ()
                    else do
                        buttSclArea <- vScrolledWinWithWgtList buttons VScroll
                        ---
                        G.boxPackStart lHBox buttSclArea G.PackNatural 0
                        G.boxPackStart lHBox vsep G.PackNatural 0
                        G.boxPackEnd lHBox canvas G.PackGrow 1
                        ---
                        let fs = filter ((/= tabTitle) . fst)
                        readIORef dref >>= \dr -> modifyIORef drawRefList ((++ [(tabTitle,dr)]) . fs)
                        ---
                        setDispFrame lHBox chainsFrame
                        --- note the results go in rbox
                        --print "notebook should be added"
                        setDispFrame rHBox groupsFrame
                        hPanedArea  groupsFrame chainsFrame 0 >>=
                            noteBookAddWidget noteb tabTitle indexRef (Just drawRefList) ff
                        G.widgetQueueDraw canvas
        --- handle for local analysis
        lAnalButtHandle :: IORef DrawRef -> PreviewParms -> Bool -> IO ()
        lAnalButtHandle drwRef pprms allSect = do
            [str1,str2] <- mapM G.entryGetText [yrsEnt pprms, distEnt pprms]
            let prt  = wrtFun pprms
            let fromTo from to = myTake to . drop from
            let datYrs a b = if allSect then unzip . map unzip else unzip . map unzip . fromTo a b
            negSlope <- G.toggleButtonGetActive (nSpopes pprms)
            case (validateEntries [str1,str2] ["years","distance"]) of
                Left [e1,e2] -> do
                    -- do the analysis on the selected block
                    dr <- readIORef drwRef
                    --let     n       = lengt (chnLabel dr)
                    let (yr,dst,ns) = (fromIntegral e1, fromIntegral e2,negSlope)
                    let (yrs, dat)  = datYrs (currChain dr) (addChain dr) (drawData dr)
                    let chns        = if allSect then (chnLabel dr) else fromTo (currChain dr) (addChain dr) (chnLabel dr)
                    let title       = caption dr
                    let title'      = filter isAlphaNum title
                    let jt          = Just  ("Analysing "++ title)
                    jtt    <- G.labelNew jt
                    let writr = G.labelSetText jtt
                    let anal        = analyseData drwRef yr  dst ns prt dat yrs chns title'
                    let anal'       = forkProcessWithScroll (Just jtt) writr anal Nothing
                    proceedAfterConsent negSlope title (anal' >> return ())
                Right string ->
                    runMsgDialog Nothing string Error
            where
                ---- need to remove the analysis (should only
                analyseData drwRef yr dist nslp pf daTa yrs chains title = do
                    inputParms <- getInputPrms
                    case inputParms of
                        Right  iprs -> do
                            g <- newStdGen
                            let dpt =  searchDepth iprs     -- search depth
                            let aMx = alignMax iprs     -- maximum number of chains to align
                            let aMn = alignMin iprs     -- minimum number of chains to align
                            let mTd = minTrend  iprs      -- minimum number of points to trend
                            --- use a depth of 5 instead of in excess of 100 for more powerful machines
                            let anl _ = return [] -- mml2DsGD g 100 yr dist (not nslp) aMx aMn mTd pf
                            let resultDir = "./LocalAnalyais"
                            let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
                            let resultFile = resultDir++('/' : title)++".txt"
                            let resultRecFile = resultDir++"/schemeResults.txt"
                            let chainsHeader = L.pack "chains:"-- L.pack "-------CHAINS---------\n"
                            let yearsHeader = L.pack "years:"-- L.pack "-------YEARS---------\n"
                            let rHdr        = L.pack "-------RESULTS--------\n"
                            let chans     = chainsHeader <> (L.pack (printElm chains)) <> (L.pack "\n")
                            --let yrsSS    = L.intercalate (L.pack "\n") $ map (L.pack . printElm) yrs
                            let yrsSS  = (L.pack . printElm) (take 1 yrs)
                            let yrss     = yearsHeader <> yrsSS <> (L.pack "\n")
                            --- debug "./LocalAnalyais/schemeResults.txt"
                            let dataVals = L.pack (printElm $ concat daTa)
                            let dataa = (L.pack "data:") <> dataVals <> (L.pack "\n")
                            print (show $ concat daTa)
                            --print $ show [show dpt, show yr, show dist, show nslp, show aMx, show aMn, show mTd ]
                            -- calculat the results and logg it ----(rHdr <>) .
                            yn <- doesDirectoryExist resultDir
                            if yn then return () else createDirectory resultDir
                            let !prtResults =  ((chans <> yrss) <>) . (dataa <> ) . results2BS'
                            --let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
                            -- print (show anl)
                            anl daTa >>= \rlt -> do
                                (L.writeFile resultFile .  prtResults) rlt
                                (modifyIORef drwRef . omod2derf) rlt
                                let record = L.snoc (L.pack (title )) '\n' --- ++":"++chnn
                                L.appendFile resultRecFile record
                                --addSchemeResults (L.pack title) resultRecFile
                            -- print . show --  mapM_ (L.writeFile resultFile .  prtResults)
                        Left string    -> print ("error reading parameter file: "++string)
                        --- infp for dialog
                proceedAfterConsent ng capt anal = do
                    let mainStr = "You have chosen to analyse "++capt
                    let endStr  = if ng then
                                     ", and have opted to include negative slopes. Are\
                                     \ you sure you want to include negative slopes?"
                                  else
                                     ". Do you wish to proceed?"
                    runDecisionMessageWindow Nothing (mainStr++endStr) anal
                ---
                omod2derf :: [([(OModel, ([Double], [Int]))], [Int])] -> DrawRef  -> DrawRef
                omod2derf   xs  = updateResults rr
                    where ks = concatMap (concatMap (fst . snd) . fst)  xs
                          rr = Results 0 0 0 [] 0 ks []
                --
                addSchemeResults :: L.ByteString -> FilePath -> IO ()
                addSchemeResults result fileName = do
                    -- have to change the result filename so it reflects the chains in the schemeas well
                    schmResults <- L.readFile fileName >>= return . L.lines
                    print "got here"
                    if any (== result) schmResults then
                        return ()
                    else
                        L.appendFile  fileName result
----------------------------------------------------------------------------------------------
--      End of Network Level Dialog Construction and related windows
----------------------------------------------------------------------------------------------}