library(reshape2)
library(stringr)

# Function that writes copynumber package segmentations as IGV-readable CBS-style .seg short files
write.seg <- function(segments, filename, cluster=TRUE)
{
  stopifnot(str_detect(filename, '\\.seg$'))
  segmeans <- segments[,-(1:5)]
  # Order using hclust
  if (cluster) segmeans <- segmeans[,hclust(dist(t(segmeans)))$order] 
  # Information for seg file in column format
  uber.df <- cbind(segments[,c('chrom', 'start.pos', 'end.pos', 'n.probes')], segmeans)
  # Segfile (defined https://www.broadinstitute.org/software/igv/SEG)
  segfile.wrong.col.order <- melt(uber.df,
                                  id.vars=c('chrom', 'start.pos', 'end.pos', 'n.probes'),
                                  variable.name='ID', value.name='seg.mean')
  segfile <- segfile.wrong.col.order[,c('ID', 'chrom', 'start.pos', 'end.pos', 'n.probes', 'seg.mean')]
  # Write to file
  write.table(segfile, file=filename, col.names=FALSE, row.names=FALSE, sep='\t', quote=FALSE)  
}