// $Id: gc_phylip.cpp,v 1.30 2018/01/03 21:32:56 mkkuhner Exp $

/*
Copyright 2002-2005 Mary K. Kuhner, Peter Beerli, and Joseph Felsenstein

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

/* Authors: Mary Kuhner, Jon Yamato, and Joseph Felsenstein */


#include <cassert>

#include "gc_errhandling.h"
#include "gc_data.h"                // for ToWxString
#include "gc_datastore.h"
#include "gc_default.h"             // for gcdefault::migrateSequenceNameLength
#include "gc_file.h"
#include "gc_file_util.h"
#include "gc_infile_err.h"
#include "gc_parse_block.h"
#include "gc_phylip.h"
#include "gc_strings.h"
#include "gc_strings_parse.h"

#include "wx/log.h"
#include "wx/tokenzr.h"
#include "wx/txtstrm.h"
#include "wx/wfstream.h"

//------------------------------------------------------------------------------------

GCPhylipParser::GCPhylipParser(const GCDataStore& ds)
    :   GCParser(ds)
{
}

GCPhylipParser::~GCPhylipParser()
{
}

void
GCPhylipParser::ParseTopPhylipLine(  size_t* numSequences,
                                     size_t* numSites,
                                     bool* hasWeights)
{
    assert(m_textStreamPointer != NULL);
    wxString line = ReadLine();
    wxStringTokenizer tokenizer(line);

    wxString sequenceString = tokenizer.GetNextToken();
    wxString siteString     = tokenizer.GetNextToken();

    long longVal;
    if(!sequenceString.ToLong(&longVal))
    {
        throw gc_phylip_first_token(sequenceString);
    }
    if(longVal <= 0)
    {
        throw gc_phylip_first_token(sequenceString);
    }
    *numSequences = (size_t)longVal;

    if(!siteString.ToLong(&longVal))
    {
        throw gc_phylip_second_token(siteString);
    }
    if(longVal <= 0)
    {
        throw gc_phylip_second_token(siteString);
    }
    *numSites = (size_t)longVal;

    *hasWeights = false;
    if(tokenizer.HasMoreTokens())
    {
        wxString weightToken = tokenizer.GetNextToken();
        if(weightToken.CmpNoCase("w") == 0) *hasWeights = true;
    }
}

bool
GCPhylipParser::ParsePhylipWeightsLine(size_t numSites, wxString fileName)
// we don't do anything with this information, but
// we need to make sure we skip over all of it.
{
    wxLogMessage(gcerr_parse::ignoringPhylipWeights,fileName.c_str());
    wxString line = ReadLine();
    wxString label = line.Left(gcdefault::migrateSequenceNameLength);
    wxString data  = line.Remove(0,gcdefault::migrateSequenceNameLength);

    // remove any whitespace characters from data
    data.Replace(" ","",true);
    data.Replace("\t","",true);

    while (data.Length() < numSites)
    {
        line = ReadLine();
        line.Replace(" ","",true);
        line.Replace("\t","",true);
        data += line;
    }

    return true;
}

GCParse *
GCPhylipParser::Parse(GCFile & fileRef, gcGeneralDataType dataTypes, GCInterleaving interleaving)
{
    SetUpStreams(fileRef.GetName());
    GCParse & parseData = MakeParse(fileRef,format_PHYLIP,dataTypes,interleaving);

    try
    {
        size_t numSequences;
        size_t numSites;
        bool hasWeights;

        ParseTopPhylipLine(&numSequences,&numSites,&hasWeights);
        if(hasWeights)
            // skipping this line
        {
            ParsePhylipWeightsLine(numSites,fileRef.GetName());
        }

        AddPop(parseData,0,wxEmptyString); // no pop names in phylip
        AddLocus(parseData,0,numSites);
        FillData(parseData,0,0,interleaving,numSequences);
        CheckNoExtraData();
        return &parseData;
    }
    catch(gc_infile_err& e)
    {
        delete &parseData;
        e.setFile(fileRef.GetName());
        e.setRow(m_linesRead);
        throw;
    }
    catch(gc_eof& f)
    {
        if(CompleteParse(parseData))
        {
            return &parseData;
        }
        else
        {
            delete &parseData;
            f.setFile(fileRef.GetName());
            throw;
        }
    }

    assert(false);
    return NULL;
}

bool
GCPhylipParser::CompleteParse(GCParse& parseData)
{
    // check we have a pop
    size_t pcount = parseData.GetPopCount();
    if(pcount != 1) return false;
    const GCParsePop & pop = parseData.GetParsePop(0);

    // Silence compiler warning about unrefereced variable.
    (void)pop;

    // check we have a locus
    size_t lcount = parseData.GetLociCount();
    if(lcount != 1) return false;
    //const GCParseLocus & loc = parseData.GetParseLocus(0);

    // check we have a single block
    constBlockVector blocks = parseData.GetBlocks();
    if(blocks.size() != 1) return false;

    // check block has correct number of sequences
    const GCParseBlock * blockP = blocks[0];
    if(blockP == NULL) return false;
    size_t expectedNumSequences = blockP->GetExpectedNumSequences();
    const GCParseSamples & samples = blockP->GetSamples();
    if(samples.size() != expectedNumSequences) return false;

    // check block has correct number of sites
    if(blockP->HasIncompleteSequences()) return false;

    return true;
}

//____________________________________________________________________________________
